bevy_ecs/world/mod.rs
1#![expect(
2 unsafe_op_in_unsafe_fn,
3 reason = "See #11590. To be removed once all applicable unsafe code has an unsafe block with a safety comment."
4)]
5
6//! Defines the [`World`] and APIs for accessing it directly.
7
8pub(crate) mod command_queue;
9mod deferred_world;
10mod entity_access;
11mod entity_fetch;
12mod filtered_resource;
13mod identifier;
14mod spawn_batch;
15
16pub mod error;
17#[cfg(feature = "bevy_reflect")]
18pub mod reflect;
19pub mod unsafe_world_cell;
20
21pub use crate::{
22 change_detection::{Mut, Ref, CHECK_TICK_THRESHOLD},
23 world::command_queue::CommandQueue,
24};
25pub use bevy_ecs_macros::FromWorld;
26pub use deferred_world::DeferredWorld;
27pub use entity_access::{
28 ComponentEntry, DynamicComponentFetch, EntityMut, EntityMutExcept, EntityRef, EntityRefExcept,
29 EntityWorldMut, FilteredEntityMut, FilteredEntityRef, OccupiedComponentEntry,
30 TryFromFilteredError, UnsafeFilteredEntityMut, VacantComponentEntry,
31};
32pub use entity_fetch::{EntityFetcher, WorldEntityFetch};
33pub use filtered_resource::*;
34pub use identifier::WorldId;
35pub use spawn_batch::*;
36
37use crate::{
38 archetype::{ArchetypeId, Archetypes},
39 bundle::{
40 Bundle, BundleId, BundleInfo, BundleInserter, BundleSpawner, Bundles, DynamicBundle,
41 InsertMode, NoBundleEffect,
42 },
43 change_detection::{
44 CheckChangeTicks, ComponentTicks, ComponentTicksMut, MaybeLocation, MutUntyped, Tick,
45 },
46 component::{
47 Component, ComponentDescriptor, ComponentId, ComponentIds, ComponentInfo, Components,
48 ComponentsQueuedRegistrator, ComponentsRegistrator, Mutable, RequiredComponents,
49 RequiredComponentsError,
50 },
51 entity::{Entities, Entity, EntityAllocator, EntityNotSpawnedError, SpawnError},
52 entity_disabling::DefaultQueryFilters,
53 error::{ErrorHandler, FallbackErrorHandler},
54 lifecycle::{ComponentHooks, RemovedComponentMessages, ADD, DESPAWN, DISCARD, INSERT, REMOVE},
55 message::{Message, MessageId, Messages, WriteBatchIds},
56 observer::Observers,
57 prelude::{Add, Despawn, Discard, Insert, Remove},
58 query::{DebugCheckedUnwrap, QueryData, QueryFilter, QueryState},
59 relationship::RelationshipHookMode,
60 resource::{IsResource, Resource, ResourceEntities, IS_RESOURCE},
61 schedule::{Schedule, ScheduleLabel, Schedules},
62 storage::{NonSendData, Storages},
63 system::Commands,
64 world::{
65 command_queue::RawCommandQueue,
66 error::{
67 EntityDespawnError, EntityMutableFetchError, TryInsertBatchError, TryRunScheduleError,
68 },
69 },
70};
71use alloc::{boxed::Box, vec::Vec};
72use bevy_platform::sync::atomic::{AtomicU32, Ordering};
73use bevy_ptr::{move_as_ptr, MovingPtr, OwningPtr, Ptr};
74use bevy_utils::prelude::DebugName;
75use core::{any::TypeId, fmt, mem::ManuallyDrop};
76use log::warn;
77use unsafe_world_cell::{UnsafeEntityCell, UnsafeWorldCell};
78
79/// Stores and exposes operations on [entities](Entity), [components](Component), resources,
80/// and their associated metadata.
81///
82/// Each [`Entity`] has a set of unique components, based on their type.
83/// Entity components can be created, updated, removed, and queried using a given [`World`].
84///
85/// For complex access patterns involving [`SystemParam`](crate::system::SystemParam),
86/// consider using [`SystemState`](crate::system::SystemState).
87///
88/// To mutate different parts of the world simultaneously,
89/// use [`World::resource_scope`] or [`SystemState`](crate::system::SystemState).
90///
91/// ## Resources
92///
93/// Worlds can also store [`Resource`]s,
94/// which are unique instances of a given type that belong to a specific unique Entity.
95/// There are also *non send resources*, which can only be accessed on the main thread.
96/// These are stored outside of the ECS.
97/// See [`Resource`] for usage.
98pub struct World {
99 id: WorldId,
100 pub(crate) entities: Entities,
101 pub(crate) entity_allocator: EntityAllocator,
102 pub(crate) components: Components,
103 pub(crate) component_ids: ComponentIds,
104 pub(crate) resource_entities: ResourceEntities,
105 pub(crate) archetypes: Archetypes,
106 pub(crate) storages: Storages,
107 pub(crate) bundles: Bundles,
108 pub(crate) observers: Observers,
109 pub(crate) removed_components: RemovedComponentMessages,
110 pub(crate) change_tick: AtomicU32,
111 pub(crate) last_change_tick: Tick,
112 pub(crate) last_check_tick: Tick,
113 pub(crate) last_trigger_id: u32,
114 pub(crate) command_queue: RawCommandQueue,
115}
116
117impl Default for World {
118 fn default() -> Self {
119 let mut world = Self {
120 id: WorldId::new().expect("More `bevy` `World`s have been created than is supported"),
121 entities: Entities::new(),
122 entity_allocator: EntityAllocator::default(),
123 components: Default::default(),
124 resource_entities: Default::default(),
125 archetypes: Archetypes::new(),
126 storages: Default::default(),
127 bundles: Default::default(),
128 observers: Observers::default(),
129 removed_components: Default::default(),
130 // Default value is `1`, and `last_change_tick`s default to `0`, such that changes
131 // are detected on first system runs and for direct world queries.
132 change_tick: AtomicU32::new(1),
133 last_change_tick: Tick::new(0),
134 last_check_tick: Tick::new(0),
135 last_trigger_id: 0,
136 command_queue: RawCommandQueue::new(),
137 component_ids: ComponentIds::default(),
138 };
139 world.bootstrap();
140 world
141 }
142}
143
144impl Drop for World {
145 fn drop(&mut self) {
146 // SAFETY: Not passing a pointer so the argument is always valid
147 unsafe { self.command_queue.apply_or_drop_queued(None) };
148 // SAFETY: Pointers in internal command queue are only invalidated here
149 drop(unsafe { Box::from_raw(self.command_queue.bytes.as_ptr()) });
150 // SAFETY: Pointers in internal command queue are only invalidated here
151 drop(unsafe { Box::from_raw(self.command_queue.cursor.as_ptr()) });
152 // SAFETY: Pointers in internal command queue are only invalidated here
153 drop(unsafe { Box::from_raw(self.command_queue.panic_recovery.as_ptr()) });
154 }
155}
156
157impl World {
158 /// This performs initialization that _must_ happen for every [`World`] immediately upon creation (such as claiming specific component ids).
159 /// This _must_ be run as part of constructing a [`World`], before it is returned to the caller.
160 #[inline]
161 fn bootstrap(&mut self) {
162 // The order that we register these events is vital to ensure that the constants are correct!
163 let on_add = self.register_event_key::<Add>();
164 assert_eq!(ADD, on_add);
165
166 let on_insert = self.register_event_key::<Insert>();
167 assert_eq!(INSERT, on_insert);
168
169 let on_discard = self.register_event_key::<Discard>();
170 assert_eq!(DISCARD, on_discard);
171
172 let on_remove = self.register_event_key::<Remove>();
173 assert_eq!(REMOVE, on_remove);
174
175 let on_despawn = self.register_event_key::<Despawn>();
176 assert_eq!(DESPAWN, on_despawn);
177
178 let is_resource = self.register_component::<IsResource>();
179 assert_eq!(IS_RESOURCE, is_resource);
180
181 // This sets up `Disabled` as a disabling component, via the FromWorld impl
182 self.init_resource::<DefaultQueryFilters>();
183 }
184 /// Creates a new empty [`World`].
185 ///
186 /// # Panics
187 ///
188 /// If [`usize::MAX`] [`World`]s have been created.
189 /// This guarantee allows System Parameters to safely uniquely identify a [`World`],
190 /// since its [`WorldId`] is unique
191 #[inline]
192 pub fn new() -> World {
193 World::default()
194 }
195
196 /// Retrieves this [`World`]'s unique ID
197 #[inline]
198 pub fn id(&self) -> WorldId {
199 self.id
200 }
201
202 /// Creates a new [`UnsafeWorldCell`] view with complete read+write access.
203 #[inline]
204 pub fn as_unsafe_world_cell(&mut self) -> UnsafeWorldCell<'_> {
205 UnsafeWorldCell::new_mutable(self)
206 }
207
208 /// Creates a new [`UnsafeWorldCell`] view with only read access to everything.
209 #[inline]
210 pub fn as_unsafe_world_cell_readonly(&self) -> UnsafeWorldCell<'_> {
211 UnsafeWorldCell::new_readonly(self)
212 }
213
214 /// Retrieves this world's [`Entities`] collection.
215 #[inline]
216 pub fn entities(&self) -> &Entities {
217 &self.entities
218 }
219
220 /// Retrieves this world's [`EntityAllocator`] collection.
221 #[inline]
222 pub fn entity_allocator(&self) -> &EntityAllocator {
223 &self.entity_allocator
224 }
225
226 /// Retrieves this world's [`EntityAllocator`] collection mutably.
227 #[inline]
228 pub fn entity_allocator_mut(&mut self) -> &mut EntityAllocator {
229 &mut self.entity_allocator
230 }
231
232 /// Retrieves this world's [`Entities`] collection mutably.
233 ///
234 /// # Safety
235 /// Mutable reference must not be used to put the [`Entities`] data
236 /// in an invalid state for this [`World`]
237 #[inline]
238 pub unsafe fn entities_mut(&mut self) -> &mut Entities {
239 &mut self.entities
240 }
241
242 /// Retrieves the number of [`Entities`] in the world.
243 ///
244 /// This is helpful as a diagnostic, but it can also be used effectively in tests.
245 #[inline]
246 pub fn entity_count(&self) -> u32 {
247 self.entities.count_spawned()
248 }
249
250 /// Retrieves this world's [`Archetypes`] collection.
251 #[inline]
252 pub fn archetypes(&self) -> &Archetypes {
253 &self.archetypes
254 }
255
256 /// Retrieves this world's [`Components`] collection.
257 #[inline]
258 pub fn components(&self) -> &Components {
259 &self.components
260 }
261
262 /// Retrieves this world's [`ResourceEntities`].
263 #[inline]
264 pub fn resource_entities(&self) -> &ResourceEntities {
265 &self.resource_entities
266 }
267
268 /// Prepares a [`ComponentsQueuedRegistrator`] for the world.
269 /// **NOTE:** [`ComponentsQueuedRegistrator`] is easily misused.
270 /// See its docs for important notes on when and how it should be used.
271 #[inline]
272 pub fn components_queue(&self) -> ComponentsQueuedRegistrator<'_> {
273 // SAFETY: These are from the same world.
274 unsafe { ComponentsQueuedRegistrator::new(&self.components, &self.component_ids) }
275 }
276
277 /// Prepares a [`ComponentsRegistrator`] for the world.
278 #[inline]
279 pub fn components_registrator(&mut self) -> ComponentsRegistrator<'_> {
280 // SAFETY: These are from the same world.
281 unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) }
282 }
283
284 /// Retrieves this world's [`Storages`] collection.
285 #[inline]
286 pub fn storages(&self) -> &Storages {
287 &self.storages
288 }
289
290 /// Retrieves this world's [`Bundles`] collection.
291 #[inline]
292 pub fn bundles(&self) -> &Bundles {
293 &self.bundles
294 }
295
296 /// Retrieves this world's [`RemovedComponentMessages`] collection
297 #[inline]
298 pub fn removed_components(&self) -> &RemovedComponentMessages {
299 &self.removed_components
300 }
301
302 /// Retrieves this world's [`Observers`] list
303 #[inline]
304 pub fn observers(&self) -> &Observers {
305 &self.observers
306 }
307
308 /// Creates a new [`Commands`] instance that writes to the world's command queue
309 /// Use [`World::flush`] to apply all queued commands
310 #[inline]
311 pub fn commands(&mut self) -> Commands<'_, '_> {
312 // SAFETY: command_queue is stored on world and always valid while the world exists
313 unsafe {
314 Commands::new_raw_from_entities(
315 self.command_queue.clone(),
316 &self.entity_allocator,
317 &self.entities,
318 )
319 }
320 }
321
322 /// Registers a new [`Component`] type and returns the [`ComponentId`] created for it.
323 ///
324 /// # Usage Notes
325 /// In most cases, you don't need to call this method directly since component registration
326 /// happens automatically during system initialization.
327 #[doc(alias = "register_resource")]
328 pub fn register_component<T: Component>(&mut self) -> ComponentId {
329 self.components_registrator().register_component::<T>()
330 }
331
332 /// Registers a component type as "disabling",
333 /// using [default query filters](DefaultQueryFilters) to exclude entities with the component from queries.
334 pub fn register_disabling_component<C: Component>(&mut self) {
335 let component_id = self.register_component::<C>();
336 let mut dqf = self.resource_mut::<DefaultQueryFilters>();
337 dqf.register_disabling_component(component_id);
338 }
339
340 /// Returns a mutable reference to the [`ComponentHooks`] for a [`Component`] type.
341 ///
342 /// Will panic if `T` exists in any archetypes.
343 #[must_use]
344 pub fn register_component_hooks<T: Component>(&mut self) -> &mut ComponentHooks {
345 let index = self.register_component::<T>();
346 assert!(!self.archetypes.archetypes.iter().any(|a| a.contains(index)), "Components hooks cannot be modified if the component already exists in an archetype, use register_component if {} may already be in use", core::any::type_name::<T>());
347 // SAFETY: We just created this component
348 unsafe { self.components.get_hooks_mut(index).debug_checked_unwrap() }
349 }
350
351 /// Returns a mutable reference to the [`ComponentHooks`] for a [`Component`] with the given id if it exists.
352 ///
353 /// Will panic if `id` exists in any archetypes.
354 pub fn register_component_hooks_by_id(
355 &mut self,
356 id: ComponentId,
357 ) -> Option<&mut ComponentHooks> {
358 assert!(!self.archetypes.archetypes.iter().any(|a| a.contains(id)), "Components hooks cannot be modified if the component already exists in an archetype, use register_component if the component with id {id:?} may already be in use");
359 self.components.get_hooks_mut(id)
360 }
361
362 /// Registers the given component `R` as a [required component] for `T`.
363 ///
364 /// When `T` is added to an entity, `R` and its own required components will also be added
365 /// if `R` was not already provided. The [`Default`] `constructor` will be used for the creation of `R`.
366 /// If a custom constructor is desired, use [`World::register_required_components_with`] instead.
367 ///
368 /// For the non-panicking version, see [`World::try_register_required_components`].
369 ///
370 /// Note that requirements must currently be registered before `T` is inserted into the world
371 /// for the first time. This limitation may be fixed in the future.
372 ///
373 /// [required component]: Component#required-components
374 ///
375 /// # Panics
376 ///
377 /// Panics if `R` is already a directly required component for `T`, or if `T` has ever been added
378 /// on an entity before the registration.
379 ///
380 /// Indirect requirements through other components are allowed. In those cases, any existing requirements
381 /// will only be overwritten if the new requirement is more specific.
382 ///
383 /// # Example
384 ///
385 /// ```
386 /// # use bevy_ecs::prelude::*;
387 /// #[derive(Component)]
388 /// struct A;
389 ///
390 /// #[derive(Component, Default, PartialEq, Eq, Debug)]
391 /// struct B(usize);
392 ///
393 /// #[derive(Component, Default, PartialEq, Eq, Debug)]
394 /// struct C(u32);
395 ///
396 /// # let mut world = World::default();
397 /// // Register B as required by A and C as required by B.
398 /// world.register_required_components::<A, B>();
399 /// world.register_required_components::<B, C>();
400 ///
401 /// // This will implicitly also insert B and C with their Default constructors.
402 /// let id = world.spawn(A).id();
403 /// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
404 /// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
405 /// ```
406 pub fn register_required_components<T: Component, R: Component + Default>(&mut self) {
407 self.try_register_required_components::<T, R>().unwrap();
408 }
409
410 /// Registers the given component `R` as a [required component] for `T`.
411 ///
412 /// When `T` is added to an entity, `R` and its own required components will also be added
413 /// if `R` was not already provided. The given `constructor` will be used for the creation of `R`.
414 /// If a [`Default`] constructor is desired, use [`World::register_required_components`] instead.
415 ///
416 /// For the non-panicking version, see [`World::try_register_required_components_with`].
417 ///
418 /// Note that requirements must currently be registered before `T` is inserted into the world
419 /// for the first time. This limitation may be fixed in the future.
420 ///
421 /// [required component]: Component#required-components
422 ///
423 /// # Panics
424 ///
425 /// Panics if `R` is already a directly required component for `T`, or if `T` has ever been added
426 /// on an entity before the registration.
427 ///
428 /// Indirect requirements through other components are allowed. In those cases, any existing requirements
429 /// will only be overwritten if the new requirement is more specific.
430 ///
431 /// # Example
432 ///
433 /// ```
434 /// # use bevy_ecs::prelude::*;
435 /// #[derive(Component)]
436 /// struct A;
437 ///
438 /// #[derive(Component, Default, PartialEq, Eq, Debug)]
439 /// struct B(usize);
440 ///
441 /// #[derive(Component, PartialEq, Eq, Debug)]
442 /// struct C(u32);
443 ///
444 /// # let mut world = World::default();
445 /// // Register B and C as required by A and C as required by B.
446 /// // A requiring C directly will overwrite the indirect requirement through B.
447 /// world.register_required_components::<A, B>();
448 /// world.register_required_components_with::<B, C>(|| C(1));
449 /// world.register_required_components_with::<A, C>(|| C(2));
450 ///
451 /// // This will implicitly also insert B with its Default constructor and C
452 /// // with the custom constructor defined by A.
453 /// let id = world.spawn(A).id();
454 /// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
455 /// assert_eq!(&C(2), world.entity(id).get::<C>().unwrap());
456 /// ```
457 pub fn register_required_components_with<T: Component, R: Component>(
458 &mut self,
459 constructor: fn() -> R,
460 ) {
461 self.try_register_required_components_with::<T, R>(constructor)
462 .unwrap();
463 }
464
465 /// Tries to register the given component `R` as a [required component] for `T`.
466 ///
467 /// When `T` is added to an entity, `R` and its own required components will also be added
468 /// if `R` was not already provided. The [`Default`] `constructor` will be used for the creation of `R`.
469 /// If a custom constructor is desired, use [`World::register_required_components_with`] instead.
470 ///
471 /// For the panicking version, see [`World::register_required_components`].
472 ///
473 /// Note that requirements must currently be registered before `T` is inserted into the world
474 /// for the first time. This limitation may be fixed in the future.
475 ///
476 /// [required component]: Component#required-components
477 ///
478 /// # Errors
479 ///
480 /// Returns a [`RequiredComponentsError`] if `R` is already a directly required component for `T`, or if `T` has ever been added
481 /// on an entity before the registration.
482 ///
483 /// Indirect requirements through other components are allowed. In those cases, any existing requirements
484 /// will only be overwritten if the new requirement is more specific.
485 ///
486 /// # Example
487 ///
488 /// ```
489 /// # use bevy_ecs::prelude::*;
490 /// #[derive(Component)]
491 /// struct A;
492 ///
493 /// #[derive(Component, Default, PartialEq, Eq, Debug)]
494 /// struct B(usize);
495 ///
496 /// #[derive(Component, Default, PartialEq, Eq, Debug)]
497 /// struct C(u32);
498 ///
499 /// # let mut world = World::default();
500 /// // Register B as required by A and C as required by B.
501 /// world.register_required_components::<A, B>();
502 /// world.register_required_components::<B, C>();
503 ///
504 /// // Duplicate registration! This will fail.
505 /// assert!(world.try_register_required_components::<A, B>().is_err());
506 ///
507 /// // This will implicitly also insert B and C with their Default constructors.
508 /// let id = world.spawn(A).id();
509 /// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
510 /// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
511 /// ```
512 pub fn try_register_required_components<T: Component, R: Component + Default>(
513 &mut self,
514 ) -> Result<(), RequiredComponentsError> {
515 self.try_register_required_components_with::<T, R>(R::default)
516 }
517
518 /// Tries to register the given component `R` as a [required component] for `T`.
519 ///
520 /// When `T` is added to an entity, `R` and its own required components will also be added
521 /// if `R` was not already provided. The given `constructor` will be used for the creation of `R`.
522 /// If a [`Default`] constructor is desired, use [`World::register_required_components`] instead.
523 ///
524 /// For the panicking version, see [`World::register_required_components_with`].
525 ///
526 /// Note that requirements must currently be registered before `T` is inserted into the world
527 /// for the first time. This limitation may be fixed in the future.
528 ///
529 /// [required component]: Component#required-components
530 ///
531 /// # Errors
532 ///
533 /// Returns a [`RequiredComponentsError`] if `R` is already a directly required component for `T`, or if `T` has ever been added
534 /// on an entity before the registration.
535 ///
536 /// Indirect requirements through other components are allowed. In those cases, any existing requirements
537 /// will only be overwritten if the new requirement is more specific.
538 ///
539 /// # Example
540 ///
541 /// ```
542 /// # use bevy_ecs::prelude::*;
543 /// #[derive(Component)]
544 /// struct A;
545 ///
546 /// #[derive(Component, Default, PartialEq, Eq, Debug)]
547 /// struct B(usize);
548 ///
549 /// #[derive(Component, PartialEq, Eq, Debug)]
550 /// struct C(u32);
551 ///
552 /// # let mut world = World::default();
553 /// // Register B and C as required by A and C as required by B.
554 /// // A requiring C directly will overwrite the indirect requirement through B.
555 /// world.register_required_components::<A, B>();
556 /// world.register_required_components_with::<B, C>(|| C(1));
557 /// world.register_required_components_with::<A, C>(|| C(2));
558 ///
559 /// // Duplicate registration! Even if the constructors were different, this would fail.
560 /// assert!(world.try_register_required_components_with::<B, C>(|| C(1)).is_err());
561 ///
562 /// // This will implicitly also insert B with its Default constructor and C
563 /// // with the custom constructor defined by A.
564 /// let id = world.spawn(A).id();
565 /// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
566 /// assert_eq!(&C(2), world.entity(id).get::<C>().unwrap());
567 /// ```
568 pub fn try_register_required_components_with<T: Component, R: Component>(
569 &mut self,
570 constructor: fn() -> R,
571 ) -> Result<(), RequiredComponentsError> {
572 let requiree = self.register_component::<T>();
573
574 // TODO: Remove this panic and update archetype edges accordingly when required components are added
575 if self.archetypes().component_index().contains_key(&requiree) {
576 return Err(RequiredComponentsError::ArchetypeExists(requiree));
577 }
578
579 let required = self.register_component::<R>();
580
581 // SAFETY: We just created the `required` and `requiree` components.
582 unsafe {
583 self.components
584 .register_required_components::<R>(requiree, required, constructor)
585 }
586 }
587
588 /// Retrieves the [required components](RequiredComponents) for the given component type, if it exists.
589 pub fn get_required_components<C: Component>(&self) -> Option<&RequiredComponents> {
590 let id = self.components().valid_component_id::<C>()?;
591 let component_info = self.components().get_info(id)?;
592 Some(component_info.required_components())
593 }
594
595 /// Retrieves the [required components](RequiredComponents) for the component of the given [`ComponentId`], if it exists.
596 pub fn get_required_components_by_id(&self, id: ComponentId) -> Option<&RequiredComponents> {
597 let component_info = self.components().get_info(id)?;
598 Some(component_info.required_components())
599 }
600
601 /// Registers a new [`Component`] type and returns the [`ComponentId`] created for it.
602 ///
603 /// This method differs from [`World::register_component`] in that it uses a [`ComponentDescriptor`]
604 /// to register the new component type instead of statically available type information. This
605 /// enables the dynamic registration of new component definitions at runtime for advanced use cases.
606 ///
607 /// While the option to register a component from a descriptor is useful in type-erased
608 /// contexts, the standard [`World::register_component`] function should always be used instead
609 /// when type information is available at compile time.
610 pub fn register_component_with_descriptor(
611 &mut self,
612 descriptor: ComponentDescriptor,
613 ) -> ComponentId {
614 self.components_registrator()
615 .register_component_with_descriptor(descriptor)
616 }
617
618 /// Returns the [`ComponentId`] of the given [`Component`] type `T`.
619 ///
620 /// The returned `ComponentId` is specific to the `World` instance
621 /// it was retrieved from and should not be used with another `World` instance.
622 ///
623 /// Returns [`None`] if the `Component` type has not yet been initialized within
624 /// the `World` using [`World::register_component`].
625 ///
626 /// ```
627 /// use bevy_ecs::prelude::*;
628 ///
629 /// let mut world = World::new();
630 ///
631 /// #[derive(Component)]
632 /// struct ComponentA;
633 ///
634 /// let component_a_id = world.register_component::<ComponentA>();
635 ///
636 /// assert_eq!(component_a_id, world.component_id::<ComponentA>().unwrap())
637 /// ```
638 ///
639 /// # See also
640 ///
641 /// * [`ComponentIdFor`](crate::component::ComponentIdFor)
642 /// * [`Components::component_id()`]
643 /// * [`Components::get_id()`]
644 #[inline]
645 pub fn component_id<T: Component>(&self) -> Option<ComponentId> {
646 self.components.component_id::<T>()
647 }
648
649 /// Registers a new [`Resource`] type and returns the [`ComponentId`] created for it.
650 ///
651 /// The [`Resource`] doesn't have a value in the [`World`], it's only registered. If you want
652 /// to insert the [`Resource`] in the [`World`], use [`World::init_resource`] or
653 /// [`World::insert_resource`] instead.
654 #[deprecated(since = "0.19.0", note = "Use register_component::<R>() instead.")]
655 pub fn register_resource<R: Resource>(&mut self) -> ComponentId {
656 self.components_registrator().register_component::<R>()
657 }
658
659 /// Returns the [`ComponentId`] of the given [`Resource`] type `T`.
660 ///
661 /// The returned [`ComponentId`] is specific to the [`World`] instance it was retrieved from
662 /// and should not be used with another [`World`] instance.
663 ///
664 /// Returns [`None`] if the [`Resource`] type has not yet been initialized within the
665 /// [`World`] using [`World::register_resource`], [`World::init_resource`] or [`World::insert_resource`].
666 #[deprecated(since = "0.19.0", note = "use component_id")]
667 pub fn resource_id<T: Resource>(&self) -> Option<ComponentId> {
668 self.components.get_id(TypeId::of::<T>())
669 }
670
671 /// Returns [`EntityRef`]s that expose read-only operations for the given
672 /// `entities`. This will panic if any of the given entities do not exist. Use
673 /// [`World::get_entity`] if you want to check for entity existence instead
674 /// of implicitly panicking.
675 ///
676 /// This function supports fetching a single entity or multiple entities:
677 /// - Pass an [`Entity`] to receive a single [`EntityRef`].
678 /// - Pass a slice of [`Entity`]s to receive a [`Vec<EntityRef>`].
679 /// - Pass an array of [`Entity`]s to receive an equally-sized array of [`EntityRef`]s.
680 ///
681 /// # Panics
682 ///
683 /// If any of the given `entities` do not exist in the world.
684 ///
685 /// # Examples
686 ///
687 /// ## Single [`Entity`]
688 ///
689 /// ```
690 /// # use bevy_ecs::prelude::*;
691 /// #[derive(Component)]
692 /// struct Position {
693 /// x: f32,
694 /// y: f32,
695 /// }
696 ///
697 /// let mut world = World::new();
698 /// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
699 ///
700 /// let position = world.entity(entity).get::<Position>().unwrap();
701 /// assert_eq!(position.x, 0.0);
702 /// ```
703 ///
704 /// ## Array of [`Entity`]s
705 ///
706 /// ```
707 /// # use bevy_ecs::prelude::*;
708 /// #[derive(Component)]
709 /// struct Position {
710 /// x: f32,
711 /// y: f32,
712 /// }
713 ///
714 /// let mut world = World::new();
715 /// let e1 = world.spawn(Position { x: 0.0, y: 0.0 }).id();
716 /// let e2 = world.spawn(Position { x: 1.0, y: 1.0 }).id();
717 ///
718 /// let [e1_ref, e2_ref] = world.entity([e1, e2]);
719 /// let e1_position = e1_ref.get::<Position>().unwrap();
720 /// assert_eq!(e1_position.x, 0.0);
721 /// let e2_position = e2_ref.get::<Position>().unwrap();
722 /// assert_eq!(e2_position.x, 1.0);
723 /// ```
724 ///
725 /// ## Slice of [`Entity`]s
726 ///
727 /// ```
728 /// # use bevy_ecs::prelude::*;
729 /// #[derive(Component)]
730 /// struct Position {
731 /// x: f32,
732 /// y: f32,
733 /// }
734 ///
735 /// let mut world = World::new();
736 /// let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
737 /// let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
738 /// let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
739 ///
740 /// let ids = vec![e1, e2, e3];
741 /// for eref in world.entity(&ids[..]) {
742 /// assert_eq!(eref.get::<Position>().unwrap().y, 1.0);
743 /// }
744 /// ```
745 ///
746 /// ## [`EntityHashSet`](crate::entity::EntityHashSet)
747 ///
748 /// ```
749 /// # use bevy_ecs::{prelude::*, entity::EntityHashSet};
750 /// #[derive(Component)]
751 /// struct Position {
752 /// x: f32,
753 /// y: f32,
754 /// }
755 ///
756 /// let mut world = World::new();
757 /// let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
758 /// let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
759 /// let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
760 ///
761 /// let ids = EntityHashSet::from_iter([e1, e2, e3]);
762 /// for (_id, eref) in world.entity(&ids) {
763 /// assert_eq!(eref.get::<Position>().unwrap().y, 1.0);
764 /// }
765 /// ```
766 ///
767 /// [`EntityHashSet`]: crate::entity::EntityHashSet
768 #[inline]
769 #[track_caller]
770 pub fn entity<F: WorldEntityFetch>(&self, entities: F) -> F::Ref<'_> {
771 match self.get_entity(entities) {
772 Ok(res) => res,
773 Err(err) => panic!("{err}"),
774 }
775 }
776
777 /// Returns [`EntityMut`]s that expose read and write operations for the
778 /// given `entities`. This will panic if any of the given entities do not
779 /// exist. Use [`World::get_entity_mut`] if you want to check for entity
780 /// existence instead of implicitly panicking.
781 ///
782 /// This function supports fetching a single entity or multiple entities:
783 /// - Pass an [`Entity`] to receive a single [`EntityWorldMut`].
784 /// - This reference type allows for structural changes to the entity,
785 /// such as adding or removing components, or despawning the entity.
786 /// - Pass a slice of [`Entity`]s to receive a [`Vec<EntityMut>`].
787 /// - Pass an array of [`Entity`]s to receive an equally-sized array of [`EntityMut`]s.
788 /// - Pass a reference to a [`EntityHashSet`](crate::entity::EntityHashMap) to receive an
789 /// [`EntityHashMap<EntityMut>`](crate::entity::EntityHashMap).
790 ///
791 /// In order to perform structural changes on the returned entity reference,
792 /// such as adding or removing components, or despawning the entity, only a
793 /// single [`Entity`] can be passed to this function. Allowing multiple
794 /// entities at the same time with structural access would lead to undefined
795 /// behavior, so [`EntityMut`] is returned when requesting multiple entities.
796 ///
797 /// # Panics
798 ///
799 /// If any of the given `entities` do not exist in the world.
800 ///
801 /// # Examples
802 ///
803 /// ## Single [`Entity`]
804 ///
805 /// ```
806 /// # use bevy_ecs::prelude::*;
807 /// #[derive(Component)]
808 /// struct Position {
809 /// x: f32,
810 /// y: f32,
811 /// }
812 ///
813 /// let mut world = World::new();
814 /// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
815 ///
816 /// let mut entity_mut = world.entity_mut(entity);
817 /// let mut position = entity_mut.get_mut::<Position>().unwrap();
818 /// position.y = 1.0;
819 /// assert_eq!(position.x, 0.0);
820 /// entity_mut.despawn();
821 /// # assert!(world.get_entity_mut(entity).is_err());
822 /// ```
823 ///
824 /// ## Array of [`Entity`]s
825 ///
826 /// ```
827 /// # use bevy_ecs::prelude::*;
828 /// #[derive(Component)]
829 /// struct Position {
830 /// x: f32,
831 /// y: f32,
832 /// }
833 ///
834 /// let mut world = World::new();
835 /// let e1 = world.spawn(Position { x: 0.0, y: 0.0 }).id();
836 /// let e2 = world.spawn(Position { x: 1.0, y: 1.0 }).id();
837 ///
838 /// let [mut e1_ref, mut e2_ref] = world.entity_mut([e1, e2]);
839 /// let mut e1_position = e1_ref.get_mut::<Position>().unwrap();
840 /// e1_position.x = 1.0;
841 /// assert_eq!(e1_position.x, 1.0);
842 /// let mut e2_position = e2_ref.get_mut::<Position>().unwrap();
843 /// e2_position.x = 2.0;
844 /// assert_eq!(e2_position.x, 2.0);
845 /// ```
846 ///
847 /// ## Slice of [`Entity`]s
848 ///
849 /// ```
850 /// # use bevy_ecs::prelude::*;
851 /// #[derive(Component)]
852 /// struct Position {
853 /// x: f32,
854 /// y: f32,
855 /// }
856 ///
857 /// let mut world = World::new();
858 /// let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
859 /// let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
860 /// let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
861 ///
862 /// let ids = vec![e1, e2, e3];
863 /// for mut eref in world.entity_mut(&ids[..]) {
864 /// let mut pos = eref.get_mut::<Position>().unwrap();
865 /// pos.y = 2.0;
866 /// assert_eq!(pos.y, 2.0);
867 /// }
868 /// ```
869 ///
870 /// ## [`EntityHashSet`](crate::entity::EntityHashSet)
871 ///
872 /// ```
873 /// # use bevy_ecs::{prelude::*, entity::EntityHashSet};
874 /// #[derive(Component)]
875 /// struct Position {
876 /// x: f32,
877 /// y: f32,
878 /// }
879 ///
880 /// let mut world = World::new();
881 /// let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
882 /// let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
883 /// let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
884 ///
885 /// let ids = EntityHashSet::from_iter([e1, e2, e3]);
886 /// for (_id, mut eref) in world.entity_mut(&ids) {
887 /// let mut pos = eref.get_mut::<Position>().unwrap();
888 /// pos.y = 2.0;
889 /// assert_eq!(pos.y, 2.0);
890 /// }
891 /// ```
892 ///
893 /// [`EntityHashSet`]: crate::entity::EntityHashSet
894 #[inline]
895 #[track_caller]
896 pub fn entity_mut<F: WorldEntityFetch>(&mut self, entities: F) -> F::Mut<'_> {
897 #[inline(never)]
898 #[cold]
899 #[track_caller]
900 fn panic_on_err(e: EntityMutableFetchError) -> ! {
901 panic!("{e}");
902 }
903
904 match self.get_entity_mut(entities) {
905 Ok(fetched) => fetched,
906 Err(e) => panic_on_err(e),
907 }
908 }
909
910 /// Returns the components of an [`Entity`] through [`ComponentInfo`].
911 #[inline]
912 pub fn inspect_entity(
913 &self,
914 entity: Entity,
915 ) -> Result<impl Iterator<Item = &ComponentInfo>, EntityNotSpawnedError> {
916 let entity_location = self.entities().get_spawned(entity)?;
917
918 let archetype = self
919 .archetypes()
920 .get(entity_location.archetype_id)
921 .expect("ArchetypeId was retrieved from an EntityLocation and should correspond to an Archetype");
922
923 Ok(archetype
924 .iter_components()
925 .filter_map(|id| self.components().get_info(id)))
926 }
927
928 /// Returns [`EntityRef`]s that expose read-only operations for the given
929 /// `entities`, returning [`Err`] if any of the given entities do not exist.
930 /// Instead of immediately unwrapping the value returned from this function,
931 /// prefer [`World::entity`].
932 ///
933 /// This function supports fetching a single entity or multiple entities:
934 /// - Pass an [`Entity`] to receive a single [`EntityRef`].
935 /// - Pass a slice of [`Entity`]s to receive a [`Vec<EntityRef>`].
936 /// - Pass an array of [`Entity`]s to receive an equally-sized array of [`EntityRef`]s.
937 /// - Pass a reference to a [`EntityHashSet`](crate::entity::EntityHashMap) to receive an
938 /// [`EntityHashMap<EntityRef>`](crate::entity::EntityHashMap).
939 ///
940 /// # Errors
941 ///
942 /// If any of the given `entities` do not exist in the world, the first
943 /// [`Entity`] found to be missing will return an [`EntityNotSpawnedError`].
944 ///
945 /// # Examples
946 ///
947 /// For examples, see [`World::entity`].
948 ///
949 /// [`EntityHashSet`]: crate::entity::EntityHashSet
950 #[inline]
951 pub fn get_entity<F: WorldEntityFetch>(
952 &self,
953 entities: F,
954 ) -> Result<F::Ref<'_>, EntityNotSpawnedError> {
955 let cell = self.as_unsafe_world_cell_readonly();
956 // SAFETY: `&self` gives read access to the entire world, and prevents mutable access.
957 unsafe { entities.fetch_ref(cell) }
958 }
959
960 /// Returns [`EntityMut`]s that expose read and write operations for the
961 /// given `entities`, returning [`Err`] if any of the given entities do not
962 /// exist. Instead of immediately unwrapping the value returned from this
963 /// function, prefer [`World::entity_mut`].
964 ///
965 /// This function supports fetching a single entity or multiple entities:
966 /// - Pass an [`Entity`] to receive a single [`EntityWorldMut`].
967 /// - This reference type allows for structural changes to the entity,
968 /// such as adding or removing components, or despawning the entity.
969 /// - Pass a slice of [`Entity`]s to receive a [`Vec<EntityMut>`].
970 /// - Pass an array of [`Entity`]s to receive an equally-sized array of [`EntityMut`]s.
971 /// - Pass a reference to a [`EntityHashSet`](crate::entity::EntityHashMap) to receive an
972 /// [`EntityHashMap<EntityMut>`](crate::entity::EntityHashMap).
973 ///
974 /// In order to perform structural changes on the returned entity reference,
975 /// such as adding or removing components, or despawning the entity, only a
976 /// single [`Entity`] can be passed to this function. Allowing multiple
977 /// entities at the same time with structural access would lead to undefined
978 /// behavior, so [`EntityMut`] is returned when requesting multiple entities.
979 ///
980 /// # Errors
981 ///
982 /// - Returns [`EntityMutableFetchError::NotSpawned`] if any of the given `entities` do not exist in the world.
983 /// - Only the first entity found to be missing will be returned.
984 /// - Returns [`EntityMutableFetchError::AliasedMutability`] if the same entity is requested multiple times.
985 ///
986 /// # Examples
987 ///
988 /// For examples, see [`World::entity_mut`].
989 ///
990 /// [`EntityHashSet`]: crate::entity::EntityHashSet
991 #[inline]
992 pub fn get_entity_mut<F: WorldEntityFetch>(
993 &mut self,
994 entities: F,
995 ) -> Result<F::Mut<'_>, EntityMutableFetchError> {
996 let cell = self.as_unsafe_world_cell();
997 // SAFETY: `&mut self` gives mutable access to the entire world,
998 // and prevents any other access to the world.
999 unsafe { entities.fetch_mut(cell) }
1000 }
1001
1002 /// Returns an [`Entity`] iterator of current entities.
1003 ///
1004 /// This is useful in contexts where you only have immutable access to the [`World`].
1005 /// If you have mutable access to the [`World`], use
1006 /// [`query()::<EntityRef>().iter(&world)`](World::query()) instead.
1007 ///
1008 /// Note that this does iterate through *all* entities, including resource entities.
1009 #[inline]
1010 pub fn iter_entities(&self) -> impl Iterator<Item = EntityRef<'_>> + '_ {
1011 self.archetypes.iter().flat_map(|archetype| {
1012 archetype
1013 .entities_with_location()
1014 .map(|(entity, location)| {
1015 // SAFETY: entity exists and location accurately specifies the archetype where the entity is stored.
1016 let cell = UnsafeEntityCell::new(
1017 self.as_unsafe_world_cell_readonly(),
1018 entity,
1019 location,
1020 self.last_change_tick,
1021 self.read_change_tick(),
1022 );
1023 // SAFETY: `&self` gives read access to the entire world.
1024 unsafe { EntityRef::new(cell) }
1025 })
1026 })
1027 }
1028
1029 /// Simultaneously provides access to entity data and a command queue, which
1030 /// will be applied when the world is next flushed.
1031 ///
1032 /// This allows using borrowed entity data to construct commands where the
1033 /// borrow checker would otherwise prevent it.
1034 ///
1035 /// See [`DeferredWorld::entities_and_commands`] for the deferred version.
1036 ///
1037 /// # Example
1038 ///
1039 /// ```rust
1040 /// # use bevy_ecs::{prelude::*, world::DeferredWorld};
1041 /// #[derive(Component)]
1042 /// struct Targets(Vec<Entity>);
1043 /// #[derive(Component)]
1044 /// struct TargetedBy(Entity);
1045 ///
1046 /// let mut world: World = // ...
1047 /// # World::new();
1048 /// # let e1 = world.spawn_empty().id();
1049 /// # let e2 = world.spawn_empty().id();
1050 /// # let eid = world.spawn(Targets(vec![e1, e2])).id();
1051 /// let (entities, mut commands) = world.entities_and_commands();
1052 ///
1053 /// let entity = entities.get(eid).unwrap();
1054 /// for &target in entity.get::<Targets>().unwrap().0.iter() {
1055 /// commands.entity(target).insert(TargetedBy(eid));
1056 /// }
1057 /// # world.flush();
1058 /// # assert_eq!(world.get::<TargetedBy>(e1).unwrap().0, eid);
1059 /// # assert_eq!(world.get::<TargetedBy>(e2).unwrap().0, eid);
1060 /// ```
1061 pub fn entities_and_commands(&mut self) -> (EntityFetcher<'_>, Commands<'_, '_>) {
1062 let cell = self.as_unsafe_world_cell();
1063 // SAFETY: `&mut self` gives mutable access to the entire world, and prevents simultaneous access.
1064 let fetcher = unsafe { EntityFetcher::new(cell) };
1065 // SAFETY:
1066 // - `&mut self` gives mutable access to the entire world, and prevents simultaneous access.
1067 // - Command queue access does not conflict with entity access.
1068 let raw_queue = unsafe { cell.get_raw_command_queue() };
1069 // SAFETY: `&mut self` ensures the commands does not outlive the world.
1070 let commands = unsafe {
1071 Commands::new_raw_from_entities(raw_queue, cell.entity_allocator(), cell.entities())
1072 };
1073
1074 (fetcher, commands)
1075 }
1076
1077 /// Spawns the bundle on the valid but not spawned entity.
1078 /// If the entity can not be spawned for any reason, returns an error.
1079 ///
1080 /// If it succeeds, this declares the entity to have this bundle.
1081 ///
1082 /// In general, you should prefer [`spawn`](Self::spawn).
1083 /// Spawn internally calls this method, but it takes care of finding a suitable [`Entity`] for you.
1084 /// This is made available for advanced use, which you can see at [`EntityAllocator::alloc`].
1085 ///
1086 /// # Risk
1087 ///
1088 /// It is possible to spawn an `entity` that has not been allocated yet;
1089 /// however, doing so is currently a bad idea as the allocator may hand out this entity index in the future, assuming it to be not spawned.
1090 /// This would cause a panic.
1091 ///
1092 /// Manual spawning is a powerful tool, but must be used carefully.
1093 ///
1094 /// # Example
1095 ///
1096 /// Currently, this is primarily used to spawn entities that come from [`EntityAllocator::alloc`].
1097 /// See that for an example.
1098 #[track_caller]
1099 pub fn spawn_at<B: Bundle>(
1100 &mut self,
1101 entity: Entity,
1102 bundle: B,
1103 ) -> Result<EntityWorldMut<'_>, SpawnError> {
1104 move_as_ptr!(bundle);
1105 self.spawn_at_with_caller(entity, bundle, MaybeLocation::caller())
1106 }
1107
1108 pub(crate) fn spawn_at_with_caller<B: Bundle>(
1109 &mut self,
1110 entity: Entity,
1111 bundle: MovingPtr<'_, B>,
1112 caller: MaybeLocation,
1113 ) -> Result<EntityWorldMut<'_>, SpawnError> {
1114 self.entities.check_can_spawn_at(entity)?;
1115 Ok(self.spawn_at_unchecked(entity, bundle, caller))
1116 }
1117
1118 /// Spawns `bundle` on `entity`.
1119 ///
1120 /// # Panics
1121 ///
1122 /// Panics if the entity index is already constructed
1123 pub(crate) fn spawn_at_unchecked<B: Bundle>(
1124 &mut self,
1125 entity: Entity,
1126 bundle: MovingPtr<'_, B>,
1127 caller: MaybeLocation,
1128 ) -> EntityWorldMut<'_> {
1129 let change_tick = self.change_tick();
1130 let mut bundle_spawner = BundleSpawner::new::<B>(self, change_tick);
1131 let (bundle, entity_location) = bundle.partial_move(|bundle| {
1132 // SAFETY:
1133 // - `B` matches `bundle_spawner`'s type
1134 // - `entity` is allocated but non-existent
1135 // - `B::Effect` is unconstrained, and `B::apply_effect` is called exactly once on the bundle after this call.
1136 // - This function ensures that the value pointed to by `bundle` must not be accessed for anything afterwards by consuming
1137 // the `MovingPtr`. The value is otherwise only used to call `apply_effect` within this function, and the safety invariants
1138 // of `DynamicBundle` ensure that only the elements that have not been moved out of by this call are accessed.
1139 unsafe { bundle_spawner.spawn_at::<B>(entity, bundle, caller) }
1140 });
1141
1142 let mut entity_location = Some(entity_location);
1143
1144 // SAFETY: command_queue is not referenced anywhere else
1145 if !unsafe { self.command_queue.is_empty() } {
1146 self.flush();
1147 entity_location = self.entities().get_spawned(entity).ok();
1148 }
1149
1150 // SAFETY: The entity and location started as valid.
1151 // If they were changed by commands, the location was updated to match.
1152 let mut entity = unsafe { EntityWorldMut::new(self, entity, entity_location) };
1153 // SAFETY:
1154 // - This is called exactly once after `get_components` has been called in `spawn_non_existent`.
1155 // - `bundle` had it's `get_components` function called exactly once inside `spawn_non_existent`.
1156 unsafe { B::apply_effect(bundle, &mut entity) };
1157 entity
1158 }
1159
1160 /// A faster version of [`spawn_at`](Self::spawn_at) for the empty bundle.
1161 #[track_caller]
1162 pub fn spawn_empty_at(&mut self, entity: Entity) -> Result<EntityWorldMut<'_>, SpawnError> {
1163 self.spawn_empty_at_with_caller(entity, MaybeLocation::caller())
1164 }
1165
1166 pub(crate) fn spawn_empty_at_with_caller(
1167 &mut self,
1168 entity: Entity,
1169 caller: MaybeLocation,
1170 ) -> Result<EntityWorldMut<'_>, SpawnError> {
1171 self.entities.check_can_spawn_at(entity)?;
1172 Ok(self.spawn_empty_at_unchecked(entity, caller))
1173 }
1174
1175 /// A faster version of [`spawn_at_unchecked`](Self::spawn_at_unchecked) for the empty bundle.
1176 ///
1177 /// # Panics
1178 ///
1179 /// Panics if the entity index is already spawned
1180 pub(crate) fn spawn_empty_at_unchecked(
1181 &mut self,
1182 entity: Entity,
1183 caller: MaybeLocation,
1184 ) -> EntityWorldMut<'_> {
1185 // SAFETY: Locations are immediately made valid
1186 unsafe {
1187 let archetype = self.archetypes.empty_mut();
1188 // PERF: consider avoiding allocating entities in the empty archetype unless needed
1189 let table_row = self.storages.tables[archetype.table_id()].allocate(entity);
1190 // SAFETY: no components are allocated by archetype.allocate() because the archetype is
1191 // empty
1192 let location = archetype.allocate(entity, table_row);
1193 let change_tick = self.change_tick();
1194 let was_at = self.entities.set_location(entity.index(), Some(location));
1195 assert!(
1196 was_at.is_none(),
1197 "Attempting to construct an empty entity, but it was already constructed."
1198 );
1199 self.entities
1200 .mark_spawned_or_despawned(entity.index(), caller, change_tick);
1201
1202 EntityWorldMut::new(self, entity, Some(location))
1203 }
1204 }
1205
1206 /// Spawns a new [`Entity`] with a given [`Bundle`] of [components](`Component`) and returns
1207 /// a corresponding [`EntityWorldMut`], which can be used to add components to the entity or
1208 /// retrieve its id. In case large batches of entities need to be spawned, consider using
1209 /// [`World::spawn_batch`] instead.
1210 ///
1211 /// ```
1212 /// use bevy_ecs::{bundle::Bundle, component::Component, world::World};
1213 ///
1214 /// #[derive(Component)]
1215 /// struct Position {
1216 /// x: f32,
1217 /// y: f32,
1218 /// }
1219 ///
1220 /// #[derive(Component)]
1221 /// struct Velocity {
1222 /// x: f32,
1223 /// y: f32,
1224 /// };
1225 ///
1226 /// #[derive(Component)]
1227 /// struct Name(&'static str);
1228 ///
1229 /// #[derive(Bundle)]
1230 /// struct PhysicsBundle {
1231 /// position: Position,
1232 /// velocity: Velocity,
1233 /// }
1234 ///
1235 /// let mut world = World::new();
1236 ///
1237 /// // `spawn` can accept a single component:
1238 /// world.spawn(Position { x: 0.0, y: 0.0 });
1239 ///
1240 /// // It can also accept a tuple of components:
1241 /// world.spawn((
1242 /// Position { x: 0.0, y: 0.0 },
1243 /// Velocity { x: 1.0, y: 1.0 },
1244 /// ));
1245 ///
1246 /// // Or it can accept a pre-defined Bundle of components:
1247 /// world.spawn(PhysicsBundle {
1248 /// position: Position { x: 2.0, y: 2.0 },
1249 /// velocity: Velocity { x: 0.0, y: 4.0 },
1250 /// });
1251 ///
1252 /// let entity = world
1253 /// // Tuples can also mix Bundles and Components
1254 /// .spawn((
1255 /// PhysicsBundle {
1256 /// position: Position { x: 2.0, y: 2.0 },
1257 /// velocity: Velocity { x: 0.0, y: 4.0 },
1258 /// },
1259 /// Name("Elaina Proctor"),
1260 /// ))
1261 /// // Calling id() will return the unique identifier for the spawned entity
1262 /// .id();
1263 /// let position = world.entity(entity).get::<Position>().unwrap();
1264 /// assert_eq!(position.x, 2.0);
1265 /// ```
1266 #[track_caller]
1267 pub fn spawn<B: Bundle>(&mut self, bundle: B) -> EntityWorldMut<'_> {
1268 move_as_ptr!(bundle);
1269 self.spawn_with_caller(bundle, MaybeLocation::caller())
1270 }
1271
1272 pub(crate) fn spawn_with_caller<B: Bundle>(
1273 &mut self,
1274 bundle: MovingPtr<'_, B>,
1275 caller: MaybeLocation,
1276 ) -> EntityWorldMut<'_> {
1277 let entity = self.entity_allocator.alloc();
1278 // This was just spawned from null, so it shouldn't panic.
1279 self.spawn_at_unchecked(entity, bundle, caller)
1280 }
1281
1282 /// Spawns a new [`Entity`] and returns a corresponding [`EntityWorldMut`], which can be used
1283 /// to add components to the entity or retrieve its id.
1284 ///
1285 /// ```
1286 /// use bevy_ecs::{component::Component, world::World};
1287 ///
1288 /// #[derive(Component)]
1289 /// struct Position {
1290 /// x: f32,
1291 /// y: f32,
1292 /// }
1293 /// #[derive(Component)]
1294 /// struct Label(&'static str);
1295 /// #[derive(Component)]
1296 /// struct Num(u32);
1297 ///
1298 /// let mut world = World::new();
1299 /// let entity = world.spawn_empty()
1300 /// .insert(Position { x: 0.0, y: 0.0 }) // add a single component
1301 /// .insert((Num(1), Label("hello"))) // add a bundle of components
1302 /// .id();
1303 ///
1304 /// let position = world.entity(entity).get::<Position>().unwrap();
1305 /// assert_eq!(position.x, 0.0);
1306 /// ```
1307 #[track_caller]
1308 pub fn spawn_empty(&mut self) -> EntityWorldMut<'_> {
1309 self.spawn_empty_with_caller(MaybeLocation::caller())
1310 }
1311
1312 pub(crate) fn spawn_empty_with_caller(&mut self, caller: MaybeLocation) -> EntityWorldMut<'_> {
1313 let entity = self.entity_allocator.alloc();
1314 // This was just spawned from null, so it shouldn't panic.
1315 self.spawn_empty_at_unchecked(entity, caller)
1316 }
1317
1318 /// Spawns a batch of entities with the same component [`Bundle`] type. Takes a given
1319 /// [`Bundle`] iterator and returns a corresponding [`Entity`] iterator.
1320 /// This is more efficient than spawning entities and adding components to them individually
1321 /// using [`World::spawn`], but it is limited to spawning entities with the same [`Bundle`]
1322 /// type, whereas spawning individually is more flexible.
1323 ///
1324 /// ```
1325 /// use bevy_ecs::{component::Component, entity::Entity, world::World};
1326 ///
1327 /// #[derive(Component)]
1328 /// struct Str(&'static str);
1329 /// #[derive(Component)]
1330 /// struct Num(u32);
1331 ///
1332 /// let mut world = World::new();
1333 /// let entities = world.spawn_batch(vec![
1334 /// (Str("a"), Num(0)), // the first entity
1335 /// (Str("b"), Num(1)), // the second entity
1336 /// ]).collect::<Vec<Entity>>();
1337 ///
1338 /// assert_eq!(entities.len(), 2);
1339 /// ```
1340 #[track_caller]
1341 pub fn spawn_batch<I>(&mut self, iter: I) -> SpawnBatchIter<'_, I::IntoIter>
1342 where
1343 I: IntoIterator,
1344 I::Item: Bundle<Effect: NoBundleEffect>,
1345 {
1346 SpawnBatchIter::new(self, iter.into_iter(), MaybeLocation::caller())
1347 }
1348
1349 /// Retrieves a reference to the given `entity`'s [`Component`] of the given type.
1350 /// Returns `None` if the `entity` does not have a [`Component`] of the given type.
1351 /// ```
1352 /// use bevy_ecs::{component::Component, world::World};
1353 ///
1354 /// #[derive(Component)]
1355 /// struct Position {
1356 /// x: f32,
1357 /// y: f32,
1358 /// }
1359 ///
1360 /// let mut world = World::new();
1361 /// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
1362 /// let position = world.get::<Position>(entity).unwrap();
1363 /// assert_eq!(position.x, 0.0);
1364 /// ```
1365 #[inline]
1366 pub fn get<T: Component>(&self, entity: Entity) -> Option<&T> {
1367 self.get_entity(entity).ok()?.get()
1368 }
1369
1370 /// Retrieves a mutable reference to the given `entity`'s [`Component`] of the given type.
1371 /// Returns `None` if the `entity` does not have a [`Component`] of the given type.
1372 /// ```
1373 /// use bevy_ecs::{component::Component, world::World};
1374 ///
1375 /// #[derive(Component)]
1376 /// struct Position {
1377 /// x: f32,
1378 /// y: f32,
1379 /// }
1380 ///
1381 /// let mut world = World::new();
1382 /// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
1383 /// let mut position = world.get_mut::<Position>(entity).unwrap();
1384 /// position.x = 1.0;
1385 /// ```
1386 #[inline]
1387 pub fn get_mut<T: Component<Mutability = Mutable>>(
1388 &mut self,
1389 entity: Entity,
1390 ) -> Option<Mut<'_, T>> {
1391 self.get_entity_mut(entity).ok()?.into_mut()
1392 }
1393
1394 /// Temporarily removes a [`Component`] `T` from the provided [`Entity`] and
1395 /// runs the provided closure on it, returning the result if `T` was available.
1396 /// This will trigger the `Remove` and `Discard` component hooks without
1397 /// causing an archetype move.
1398 ///
1399 /// This is most useful with immutable components, where removal and reinsertion
1400 /// is the only way to modify a value.
1401 ///
1402 /// If you do not need to ensure the above hooks are triggered, and your component
1403 /// is mutable, prefer using [`get_mut`](World::get_mut).
1404 ///
1405 /// # Examples
1406 ///
1407 /// ```rust
1408 /// # use bevy_ecs::prelude::*;
1409 /// #
1410 /// #[derive(Component, PartialEq, Eq, Debug)]
1411 /// #[component(immutable)]
1412 /// struct Foo(bool);
1413 ///
1414 /// # let mut world = World::default();
1415 /// # world.register_component::<Foo>();
1416 /// #
1417 /// # let entity = world.spawn(Foo(false)).id();
1418 /// #
1419 /// world.modify_component(entity, |foo: &mut Foo| {
1420 /// foo.0 = true;
1421 /// });
1422 /// #
1423 /// # assert_eq!(world.get::<Foo>(entity), Some(&Foo(true)));
1424 /// ```
1425 #[inline]
1426 #[track_caller]
1427 pub fn modify_component<T: Component, R>(
1428 &mut self,
1429 entity: Entity,
1430 f: impl FnOnce(&mut T) -> R,
1431 ) -> Result<Option<R>, EntityMutableFetchError> {
1432 let mut world = DeferredWorld::from(&mut *self);
1433
1434 let result = world.modify_component_with_relationship_hook_mode(
1435 entity,
1436 RelationshipHookMode::Run,
1437 f,
1438 )?;
1439
1440 self.flush();
1441 Ok(result)
1442 }
1443
1444 /// Temporarily removes a [`Component`] identified by the provided
1445 /// [`ComponentId`] from the provided [`Entity`] and runs the provided
1446 /// closure on it, returning the result if the component was available.
1447 /// This will trigger the `Remove` and `Discard` component hooks without
1448 /// causing an archetype move.
1449 ///
1450 /// This is most useful with immutable components, where removal and reinsertion
1451 /// is the only way to modify a value.
1452 ///
1453 /// If you do not need to ensure the above hooks are triggered, and your component
1454 /// is mutable, prefer using [`get_mut_by_id`](World::get_mut_by_id).
1455 ///
1456 /// You should prefer the typed [`modify_component`](World::modify_component)
1457 /// whenever possible.
1458 #[inline]
1459 #[track_caller]
1460 pub fn modify_component_by_id<R>(
1461 &mut self,
1462 entity: Entity,
1463 component_id: ComponentId,
1464 f: impl for<'a> FnOnce(MutUntyped<'a>) -> R,
1465 ) -> Result<Option<R>, EntityMutableFetchError> {
1466 let mut world = DeferredWorld::from(&mut *self);
1467
1468 let result = world.modify_component_by_id_with_relationship_hook_mode(
1469 entity,
1470 component_id,
1471 RelationshipHookMode::Run,
1472 f,
1473 )?;
1474
1475 self.flush();
1476 Ok(result)
1477 }
1478
1479 /// Temporarily removes a [`Resource`] `R` and
1480 /// runs the provided closure on it, returning the result if `R` was available.
1481 /// This will trigger the `Remove` and `Discard` component hooks without
1482 /// causing an archetype move.
1483 ///
1484 /// This is most useful with immutable resources, where removal and reinsertion
1485 /// is the only way to modify a value.
1486 ///
1487 /// If you do not need to ensure the above hooks are triggered, and your resource
1488 /// is mutable, prefer using [`get_resource_mut`](World::get_resource_mut).
1489 ///
1490 /// # Examples
1491 ///
1492 /// ```rust
1493 /// # use bevy_ecs::prelude::*;
1494 /// #
1495 /// #[derive(Resource, PartialEq, Eq, Debug)]
1496 /// #[component(immutable)]
1497 /// struct Bar(bool);
1498 ///
1499 /// # let mut world = World::default();
1500 /// # world.insert_resource(Bar(false));
1501 /// #
1502 /// world.modify_resource(|bar: &mut Bar| {
1503 /// bar.0 = true;
1504 /// });
1505 /// #
1506 /// # assert_eq!(world.get_resource::<Bar>(), Some(&Bar(true)));
1507 /// ```
1508 #[inline]
1509 #[track_caller]
1510 pub fn modify_resource<R: Resource, S>(
1511 &mut self,
1512 f: impl FnOnce(&mut R) -> S,
1513 ) -> Result<Option<S>, EntityMutableFetchError> {
1514 let component_id = self.register_component::<R>();
1515 if let Some(entity) = self.resource_entities.get(component_id) {
1516 let mut world = DeferredWorld::from(&mut *self);
1517 let result = world.modify_component_with_relationship_hook_mode(
1518 entity,
1519 RelationshipHookMode::Run,
1520 f,
1521 )?;
1522
1523 self.flush();
1524 Ok(result)
1525 } else {
1526 Ok(None)
1527 }
1528 }
1529
1530 /// Temporarily removes a [`Resource`] identified by the provided
1531 /// [`ComponentId`] and runs the provided
1532 /// closure on it, returning the result if the component was available.
1533 /// This will trigger the `Remove` and `Discard` component hooks without
1534 /// causing an archetype move.
1535 ///
1536 /// This is most useful with immutable resources, where removal and reinsertion
1537 /// is the only way to modify a value.
1538 ///
1539 /// If you do not need to ensure the above hooks are triggered, and your resource
1540 /// is mutable, prefer using [`get_resource_mut_by_id`](World::get_resource_mut_by_id).
1541 ///
1542 /// You should prefer the typed [`modify_resource`](World::modify_resource)
1543 /// whenever possible.
1544 #[inline]
1545 #[track_caller]
1546 pub fn modify_resource_by_id<S>(
1547 &mut self,
1548 component_id: ComponentId,
1549 f: impl for<'a> FnOnce(MutUntyped<'a>) -> S,
1550 ) -> Result<Option<S>, EntityMutableFetchError> {
1551 if let Some(entity) = self.resource_entities.get(component_id) {
1552 let mut world = DeferredWorld::from(&mut *self);
1553
1554 let result = world.modify_component_by_id_with_relationship_hook_mode(
1555 entity,
1556 component_id,
1557 RelationshipHookMode::Run,
1558 f,
1559 )?;
1560
1561 self.flush();
1562 Ok(result)
1563 } else {
1564 Ok(None)
1565 }
1566 }
1567
1568 /// Despawns the given [`Entity`], if it exists.
1569 /// This will also remove all of the entity's [`Components`](Component).
1570 ///
1571 /// Returns `true` if the entity is successfully despawned and `false` if
1572 /// the entity does not exist.
1573 /// This counts despawning a not constructed entity as a success, and frees it to the allocator.
1574 /// See [entity](crate::entity) module docs for more about construction.
1575 ///
1576 /// # Note
1577 ///
1578 /// This will also despawn the entities in any [`RelationshipTarget`](crate::relationship::RelationshipTarget) that is configured
1579 /// to despawn descendants. For example, this will recursively despawn [`Children`](crate::hierarchy::Children).
1580 ///
1581 /// ```
1582 /// use bevy_ecs::{component::Component, world::World};
1583 ///
1584 /// #[derive(Component)]
1585 /// struct Position {
1586 /// x: f32,
1587 /// y: f32,
1588 /// }
1589 ///
1590 /// let mut world = World::new();
1591 /// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
1592 /// assert!(world.despawn(entity));
1593 /// assert!(world.get_entity(entity).is_err());
1594 /// assert!(world.get::<Position>(entity).is_none());
1595 /// ```
1596 #[track_caller]
1597 #[inline]
1598 pub fn despawn(&mut self, entity: Entity) -> bool {
1599 if let Err(error) = self.despawn_with_caller(entity, MaybeLocation::caller()) {
1600 warn!("{error}");
1601 false
1602 } else {
1603 true
1604 }
1605 }
1606
1607 /// Despawns the given `entity`, if it exists. This will also remove all of the entity's
1608 /// [`Components`](Component).
1609 ///
1610 /// Returns an [`EntityDespawnError`] if the entity is not spawned to be despawned.
1611 ///
1612 /// # Note
1613 ///
1614 /// This will also despawn the entities in any [`RelationshipTarget`](crate::relationship::RelationshipTarget) that is configured
1615 /// to despawn descendants. For example, this will recursively despawn [`Children`](crate::hierarchy::Children).
1616 #[track_caller]
1617 #[inline]
1618 pub fn try_despawn(&mut self, entity: Entity) -> Result<(), EntityDespawnError> {
1619 self.despawn_with_caller(entity, MaybeLocation::caller())
1620 }
1621
1622 #[inline]
1623 pub(crate) fn despawn_with_caller(
1624 &mut self,
1625 entity: Entity,
1626 caller: MaybeLocation,
1627 ) -> Result<(), EntityDespawnError> {
1628 match self.get_entity_mut(entity) {
1629 Ok(entity) => {
1630 entity.despawn_with_caller(caller);
1631 Ok(())
1632 }
1633 // Only one entity.
1634 Err(EntityMutableFetchError::AliasedMutability(_)) => unreachable!(),
1635 Err(EntityMutableFetchError::NotSpawned(err)) => Err(EntityDespawnError(err)),
1636 }
1637 }
1638
1639 /// Performs [`try_despawn_no_free`](Self::try_despawn_no_free), warning on errors.
1640 /// See that method for more information.
1641 #[track_caller]
1642 #[inline]
1643 pub fn despawn_no_free(&mut self, entity: Entity) -> Option<Entity> {
1644 match self.despawn_no_free_with_caller(entity, MaybeLocation::caller()) {
1645 Ok(entity) => Some(entity),
1646 Err(error) => {
1647 warn!("{error}");
1648 None
1649 }
1650 }
1651 }
1652
1653 /// Despawns the given `entity`, if it exists.
1654 /// This will also remove all of the entity's [`Component`]s.
1655 ///
1656 /// The *only* difference between this and [despawning](Self::despawn) an entity is that this does not release the `entity` to be reused.
1657 /// It is up to the caller to either re-spawn or free the `entity`; otherwise, the [`EntityIndex`](crate::entity::EntityIndex) will not be able to be reused.
1658 /// In general, [`despawn`](Self::despawn) should be used instead, which automatically allows the row to be reused.
1659 ///
1660 /// Returns the new [`Entity`] if of the despawned [`EntityIndex`](crate::entity::EntityIndex), which should eventually either be re-spawned or freed to the allocator.
1661 /// Returns an [`EntityDespawnError`] if the entity is not spawned.
1662 ///
1663 /// # Note
1664 ///
1665 /// This will also *despawn* the entities in any [`RelationshipTarget`](crate::relationship::RelationshipTarget) that is configured
1666 /// to despawn descendants. For example, this will recursively despawn [`Children`](crate::hierarchy::Children).
1667 ///
1668 /// # Example
1669 ///
1670 /// There is no simple example in which this would be practical, but one use for this is a custom entity allocator.
1671 /// Despawning internally calls this and frees the entity id to Bevy's default entity allocator.
1672 /// The same principal can be used to create custom allocators with additional properties.
1673 /// For example, this could be used to make an allocator that yields groups of consecutive [`EntityIndex`](crate::entity::EntityIndex)s, etc.
1674 /// See [`EntityAllocator::alloc`] for more on this.
1675 #[track_caller]
1676 #[inline]
1677 pub fn try_despawn_no_free(&mut self, entity: Entity) -> Result<Entity, EntityDespawnError> {
1678 self.despawn_no_free_with_caller(entity, MaybeLocation::caller())
1679 }
1680
1681 #[inline]
1682 pub(crate) fn despawn_no_free_with_caller(
1683 &mut self,
1684 entity: Entity,
1685 caller: MaybeLocation,
1686 ) -> Result<Entity, EntityDespawnError> {
1687 let mut entity = self.get_entity_mut(entity).map_err(|err| match err {
1688 EntityMutableFetchError::NotSpawned(err) => err,
1689 // Only one entity.
1690 EntityMutableFetchError::AliasedMutability(_) => unreachable!(),
1691 })?;
1692 entity.despawn_no_free_with_caller(caller);
1693 Ok(entity.id())
1694 }
1695
1696 /// Clears the internal component tracker state.
1697 ///
1698 /// The world maintains some internal state about changed and removed components. This state
1699 /// is used by [`RemovedComponents`] to provide access to the entities that had a specific type
1700 /// of component removed since last tick.
1701 ///
1702 /// The state is also used for change detection when accessing components and resources outside
1703 /// of a system, for example via [`World::get_mut()`] or [`World::get_resource_mut()`].
1704 ///
1705 /// By clearing this internal state, the world "forgets" about those changes, allowing a new round
1706 /// of detection to be recorded.
1707 ///
1708 /// When using `bevy_ecs` as part of the full Bevy engine, this method is called automatically
1709 /// by `bevy_app::App::update` and `bevy_app::SubApp::update`, so you don't need to call it manually.
1710 /// When using `bevy_ecs` as a separate standalone crate however, you do need to call this manually.
1711 ///
1712 /// ```
1713 /// # use bevy_ecs::prelude::*;
1714 /// # #[derive(Component, Default)]
1715 /// # struct Transform;
1716 /// // a whole new world
1717 /// let mut world = World::new();
1718 ///
1719 /// // you changed it
1720 /// let entity = world.spawn(Transform::default()).id();
1721 ///
1722 /// // change is detected
1723 /// let transform = world.get_mut::<Transform>(entity).unwrap();
1724 /// assert!(transform.is_changed());
1725 ///
1726 /// // update the last change tick
1727 /// world.clear_trackers();
1728 ///
1729 /// // change is no longer detected
1730 /// let transform = world.get_mut::<Transform>(entity).unwrap();
1731 /// assert!(!transform.is_changed());
1732 /// ```
1733 ///
1734 /// [`RemovedComponents`]: crate::lifecycle::RemovedComponents
1735 pub fn clear_trackers(&mut self) {
1736 self.removed_components.update();
1737 self.last_change_tick = self.increment_change_tick();
1738 }
1739
1740 /// Returns [`QueryState`] for the given [`QueryData`], which is used to efficiently
1741 /// run queries on the [`World`] by storing and reusing the [`QueryState`].
1742 /// ```
1743 /// use bevy_ecs::{component::Component, entity::Entity, world::World};
1744 ///
1745 /// #[derive(Component, Debug, PartialEq)]
1746 /// struct Position {
1747 /// x: f32,
1748 /// y: f32,
1749 /// }
1750 ///
1751 /// #[derive(Component)]
1752 /// struct Velocity {
1753 /// x: f32,
1754 /// y: f32,
1755 /// }
1756 ///
1757 /// let mut world = World::new();
1758 /// let entities = world.spawn_batch(vec![
1759 /// (Position { x: 0.0, y: 0.0}, Velocity { x: 1.0, y: 0.0 }),
1760 /// (Position { x: 0.0, y: 0.0}, Velocity { x: 0.0, y: 1.0 }),
1761 /// ]).collect::<Vec<Entity>>();
1762 ///
1763 /// let mut query = world.query::<(&mut Position, &Velocity)>();
1764 /// for (mut position, velocity) in query.iter_mut(&mut world) {
1765 /// position.x += velocity.x;
1766 /// position.y += velocity.y;
1767 /// }
1768 ///
1769 /// assert_eq!(world.get::<Position>(entities[0]).unwrap(), &Position { x: 1.0, y: 0.0 });
1770 /// assert_eq!(world.get::<Position>(entities[1]).unwrap(), &Position { x: 0.0, y: 1.0 });
1771 /// ```
1772 ///
1773 /// To iterate over entities in a deterministic order,
1774 /// sort the results of the query using the desired component as a key.
1775 /// Note that this requires fetching the whole result set from the query
1776 /// and allocation of a [`Vec`] to store it.
1777 ///
1778 /// ```
1779 /// use bevy_ecs::{component::Component, entity::Entity, world::World};
1780 ///
1781 /// #[derive(Component, PartialEq, Eq, PartialOrd, Ord, Debug)]
1782 /// struct Order(i32);
1783 /// #[derive(Component, PartialEq, Debug)]
1784 /// struct Label(&'static str);
1785 ///
1786 /// let mut world = World::new();
1787 /// let a = world.spawn((Order(2), Label("second"))).id();
1788 /// let b = world.spawn((Order(3), Label("third"))).id();
1789 /// let c = world.spawn((Order(1), Label("first"))).id();
1790 /// let mut entities = world.query::<(Entity, &Order, &Label)>()
1791 /// .iter(&world)
1792 /// .collect::<Vec<_>>();
1793 /// // Sort the query results by their `Order` component before comparing
1794 /// // to expected results. Query iteration order should not be relied on.
1795 /// entities.sort_by_key(|e| e.1);
1796 /// assert_eq!(entities, vec![
1797 /// (c, &Order(1), &Label("first")),
1798 /// (a, &Order(2), &Label("second")),
1799 /// (b, &Order(3), &Label("third")),
1800 /// ]);
1801 /// ```
1802 #[inline]
1803 pub fn query<D: QueryData>(&mut self) -> QueryState<D, ()> {
1804 self.query_filtered::<D, ()>()
1805 }
1806
1807 /// Returns [`QueryState`] for the given filtered [`QueryData`], which is used to efficiently
1808 /// run queries on the [`World`] by storing and reusing the [`QueryState`].
1809 /// ```
1810 /// use bevy_ecs::{component::Component, entity::Entity, world::World, query::With};
1811 ///
1812 /// #[derive(Component)]
1813 /// struct A;
1814 /// #[derive(Component)]
1815 /// struct B;
1816 ///
1817 /// let mut world = World::new();
1818 /// let e1 = world.spawn(A).id();
1819 /// let e2 = world.spawn((A, B)).id();
1820 ///
1821 /// let mut query = world.query_filtered::<Entity, With<B>>();
1822 /// let matching_entities = query.iter(&world).collect::<Vec<Entity>>();
1823 ///
1824 /// assert_eq!(matching_entities, vec![e2]);
1825 /// ```
1826 #[inline]
1827 pub fn query_filtered<D: QueryData, F: QueryFilter>(&mut self) -> QueryState<D, F> {
1828 QueryState::new(self)
1829 }
1830
1831 /// Returns [`QueryState`] for the given [`QueryData`], which is used to efficiently
1832 /// run queries on the [`World`] by storing and reusing the [`QueryState`].
1833 /// ```
1834 /// use bevy_ecs::{component::Component, entity::Entity, world::World};
1835 ///
1836 /// #[derive(Component, Debug, PartialEq)]
1837 /// struct Position {
1838 /// x: f32,
1839 /// y: f32,
1840 /// }
1841 ///
1842 /// let mut world = World::new();
1843 /// world.spawn_batch(vec![
1844 /// Position { x: 0.0, y: 0.0 },
1845 /// Position { x: 1.0, y: 1.0 },
1846 /// ]);
1847 ///
1848 /// fn get_positions(world: &World) -> Vec<(Entity, &Position)> {
1849 /// let mut query = world.try_query::<(Entity, &Position)>().unwrap();
1850 /// query.iter(world).collect()
1851 /// }
1852 ///
1853 /// let positions = get_positions(&world);
1854 ///
1855 /// assert_eq!(world.get::<Position>(positions[0].0).unwrap(), positions[0].1);
1856 /// assert_eq!(world.get::<Position>(positions[1].0).unwrap(), positions[1].1);
1857 /// ```
1858 ///
1859 /// Requires only an immutable world reference, but may fail if, for example,
1860 /// the components that make up this query have not been registered into the world.
1861 /// ```
1862 /// use bevy_ecs::{component::Component, entity::Entity, world::World};
1863 ///
1864 /// #[derive(Component)]
1865 /// struct A;
1866 ///
1867 /// let mut world = World::new();
1868 ///
1869 /// let none_query = world.try_query::<&A>();
1870 /// assert!(none_query.is_none());
1871 ///
1872 /// world.register_component::<A>();
1873 ///
1874 /// let some_query = world.try_query::<&A>();
1875 /// assert!(some_query.is_some());
1876 /// ```
1877 #[inline]
1878 pub fn try_query<D: QueryData>(&self) -> Option<QueryState<D, ()>> {
1879 self.try_query_filtered::<D, ()>()
1880 }
1881
1882 /// Returns [`QueryState`] for the given filtered [`QueryData`], which is used to efficiently
1883 /// run queries on the [`World`] by storing and reusing the [`QueryState`].
1884 /// ```
1885 /// use bevy_ecs::{component::Component, entity::Entity, world::World, query::With};
1886 ///
1887 /// #[derive(Component)]
1888 /// struct A;
1889 /// #[derive(Component)]
1890 /// struct B;
1891 ///
1892 /// let mut world = World::new();
1893 /// let e1 = world.spawn(A).id();
1894 /// let e2 = world.spawn((A, B)).id();
1895 ///
1896 /// let mut query = world.try_query_filtered::<Entity, With<B>>().unwrap();
1897 /// let matching_entities = query.iter(&world).collect::<Vec<Entity>>();
1898 ///
1899 /// assert_eq!(matching_entities, vec![e2]);
1900 /// ```
1901 ///
1902 /// Requires only an immutable world reference, but may fail if, for example,
1903 /// the components that make up this query have not been registered into the world.
1904 #[inline]
1905 pub fn try_query_filtered<D: QueryData, F: QueryFilter>(&self) -> Option<QueryState<D, F>> {
1906 QueryState::try_new(self)
1907 }
1908
1909 /// Returns an iterator of entities that had components of type `T` removed
1910 /// since the last call to [`World::clear_trackers`].
1911 pub fn removed<T: Component>(&self) -> impl Iterator<Item = Entity> + '_ {
1912 self.components
1913 .get_valid_id(TypeId::of::<T>())
1914 .map(|component_id| self.removed_with_id(component_id))
1915 .into_iter()
1916 .flatten()
1917 }
1918
1919 /// Returns an iterator of entities that had components with the given `component_id` removed
1920 /// since the last call to [`World::clear_trackers`].
1921 pub fn removed_with_id(&self, component_id: ComponentId) -> impl Iterator<Item = Entity> + '_ {
1922 self.removed_components
1923 .get(component_id)
1924 .map(|removed| removed.iter_current_update_messages().cloned())
1925 .into_iter()
1926 .flatten()
1927 .map(Into::into)
1928 }
1929
1930 /// Registers a new non-send resource type and returns the [`ComponentId`] created for it.
1931 ///
1932 /// This enables the dynamic registration of new non-send resources definitions at runtime for
1933 /// advanced use cases.
1934 ///
1935 /// # Note
1936 ///
1937 /// Registering a non-send resource does not insert it into [`World`]. For insertion, you could use
1938 /// [`World::insert_non_send_by_id`].
1939 pub fn register_non_send_with_descriptor(
1940 &mut self,
1941 descriptor: ComponentDescriptor,
1942 ) -> ComponentId {
1943 self.components_registrator()
1944 .register_component_with_descriptor(descriptor)
1945 }
1946
1947 fn insert_resource_if_not_exists_with_caller<R: Resource>(
1948 &mut self,
1949 func: impl FnOnce(&mut World) -> R,
1950 caller: MaybeLocation,
1951 ) -> (ComponentId, EntityWorldMut<'_>) {
1952 let resource_id = self.register_component::<R>();
1953
1954 if let Some(entity) = self.resource_entities.get(resource_id) {
1955 let entity_ref = self.get_entity(entity).expect("ResourceCache is in sync");
1956 if !entity_ref.contains_id(resource_id) {
1957 let resource = func(self);
1958 move_as_ptr!(resource);
1959 self.entity_mut(entity).insert_with_caller(
1960 resource,
1961 InsertMode::Replace,
1962 caller,
1963 RelationshipHookMode::Run,
1964 );
1965 }
1966 return (resource_id, self.entity_mut(entity));
1967 }
1968
1969 let resource = func(self);
1970 move_as_ptr!(resource);
1971 let entity_mut = self.spawn_with_caller(resource, caller); // ResourceCache is updated automatically
1972 (resource_id, entity_mut)
1973 }
1974
1975 /// Initializes a new resource and returns the [`ComponentId`] created for it.
1976 ///
1977 /// If the resource already exists, nothing happens.
1978 ///
1979 /// The value given by the [`FromWorld::from_world`] method will be used.
1980 /// Note that any resource with the [`Default`] trait automatically implements [`FromWorld`],
1981 /// and those default values will be here instead.
1982 #[inline]
1983 #[track_caller]
1984 pub fn init_resource<R: Resource + FromWorld>(&mut self) -> ComponentId {
1985 let caller = MaybeLocation::caller();
1986 self.insert_resource_if_not_exists_with_caller(R::from_world, caller)
1987 .0
1988 }
1989
1990 /// Inserts a new resource with the given `value`.
1991 ///
1992 /// Resources are "unique" data of a given type.
1993 /// If you insert a resource of a type that already exists,
1994 /// you will overwrite any existing data.
1995 #[inline]
1996 #[track_caller]
1997 pub fn insert_resource<R: Resource>(&mut self, value: R) {
1998 self.insert_resource_with_caller(value, MaybeLocation::caller());
1999 }
2000
2001 /// Split into a new function so we can pass the calling location into the function when using
2002 /// as a command.
2003 #[inline]
2004 pub(crate) fn insert_resource_with_caller<R: Resource>(
2005 &mut self,
2006 value: R,
2007 caller: MaybeLocation,
2008 ) {
2009 let component_id = self.components_registrator().register_component::<R>();
2010 OwningPtr::make(value, |ptr| {
2011 // SAFETY: component_id was just initialized and corresponds to resource of type R.
2012 unsafe {
2013 self.insert_resource_by_id(component_id, ptr, caller);
2014 }
2015 });
2016 }
2017
2018 /// Initializes a new non-send resource and returns the [`ComponentId`] created for it.
2019 #[deprecated(since = "0.19.0", note = "use World::init_non_send")]
2020 pub fn init_non_send_resource<R: 'static + FromWorld>(&mut self) -> ComponentId {
2021 self.init_non_send::<R>()
2022 }
2023
2024 /// Initializes new non-send data and returns the [`ComponentId`] created for it.
2025 ///
2026 /// If the data already exists, nothing happens.
2027 ///
2028 /// The value given by the [`FromWorld::from_world`] method will be used.
2029 /// Note that any non-send data with the `Default` trait automatically implements
2030 /// `FromWorld`, and those default values will be here instead.
2031 ///
2032 /// # Panics
2033 ///
2034 /// Panics if called from a thread other than the main thread.
2035 #[inline]
2036 #[track_caller]
2037 pub fn init_non_send<R: 'static + FromWorld>(&mut self) -> ComponentId {
2038 let caller = MaybeLocation::caller();
2039 let component_id = self.components_registrator().register_non_send::<R>();
2040 if self
2041 .storages
2042 .non_sends
2043 .get(component_id)
2044 .is_none_or(|data| !data.is_present())
2045 {
2046 let value = R::from_world(self);
2047 OwningPtr::make(value, |ptr| {
2048 // SAFETY: component_id was just initialized and corresponds to resource of type R.
2049 unsafe {
2050 self.insert_non_send_by_id(component_id, ptr, caller);
2051 }
2052 });
2053 }
2054 component_id
2055 }
2056
2057 /// Inserts a new non-send resource with the given `value`.
2058 #[deprecated(since = "0.19.0", note = "use World::insert_non_send")]
2059 pub fn insert_non_send_resource<R: 'static>(&mut self, value: R) {
2060 self.insert_non_send(value);
2061 }
2062
2063 /// Inserts new non-send data with the given `value`.
2064 ///
2065 /// `NonSend` data cannot be sent across threads,
2066 /// and do not need the `Send + Sync` bounds.
2067 /// Systems with `NonSend` resources are always scheduled on the main thread.
2068 ///
2069 /// # Panics
2070 /// If a value is already present, this function will panic if called
2071 /// from a different thread than where the original value was inserted from.
2072 #[inline]
2073 #[track_caller]
2074 pub fn insert_non_send<R: 'static>(&mut self, value: R) {
2075 let caller = MaybeLocation::caller();
2076 let component_id = self.components_registrator().register_non_send::<R>();
2077 OwningPtr::make(value, |ptr| {
2078 // SAFETY: component_id was just initialized and corresponds to the data of type R.
2079 unsafe {
2080 self.insert_non_send_by_id(component_id, ptr, caller);
2081 }
2082 });
2083 }
2084
2085 /// Removes the resource of a given type and returns it, if it exists. Otherwise returns `None`.
2086 #[inline]
2087 pub fn remove_resource<R: Resource>(&mut self) -> Option<R> {
2088 let resource_id = self.component_id::<R>()?;
2089 let entity = self.resource_entities.get(resource_id)?;
2090 let value = self
2091 .get_entity_mut(entity)
2092 .expect("ResourceCache is in sync")
2093 .take::<R>()?;
2094 Some(value)
2095 }
2096
2097 /// Removes a `!Send` resource from the world and returns it, if present.
2098 #[deprecated(since = "0.19.0", note = "use World::remove_non_send")]
2099 pub fn remove_non_send_resource<R: 'static>(&mut self) -> Option<R> {
2100 self.remove_non_send::<R>()
2101 }
2102
2103 /// Removes `!Send` data from the world and returns it, if present.
2104 ///
2105 /// `NonSend` resources cannot be sent across threads,
2106 /// and do not need the `Send + Sync` bounds.
2107 /// Systems with `NonSend` data are always scheduled on the main thread.
2108 ///
2109 /// Returns `None` if a value was not previously present.
2110 ///
2111 /// # Panics
2112 /// If a value is present, this function will panic if called from a different
2113 /// thread than where the value was inserted from.
2114 #[inline]
2115 pub fn remove_non_send<R: 'static>(&mut self) -> Option<R> {
2116 let component_id = self.components.get_valid_id(TypeId::of::<R>())?;
2117 let (ptr, _, _) = self.storages.non_sends.get_mut(component_id)?.remove()?;
2118 // SAFETY: `component_id` was gotten via looking up the `R` type
2119 unsafe { Some(ptr.read::<R>()) }
2120 }
2121
2122 /// Returns `true` if a resource of type `R` exists. Otherwise returns `false`.
2123 #[inline]
2124 pub fn contains_resource<R: Resource>(&self) -> bool {
2125 self.components
2126 .get_valid_id(TypeId::of::<R>())
2127 .is_some_and(|component_id| self.contains_resource_by_id(component_id))
2128 }
2129
2130 /// Returns `true` if a resource with provided `component_id` exists. Otherwise returns `false`.
2131 #[inline]
2132 pub fn contains_resource_by_id(&self, component_id: ComponentId) -> bool {
2133 if let Some(entity) = self.resource_entities.get(component_id)
2134 && let Ok(entity_ref) = self.get_entity(entity)
2135 {
2136 return entity_ref.contains_id(component_id);
2137 }
2138 false
2139 }
2140
2141 /// Returns `true` if `!Send` data of type `R` exists. Otherwise returns `false`.
2142 #[inline]
2143 pub fn contains_non_send<R: 'static>(&self) -> bool {
2144 self.components
2145 .get_valid_id(TypeId::of::<R>())
2146 .and_then(|component_id| self.storages.non_sends.get(component_id))
2147 .is_some_and(NonSendData::is_present)
2148 }
2149
2150 /// Returns `true` if `!Send` data with `component_id` exists. Otherwise returns `false`.
2151 #[inline]
2152 pub fn contains_non_send_by_id(&self, component_id: ComponentId) -> bool {
2153 self.storages
2154 .non_sends
2155 .get(component_id)
2156 .is_some_and(NonSendData::is_present)
2157 }
2158
2159 /// Returns `true` if a resource of type `R` exists and was added since the world's
2160 /// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
2161 ///
2162 /// This means that:
2163 /// - When called from an exclusive system, this will check for additions since the system last ran.
2164 /// - When called elsewhere, this will check for additions since the last time that [`World::clear_trackers`]
2165 /// was called.
2166 pub fn is_resource_added<R: Resource>(&self) -> bool {
2167 self.components
2168 .get_valid_id(TypeId::of::<R>())
2169 .is_some_and(|component_id| self.is_resource_added_by_id(component_id))
2170 }
2171
2172 /// Returns `true` if a resource with id `component_id` exists and was added since the world's
2173 /// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
2174 ///
2175 /// This means that:
2176 /// - When called from an exclusive system, this will check for additions since the system last ran.
2177 /// - When called elsewhere, this will check for additions since the last time that [`World::clear_trackers`]
2178 /// was called.
2179 pub fn is_resource_added_by_id(&self, component_id: ComponentId) -> bool {
2180 self.get_resource_change_ticks_by_id(component_id)
2181 .is_some_and(|ticks| ticks.is_added(self.last_change_tick(), self.read_change_tick()))
2182 }
2183
2184 /// Returns `true` if a resource of type `R` exists and was modified since the world's
2185 /// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
2186 ///
2187 /// This means that:
2188 /// - When called from an exclusive system, this will check for changes since the system last ran.
2189 /// - When called elsewhere, this will check for changes since the last time that [`World::clear_trackers`]
2190 /// was called.
2191 pub fn is_resource_changed<R: Resource>(&self) -> bool {
2192 self.components
2193 .get_valid_id(TypeId::of::<R>())
2194 .is_some_and(|component_id| self.is_resource_changed_by_id(component_id))
2195 }
2196
2197 /// Returns `true` if a resource with id `component_id` exists and was modified since the world's
2198 /// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
2199 ///
2200 /// This means that:
2201 /// - When called from an exclusive system, this will check for changes since the system last ran.
2202 /// - When called elsewhere, this will check for changes since the last time that [`World::clear_trackers`]
2203 /// was called.
2204 pub fn is_resource_changed_by_id(&self, component_id: ComponentId) -> bool {
2205 self.get_resource_change_ticks_by_id(component_id)
2206 .is_some_and(|ticks| ticks.is_changed(self.last_change_tick(), self.read_change_tick()))
2207 }
2208
2209 /// Retrieves the change ticks for the given resource.
2210 pub fn get_resource_change_ticks<R: Resource>(&self) -> Option<ComponentTicks> {
2211 self.components
2212 .get_valid_id(TypeId::of::<R>())
2213 .and_then(|component_id| self.get_resource_change_ticks_by_id(component_id))
2214 }
2215
2216 /// Retrieves the change ticks for the given [`ComponentId`].
2217 ///
2218 /// **You should prefer to use the typed API [`World::get_resource_change_ticks`] where possible.**
2219 pub fn get_resource_change_ticks_by_id(
2220 &self,
2221 component_id: ComponentId,
2222 ) -> Option<ComponentTicks> {
2223 let entity = self.resource_entities.get(component_id)?;
2224 let entity_ref = self.get_entity(entity).ok()?;
2225 entity_ref.get_change_ticks_by_id(component_id)
2226 }
2227
2228 /// Gets a reference to the resource of the given type
2229 ///
2230 /// # Panics
2231 ///
2232 /// Panics if the resource does not exist.
2233 /// Use [`get_resource`](World::get_resource) instead if you want to handle this case.
2234 ///
2235 /// If you want to instead insert a value if the resource does not exist,
2236 /// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
2237 #[inline]
2238 #[track_caller]
2239 pub fn resource<R: Resource>(&self) -> &R {
2240 match self.get_resource() {
2241 Some(x) => x,
2242 None => panic!(
2243 "Requested resource {} does not exist in the `World`.
2244 Did you forget to add it using `app.insert_resource` / `app.init_resource`?
2245 Resources are also implicitly added via `app.add_message`,
2246 and can be added by plugins.",
2247 DebugName::type_name::<R>()
2248 ),
2249 }
2250 }
2251
2252 /// Gets a reference to the resource of the given type
2253 ///
2254 /// # Panics
2255 ///
2256 /// Panics if the resource does not exist.
2257 /// Use [`get_resource_ref`](World::get_resource_ref) instead if you want to handle this case.
2258 ///
2259 /// If you want to instead insert a value if the resource does not exist,
2260 /// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
2261 #[inline]
2262 #[track_caller]
2263 pub fn resource_ref<R: Resource>(&self) -> Ref<'_, R> {
2264 match self.get_resource_ref() {
2265 Some(x) => x,
2266 None => panic!(
2267 "Requested resource {} does not exist in the `World`.
2268 Did you forget to add it using `app.insert_resource` / `app.init_resource`?
2269 Resources are also implicitly added via `app.add_message`,
2270 and can be added by plugins.",
2271 DebugName::type_name::<R>()
2272 ),
2273 }
2274 }
2275
2276 /// Gets a mutable reference to the resource of the given type
2277 ///
2278 /// # Panics
2279 ///
2280 /// Panics if the resource does not exist.
2281 /// Use [`get_resource_mut`](World::get_resource_mut) instead if you want to handle this case.
2282 ///
2283 /// If you want to instead insert a value if the resource does not exist,
2284 /// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
2285 #[inline]
2286 #[track_caller]
2287 pub fn resource_mut<R: Resource<Mutability = Mutable>>(&mut self) -> Mut<'_, R> {
2288 match self.get_resource_mut() {
2289 Some(x) => x,
2290 None => panic!(
2291 "Requested resource {} does not exist in the `World`.
2292 Did you forget to add it using `app.insert_resource` / `app.init_resource`?
2293 Resources are also implicitly added via `app.add_message`,
2294 and can be added by plugins.",
2295 DebugName::type_name::<R>()
2296 ),
2297 }
2298 }
2299
2300 /// Gets a reference to the resource of the given type if it exists
2301 #[inline]
2302 pub fn get_resource<R: Resource>(&self) -> Option<&R> {
2303 // SAFETY:
2304 // - `as_unsafe_world_cell_readonly` gives permission to access everything immutably
2305 // - `&self` ensures nothing in world is borrowed mutably
2306 unsafe { self.as_unsafe_world_cell_readonly().get_resource() }
2307 }
2308
2309 /// Gets a reference including change detection to the resource of the given type if it exists.
2310 #[inline]
2311 pub fn get_resource_ref<R: Resource>(&self) -> Option<Ref<'_, R>> {
2312 // SAFETY:
2313 // - `as_unsafe_world_cell_readonly` gives permission to access everything immutably
2314 // - `&self` ensures nothing in world is borrowed mutably
2315 unsafe { self.as_unsafe_world_cell_readonly().get_resource_ref() }
2316 }
2317
2318 /// Gets a mutable reference to the resource of the given type if it exists
2319 #[inline]
2320 pub fn get_resource_mut<R: Resource<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, R>> {
2321 // SAFETY:
2322 // - `as_unsafe_world_cell` gives permission to access everything mutably
2323 // - `&mut self` ensures nothing in world is borrowed
2324 unsafe { self.as_unsafe_world_cell().get_resource_mut() }
2325 }
2326
2327 /// Gets a mutable reference to the resource of type `T` if it exists,
2328 /// otherwise inserts the resource using the result of calling `func`.
2329 ///
2330 /// # Example
2331 ///
2332 /// ```
2333 /// # use bevy_ecs::prelude::*;
2334 /// #
2335 /// #[derive(Resource)]
2336 /// struct MyResource(i32);
2337 ///
2338 /// # let mut world = World::new();
2339 /// let my_res = world.get_resource_or_insert_with(|| MyResource(10));
2340 /// assert_eq!(my_res.0, 10);
2341 /// ```
2342 #[inline]
2343 #[track_caller]
2344 pub fn get_resource_or_insert_with<R: Resource<Mutability = Mutable>>(
2345 &mut self,
2346 func: impl FnOnce() -> R,
2347 ) -> Mut<'_, R> {
2348 let caller = MaybeLocation::caller();
2349 let (resource_id, entity) =
2350 self.insert_resource_if_not_exists_with_caller(|_world: &mut World| func(), caller);
2351 let untyped = entity
2352 .into_mut_by_id(resource_id)
2353 .expect("Resource must exist");
2354 // SAFETY: resource is of type R
2355 unsafe { untyped.with_type() }
2356 }
2357
2358 /// Gets a mutable reference to the resource of type `T` if it exists,
2359 /// otherwise initializes the resource by calling its [`FromWorld`]
2360 /// implementation.
2361 ///
2362 /// # Example
2363 ///
2364 /// ```
2365 /// # use bevy_ecs::prelude::*;
2366 /// #
2367 /// #[derive(Resource)]
2368 /// struct Foo(i32);
2369 ///
2370 /// impl Default for Foo {
2371 /// fn default() -> Self {
2372 /// Self(15)
2373 /// }
2374 /// }
2375 ///
2376 /// #[derive(Resource)]
2377 /// struct MyResource(i32);
2378 ///
2379 /// impl FromWorld for MyResource {
2380 /// fn from_world(world: &mut World) -> Self {
2381 /// let foo = world.get_resource_or_init::<Foo>();
2382 /// Self(foo.0 * 2)
2383 /// }
2384 /// }
2385 ///
2386 /// # let mut world = World::new();
2387 /// let my_res = world.get_resource_or_init::<MyResource>();
2388 /// assert_eq!(my_res.0, 30);
2389 /// ```
2390 #[track_caller]
2391 pub fn get_resource_or_init<R: Resource<Mutability = Mutable> + FromWorld>(
2392 &mut self,
2393 ) -> Mut<'_, R> {
2394 let caller = MaybeLocation::caller();
2395 let (resource_id, entity) =
2396 self.insert_resource_if_not_exists_with_caller(R::from_world, caller);
2397 let untyped = entity
2398 .into_mut_by_id(resource_id)
2399 .expect("Resource must exist");
2400 // SAFETY: resource is of type R
2401 unsafe { untyped.with_type() }
2402 }
2403
2404 /// Gets an immutable reference to a non-send resource of the given type, if it exists.
2405 #[deprecated(since = "0.19.0", note = "use World::non_send")]
2406 pub fn non_send_resource<R: 'static>(&self) -> &R {
2407 self.non_send::<R>()
2408 }
2409
2410 /// Gets an immutable reference to the non-send data of the given type, if it exists.
2411 ///
2412 /// # Panics
2413 ///
2414 /// Panics if the data does not exist.
2415 /// Use [`get_non_send`](World::get_non_send) instead if you want to handle this case.
2416 ///
2417 /// This function will panic if it isn't called from the same thread that the resource was inserted from.
2418 #[inline]
2419 #[track_caller]
2420 pub fn non_send<R: 'static>(&self) -> &R {
2421 match self.get_non_send() {
2422 Some(x) => x,
2423 None => panic!(
2424 "Requested non-send resource {} does not exist in the `World`.
2425 Did you forget to add it using `app.insert_non_send` / `app.init_non_send`?
2426 Non-send resources can also be added by plugins.",
2427 DebugName::type_name::<R>()
2428 ),
2429 }
2430 }
2431
2432 /// Gets a mutable reference to a non-send resource of the given type, if it exists.
2433 #[deprecated(since = "0.19.0", note = "use World::non_send_mut")]
2434 pub fn non_send_resource_mut<R: 'static>(&mut self) -> Mut<'_, R> {
2435 self.non_send_mut::<R>()
2436 }
2437
2438 /// Gets a mutable reference to the non-send data of the given type, if it exists.
2439 ///
2440 /// # Panics
2441 ///
2442 /// Panics if the data does not exist.
2443 /// Use [`get_non_send_mut`](World::get_non_send_mut) instead if you want to handle this case.
2444 ///
2445 /// This function will panic if it isn't called from the same thread that the resource was inserted from.
2446 #[inline]
2447 #[track_caller]
2448 pub fn non_send_mut<R: 'static>(&mut self) -> Mut<'_, R> {
2449 match self.get_non_send_mut() {
2450 Some(x) => x,
2451 None => panic!(
2452 "Requested non-send resource {} does not exist in the `World`.
2453 Did you forget to add it using `app.insert_non_send` / `app.init_non_send`?
2454 Non-send resources can also be added by plugins.",
2455 DebugName::type_name::<R>()
2456 ),
2457 }
2458 }
2459
2460 /// Gets a reference to a non-send resource of the given type, if it exists.
2461 /// Otherwise returns `None`.
2462 #[deprecated(since = "0.19.0", note = "use World::get_non_send")]
2463 pub fn get_non_send_resource<R: 'static>(&self) -> Option<&R> {
2464 self.get_non_send::<R>()
2465 }
2466
2467 /// Gets a reference to the non-send data of the given type, if it exists.
2468 /// Otherwise returns `None`.
2469 ///
2470 /// # Panics
2471 /// This function will panic if it isn't called from the same thread that the resource was inserted from.
2472 #[inline]
2473 pub fn get_non_send<R: 'static>(&self) -> Option<&R> {
2474 // SAFETY:
2475 // - `as_unsafe_world_cell_readonly` gives permission to access the entire world immutably
2476 // - `&self` ensures that there are no mutable borrows of world data
2477 unsafe { self.as_unsafe_world_cell_readonly().get_non_send() }
2478 }
2479
2480 /// Gets a mutable reference to a non-send resource of the given type, if it exists.
2481 /// Otherwise returns `None`.
2482 #[deprecated(since = "0.19.0", note = "use World::get_non_send_mut")]
2483 pub fn get_non_send_resource_mut<R: 'static>(&mut self) -> Option<Mut<'_, R>> {
2484 self.get_non_send_mut::<R>()
2485 }
2486
2487 /// Gets a mutable reference to the non-send data of the given type, if it exists.
2488 /// Otherwise returns `None`.
2489 ///
2490 /// # Panics
2491 /// This function will panic if it isn't called from the same thread that the resource was inserted from.
2492 #[inline]
2493 pub fn get_non_send_mut<R: 'static>(&mut self) -> Option<Mut<'_, R>> {
2494 // SAFETY:
2495 // - `as_unsafe_world_cell` gives permission to access the entire world mutably
2496 // - `&mut self` ensures that there are no borrows of world data
2497 unsafe { self.as_unsafe_world_cell().get_non_send_mut() }
2498 }
2499
2500 /// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2501 /// adds the `Bundle` of components to each `Entity`.
2502 /// This is faster than doing equivalent operations one-by-one.
2503 ///
2504 /// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2505 /// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2506 ///
2507 /// This will overwrite any previous values of components shared by the `Bundle`.
2508 /// See [`World::insert_batch_if_new`] to keep the old values instead.
2509 ///
2510 /// # Panics
2511 ///
2512 /// This function will panic if any of the associated entities do not exist.
2513 ///
2514 /// For the fallible version, see [`World::try_insert_batch`].
2515 #[track_caller]
2516 pub fn insert_batch<I, B>(&mut self, batch: I)
2517 where
2518 I: IntoIterator,
2519 I::IntoIter: Iterator<Item = (Entity, B)>,
2520 B: Bundle<Effect: NoBundleEffect>,
2521 {
2522 self.insert_batch_with_caller(batch, InsertMode::Replace, MaybeLocation::caller());
2523 }
2524
2525 /// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2526 /// adds the `Bundle` of components to each `Entity` without overwriting.
2527 /// This is faster than doing equivalent operations one-by-one.
2528 ///
2529 /// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2530 /// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2531 ///
2532 /// This is the same as [`World::insert_batch`], but in case of duplicate
2533 /// components it will leave the old values instead of replacing them with new ones.
2534 ///
2535 /// # Panics
2536 ///
2537 /// This function will panic if any of the associated entities do not exist.
2538 ///
2539 /// For the fallible version, see [`World::try_insert_batch_if_new`].
2540 #[track_caller]
2541 pub fn insert_batch_if_new<I, B>(&mut self, batch: I)
2542 where
2543 I: IntoIterator,
2544 I::IntoIter: Iterator<Item = (Entity, B)>,
2545 B: Bundle<Effect: NoBundleEffect>,
2546 {
2547 self.insert_batch_with_caller(batch, InsertMode::Keep, MaybeLocation::caller());
2548 }
2549
2550 /// Split into a new function so we can differentiate the calling location.
2551 ///
2552 /// This can be called by:
2553 /// - [`World::insert_batch`]
2554 /// - [`World::insert_batch_if_new`]
2555 #[inline]
2556 pub(crate) fn insert_batch_with_caller<I, B>(
2557 &mut self,
2558 batch: I,
2559 insert_mode: InsertMode,
2560 caller: MaybeLocation,
2561 ) where
2562 I: IntoIterator,
2563 I::IntoIter: Iterator<Item = (Entity, B)>,
2564 B: Bundle<Effect: NoBundleEffect>,
2565 {
2566 struct InserterArchetypeCache<'w> {
2567 inserter: BundleInserter<'w>,
2568 archetype_id: ArchetypeId,
2569 }
2570
2571 let change_tick = self.change_tick();
2572 let bundle_id = self.register_bundle_info::<B>();
2573
2574 let mut batch_iter = batch.into_iter();
2575
2576 if let Some((first_entity, first_bundle)) = batch_iter.next() {
2577 match self.entities().get_spawned(first_entity) {
2578 Err(err) => {
2579 panic!("error[B0003]: Could not insert a bundle (of type `{}`) for entity {first_entity} because: {err}. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::<B>());
2580 }
2581 Ok(first_location) => {
2582 let mut cache = InserterArchetypeCache {
2583 // SAFETY: we initialized this bundle_id in `register_info`
2584 inserter: unsafe {
2585 BundleInserter::new_with_id(
2586 self,
2587 first_location.archetype_id,
2588 bundle_id,
2589 change_tick,
2590 )
2591 },
2592 archetype_id: first_location.archetype_id,
2593 };
2594 move_as_ptr!(first_bundle);
2595 // SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
2596 unsafe {
2597 cache.inserter.insert(
2598 first_entity,
2599 first_location,
2600 first_bundle,
2601 insert_mode,
2602 caller,
2603 RelationshipHookMode::Run,
2604 )
2605 };
2606
2607 for (entity, bundle) in batch_iter {
2608 match cache.inserter.entities().get_spawned(entity) {
2609 Ok(location) => {
2610 if location.archetype_id != cache.archetype_id {
2611 cache = InserterArchetypeCache {
2612 // SAFETY: we initialized this bundle_id in `register_info`
2613 inserter: unsafe {
2614 BundleInserter::new_with_id(
2615 self,
2616 location.archetype_id,
2617 bundle_id,
2618 change_tick,
2619 )
2620 },
2621 archetype_id: location.archetype_id,
2622 }
2623 }
2624 move_as_ptr!(bundle);
2625 // SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
2626 unsafe {
2627 cache.inserter.insert(
2628 entity,
2629 location,
2630 bundle,
2631 insert_mode,
2632 caller,
2633 RelationshipHookMode::Run,
2634 )
2635 };
2636 }
2637 Err(err) => {
2638 panic!("error[B0003]: Could not insert a bundle (of type `{}`) for entity {entity} because: {err}. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::<B>());
2639 }
2640 }
2641 }
2642 }
2643 }
2644 }
2645 }
2646
2647 /// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2648 /// adds the `Bundle` of components to each `Entity`.
2649 /// This is faster than doing equivalent operations one-by-one.
2650 ///
2651 /// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2652 /// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2653 ///
2654 /// This will overwrite any previous values of components shared by the `Bundle`.
2655 /// See [`World::try_insert_batch_if_new`] to keep the old values instead.
2656 ///
2657 /// Returns a [`TryInsertBatchError`] if any of the provided entities do not exist.
2658 ///
2659 /// For the panicking version, see [`World::insert_batch`].
2660 #[track_caller]
2661 pub fn try_insert_batch<I, B>(&mut self, batch: I) -> Result<(), TryInsertBatchError>
2662 where
2663 I: IntoIterator,
2664 I::IntoIter: Iterator<Item = (Entity, B)>,
2665 B: Bundle<Effect: NoBundleEffect>,
2666 {
2667 self.try_insert_batch_with_caller(batch, InsertMode::Replace, MaybeLocation::caller())
2668 }
2669 /// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2670 /// adds the `Bundle` of components to each `Entity` without overwriting.
2671 /// This is faster than doing equivalent operations one-by-one.
2672 ///
2673 /// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2674 /// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2675 ///
2676 /// This is the same as [`World::try_insert_batch`], but in case of duplicate
2677 /// components it will leave the old values instead of replacing them with new ones.
2678 ///
2679 /// Returns a [`TryInsertBatchError`] if any of the provided entities do not exist.
2680 ///
2681 /// For the panicking version, see [`World::insert_batch_if_new`].
2682 #[track_caller]
2683 pub fn try_insert_batch_if_new<I, B>(&mut self, batch: I) -> Result<(), TryInsertBatchError>
2684 where
2685 I: IntoIterator,
2686 I::IntoIter: Iterator<Item = (Entity, B)>,
2687 B: Bundle<Effect: NoBundleEffect>,
2688 {
2689 self.try_insert_batch_with_caller(batch, InsertMode::Keep, MaybeLocation::caller())
2690 }
2691
2692 /// Split into a new function so we can differentiate the calling location.
2693 ///
2694 /// This can be called by:
2695 /// - [`World::try_insert_batch`]
2696 /// - [`World::try_insert_batch_if_new`]
2697 /// - [`Commands::insert_batch`]
2698 /// - [`Commands::insert_batch_if_new`]
2699 /// - [`Commands::try_insert_batch`]
2700 /// - [`Commands::try_insert_batch_if_new`]
2701 #[inline]
2702 pub(crate) fn try_insert_batch_with_caller<I, B>(
2703 &mut self,
2704 batch: I,
2705 insert_mode: InsertMode,
2706 caller: MaybeLocation,
2707 ) -> Result<(), TryInsertBatchError>
2708 where
2709 I: IntoIterator,
2710 I::IntoIter: Iterator<Item = (Entity, B)>,
2711 B: Bundle<Effect: NoBundleEffect>,
2712 {
2713 struct InserterArchetypeCache<'w> {
2714 inserter: BundleInserter<'w>,
2715 archetype_id: ArchetypeId,
2716 }
2717
2718 let change_tick = self.change_tick();
2719 let bundle_id = self.register_bundle_info::<B>();
2720
2721 let mut invalid_entities = Vec::<Entity>::new();
2722 let mut batch_iter = batch.into_iter();
2723
2724 // We need to find the first valid entity so we can initialize the bundle inserter.
2725 // This differs from `insert_batch_with_caller` because that method can just panic
2726 // if the first entity is invalid, whereas this method needs to keep going.
2727 let cache = loop {
2728 if let Some((first_entity, first_bundle)) = batch_iter.next() {
2729 if let Ok(first_location) = self.entities().get_spawned(first_entity) {
2730 let mut cache = InserterArchetypeCache {
2731 // SAFETY: we initialized this bundle_id in `register_bundle_info`
2732 inserter: unsafe {
2733 BundleInserter::new_with_id(
2734 self,
2735 first_location.archetype_id,
2736 bundle_id,
2737 change_tick,
2738 )
2739 },
2740 archetype_id: first_location.archetype_id,
2741 };
2742
2743 move_as_ptr!(first_bundle);
2744 // SAFETY:
2745 // - `entity` is valid, `location` matches entity, bundle matches inserter
2746 // - `apply_effect` is never called on this bundle.
2747 // - `first_bundle` is not be accessed or dropped after this.
2748 unsafe {
2749 cache.inserter.insert(
2750 first_entity,
2751 first_location,
2752 first_bundle,
2753 insert_mode,
2754 caller,
2755 RelationshipHookMode::Run,
2756 )
2757 };
2758 break Some(cache);
2759 }
2760 invalid_entities.push(first_entity);
2761 } else {
2762 // We reached the end of the entities the caller provided and none were valid.
2763 break None;
2764 }
2765 };
2766
2767 if let Some(mut cache) = cache {
2768 for (entity, bundle) in batch_iter {
2769 if let Ok(location) = cache.inserter.entities().get_spawned(entity) {
2770 if location.archetype_id != cache.archetype_id {
2771 cache = InserterArchetypeCache {
2772 // SAFETY: we initialized this bundle_id in `register_info`
2773 inserter: unsafe {
2774 BundleInserter::new_with_id(
2775 self,
2776 location.archetype_id,
2777 bundle_id,
2778 change_tick,
2779 )
2780 },
2781 archetype_id: location.archetype_id,
2782 }
2783 }
2784
2785 move_as_ptr!(bundle);
2786 // SAFETY:
2787 // - `entity` is valid, `location` matches entity, bundle matches inserter
2788 // - `apply_effect` is never called on this bundle.
2789 // - `bundle` is not be accessed or dropped after this.
2790 unsafe {
2791 cache.inserter.insert(
2792 entity,
2793 location,
2794 bundle,
2795 insert_mode,
2796 caller,
2797 RelationshipHookMode::Run,
2798 )
2799 };
2800 } else {
2801 invalid_entities.push(entity);
2802 }
2803 }
2804 }
2805
2806 if invalid_entities.is_empty() {
2807 Ok(())
2808 } else {
2809 Err(TryInsertBatchError {
2810 bundle_type: DebugName::type_name::<B>(),
2811 entities: invalid_entities,
2812 })
2813 }
2814 }
2815
2816 /// Temporarily removes the requested resource from this [`World`], runs custom user code,
2817 /// then re-adds the resource before returning.
2818 ///
2819 /// This enables safe simultaneous mutable access to both a resource and the rest of the [`World`].
2820 /// For more complex access patterns, consider using [`SystemState`](crate::system::SystemState).
2821 ///
2822 /// # Panics
2823 ///
2824 /// Panics if the resource does not exist.
2825 /// Use [`try_resource_scope`](Self::try_resource_scope) instead if you want to handle this case.
2826 ///
2827 /// # Example
2828 /// ```
2829 /// use bevy_ecs::prelude::*;
2830 /// #[derive(Resource)]
2831 /// struct A(u32);
2832 /// #[derive(Component)]
2833 /// struct B(u32);
2834 /// let mut world = World::new();
2835 /// world.insert_resource(A(1));
2836 /// let entity = world.spawn(B(1)).id();
2837 ///
2838 /// world.resource_scope(|world, mut a: Mut<A>| {
2839 /// let b = world.get_mut::<B>(entity).unwrap();
2840 /// a.0 += b.0;
2841 /// });
2842 /// assert_eq!(world.get_resource::<A>().unwrap().0, 2);
2843 /// ```
2844 ///
2845 /// # Note
2846 ///
2847 /// If the world's resource metadata is cleared within the scope, such as by calling
2848 /// [`World::clear_resources`] or [`World::clear_all`], the resource will *not* be re-inserted
2849 /// at the end of the scope.
2850 #[track_caller]
2851 pub fn resource_scope<R: Resource, U>(&mut self, f: impl FnOnce(&mut World, Mut<R>) -> U) -> U {
2852 self.try_resource_scope(f)
2853 .unwrap_or_else(|| panic!("resource does not exist: {}", DebugName::type_name::<R>()))
2854 }
2855
2856 /// Temporarily removes the requested resource from this [`World`] if it exists, runs custom user code,
2857 /// then re-adds the resource before returning. Returns `None` if the resource does not exist in this [`World`].
2858 ///
2859 /// This enables safe simultaneous mutable access to both a resource and the rest of the [`World`].
2860 /// For more complex access patterns, consider using [`SystemState`](crate::system::SystemState).
2861 ///
2862 /// See also [`resource_scope`](Self::resource_scope).
2863 ///
2864 /// # Note
2865 ///
2866 /// If the world's resource metadata is cleared within the scope, such as by calling
2867 /// [`World::clear_resources`] or [`World::clear_all`], the resource will *not* be re-inserted
2868 /// at the end of the scope.
2869 pub fn try_resource_scope<R: Resource, U>(
2870 &mut self,
2871 f: impl FnOnce(&mut World, Mut<R>) -> U,
2872 ) -> Option<U> {
2873 let last_change_tick = self.last_change_tick();
2874 let change_tick = self.change_tick();
2875
2876 let component_id = self.components.valid_component_id::<R>()?;
2877 let entity = self.resource_entities.get(component_id)?;
2878 let mut entity_mut = self.get_entity_mut(entity).ok()?;
2879
2880 let mut ticks = entity_mut.get_change_ticks::<R>()?;
2881 let changed_by = entity_mut.get_changed_by::<R>()?;
2882 let value = entity_mut.take::<R>()?;
2883
2884 // type used to manage reinserting the resource at the end of the scope. use of a drop impl means that
2885 // the resource is inserted even if the user-provided closure unwinds.
2886 // this facilitates localized panic recovery and makes app shutdown in response to a panic more graceful
2887 // by avoiding knock-on errors.
2888 struct ReinsertGuard<'a, R: Resource> {
2889 world: &'a mut World,
2890 entity: Entity,
2891 component_id: ComponentId,
2892 value: ManuallyDrop<R>,
2893 caller: MaybeLocation,
2894 }
2895 impl<R: Resource> Drop for ReinsertGuard<'_, R> {
2896 fn drop(&mut self) {
2897 // take ownership of the value first so it'll get dropped if we return early
2898 // SAFETY: drop semantics ensure that `self.value` will never be accessed again after this call
2899 let value = unsafe { ManuallyDrop::take(&mut self.value) };
2900
2901 let Ok(mut entity_mut) = self.world.get_entity_mut(self.entity) else {
2902 return;
2903 };
2904
2905 // in debug mode, raise a panic if user code re-inserted a resource of this type within the scope.
2906 // resource insertion usually indicates a logic error in user code, which is useful to catch at dev time,
2907 // however it does not inherently lead to corrupted state, so we avoid introducing an unnecessary crash
2908 // for production builds.
2909 if entity_mut.contains_id(self.component_id) {
2910 #[cfg(debug_assertions)]
2911 {
2912 // if we're already panicking, log an error instead of panicking, as double-panics result in an abort
2913 #[cfg(feature = "std")]
2914 if std::thread::panicking() {
2915 log::error!("Resource `{}` was inserted during a call to World::resource_scope, which may result in unexpected behavior.\n\
2916 In release builds, the value inserted will be overwritten at the end of the scope.",
2917 DebugName::type_name::<R>());
2918 // return early to maintain consistent behavior with non-panicking calls in debug builds
2919 return;
2920 }
2921
2922 panic!("Resource `{}` was inserted during a call to World::resource_scope, which may result in unexpected behavior.\n\
2923 In release builds, the value inserted will be overwritten at the end of the scope.",
2924 DebugName::type_name::<R>());
2925 }
2926 #[cfg(not(debug_assertions))]
2927 {
2928 #[cold]
2929 #[inline(never)]
2930 fn warn_reinsert(resource_name: &str) {
2931 warn!(
2932 "Resource `{resource_name}` was inserted during a call to World::resource_scope: the inserted value will be overwritten.",
2933 );
2934 }
2935
2936 warn_reinsert(&DebugName::type_name::<R>());
2937 }
2938 }
2939
2940 move_as_ptr!(value);
2941
2942 // See EntityWorldMut::insert_with_caller for the original code.
2943 // This is copied here to update the change ticks. This way we can ensure that the commands
2944 // ran during self.flush(), interact with the correct ticks on the resource component.
2945 {
2946 let location = entity_mut.location();
2947 // SAFETY:
2948 // - We update the entity location like in `EntityWorldMut::insert_with_caller`.
2949 let world = unsafe { entity_mut.world_mut() };
2950 let tick = world.change_tick();
2951 // SAFETY:
2952 // - `location.archetype_id` is part of a valid `EntityLocation`.
2953 let mut bundle_inserter =
2954 unsafe { BundleInserter::new::<R>(world, location.archetype_id, tick) };
2955 // SAFETY:
2956 // - `location` matches current entity and thus must currently exist in the source
2957 // archetype for this inserter and its location within the archetype.
2958 // - `T` matches the type used to create the `BundleInserter`.
2959 // - `apply_effect` is called exactly once after this function.
2960 // - The value pointed at by `bundle` is not accessed for anything other than `apply_effect`
2961 // and the caller ensures that the value is not accessed or dropped after this function
2962 // returns.
2963 let (bundle, _) = value.partial_move(|bundle| unsafe {
2964 bundle_inserter.insert(
2965 self.entity,
2966 location,
2967 bundle,
2968 InsertMode::Replace,
2969 self.caller,
2970 RelationshipHookMode::Run,
2971 )
2972 });
2973 entity_mut.update_location();
2974
2975 // SAFETY: We update the entity location afterwards.
2976 unsafe { entity_mut.world_mut() }.flush();
2977
2978 entity_mut.update_location();
2979 // SAFETY:
2980 // - This is called exactly once after the `BundleInsert::insert` call before returning to safe code.
2981 // - `bundle` points to the same `B` that `BundleInsert::insert` was called on.
2982 unsafe { R::apply_effect(bundle, &mut entity_mut) };
2983 }
2984 }
2985 }
2986
2987 let mut guard = ReinsertGuard {
2988 world: self,
2989 entity,
2990 component_id,
2991 value: ManuallyDrop::new(value),
2992 caller: changed_by,
2993 };
2994
2995 let value_mut = Mut {
2996 value: &mut *guard.value,
2997 ticks: ComponentTicksMut {
2998 added: &mut ticks.added,
2999 changed: &mut ticks.changed,
3000 changed_by: guard.caller.as_mut(),
3001 last_run: last_change_tick,
3002 this_run: change_tick,
3003 },
3004 };
3005
3006 let result = f(guard.world, value_mut);
3007
3008 Some(result)
3009 }
3010
3011 /// Writes a [`Message`].
3012 /// This method returns the [`MessageId`] of the written `message`,
3013 /// or [`None`] if the `message` could not be written.
3014 #[inline]
3015 pub fn write_message<M: Message>(&mut self, message: M) -> Option<MessageId<M>> {
3016 self.write_message_batch(core::iter::once(message))?.next()
3017 }
3018
3019 /// Writes the default value of the [`Message`] of type `M`.
3020 /// This method returns the [`MessageId`] of the written message,
3021 /// or [`None`] if the `event` could not be written.
3022 #[inline]
3023 pub fn write_message_default<M: Message + Default>(&mut self) -> Option<MessageId<M>> {
3024 self.write_message(M::default())
3025 }
3026
3027 /// Writes a batch of [`Message`]s from an iterator.
3028 /// This method returns the [IDs](`MessageId`) of the written `messages`,
3029 /// or [`None`] if the `events` could not be written.
3030 #[inline]
3031 pub fn write_message_batch<M: Message>(
3032 &mut self,
3033 messages: impl IntoIterator<Item = M>,
3034 ) -> Option<WriteBatchIds<M>> {
3035 let Some(mut events_resource) = self.get_resource_mut::<Messages<M>>() else {
3036 log::error!(
3037 "Unable to send event `{}`\n\tEvent must be added to the app with `add_event()`\n\thttps://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_message ",
3038 DebugName::type_name::<M>()
3039 );
3040 return None;
3041 };
3042 Some(events_resource.write_batch(messages))
3043 }
3044
3045 /// Inserts a new resource with the given `value`. Will replace the value if it already existed.
3046 ///
3047 /// **You should prefer to use the typed API [`World::insert_resource`] where possible and only
3048 /// use this in cases where the actual types are not known at compile time.**
3049 ///
3050 /// # Safety
3051 /// The value referenced by `value` must be valid for the given [`ComponentId`] of this world.
3052 #[inline]
3053 #[track_caller]
3054 pub unsafe fn insert_resource_by_id(
3055 &mut self,
3056 component_id: ComponentId,
3057 value: OwningPtr<'_>,
3058 caller: MaybeLocation,
3059 ) {
3060 // if the resource already exists, we replace it on the same entity
3061 let mut entity_mut = if let Some(entity) = self.resource_entities.get(component_id) {
3062 self.get_entity_mut(entity)
3063 .expect("ResourceCache is in sync")
3064 } else {
3065 self.spawn_empty()
3066 };
3067 entity_mut.insert_by_id_with_caller(
3068 component_id,
3069 value,
3070 InsertMode::Replace,
3071 caller,
3072 RelationshipHookMode::Run,
3073 );
3074 }
3075
3076 /// Inserts new `!Send` data with the given `value`. Will replace the value if it already
3077 /// existed.
3078 ///
3079 /// **You should prefer to use the typed API [`World::insert_non_send`] where possible and only
3080 /// use this in cases where the actual types are not known at compile time.**
3081 ///
3082 /// # Panics
3083 /// If a value is already present, this function will panic if not called from the same
3084 /// thread that the original value was inserted from.
3085 ///
3086 /// # Safety
3087 /// The value referenced by `value` must be valid for the given [`ComponentId`] of this world.
3088 #[inline]
3089 #[track_caller]
3090 pub unsafe fn insert_non_send_by_id(
3091 &mut self,
3092 component_id: ComponentId,
3093 value: OwningPtr<'_>,
3094 caller: MaybeLocation,
3095 ) {
3096 let change_tick = self.change_tick();
3097
3098 let resource = self.initialize_non_send_internal(component_id);
3099 // SAFETY: `value` is valid for `component_id`, ensured by caller
3100 unsafe {
3101 resource.insert(value, change_tick, caller);
3102 }
3103 }
3104
3105 /// # Panics
3106 /// Panics if `component_id` is not registered in this world
3107 #[inline]
3108 pub(crate) fn initialize_non_send_internal(
3109 &mut self,
3110 component_id: ComponentId,
3111 ) -> &mut NonSendData {
3112 self.flush_components();
3113 self.storages
3114 .non_sends
3115 .initialize_with(component_id, &self.components)
3116 }
3117
3118 /// Applies any commands in the world's internal [`CommandQueue`].
3119 /// This does not apply commands from any systems, only those stored in the world.
3120 ///
3121 /// # Panics
3122 /// This will panic if any of the queued commands are [`spawn`](Commands::spawn).
3123 /// If this is possible, you should instead use [`flush`](Self::flush).
3124 pub(crate) fn flush_commands(&mut self) {
3125 // SAFETY: `self.command_queue` is only de-allocated in `World`'s `Drop`
3126 if !unsafe { self.command_queue.is_empty() } {
3127 // SAFETY: `self.command_queue` is only de-allocated in `World`'s `Drop`
3128 unsafe {
3129 self.command_queue
3130 .clone()
3131 .apply_or_drop_queued(Some(self.into()));
3132 };
3133 }
3134 }
3135
3136 /// Applies any queued component registration.
3137 /// For spawning vanilla rust component types and resources, this is not strictly necessary.
3138 /// However, flushing components can make information available more quickly, and can have performance benefits.
3139 /// Additionally, for components and resources registered dynamically through a raw descriptor or similar,
3140 /// this is the only way to complete their registration.
3141 pub(crate) fn flush_components(&mut self) {
3142 self.components_registrator().apply_queued_registrations();
3143 }
3144
3145 /// Flushes queued entities and commands.
3146 ///
3147 /// Queued entities will be spawned, and then commands will be applied.
3148 #[inline]
3149 #[track_caller]
3150 pub fn flush(&mut self) {
3151 self.flush_components();
3152 self.flush_commands();
3153 }
3154
3155 /// Increments the world's current change tick and returns the old value.
3156 ///
3157 /// If you need to call this method, but do not have `&mut` access to the world,
3158 /// consider using [`as_unsafe_world_cell_readonly`](Self::as_unsafe_world_cell_readonly)
3159 /// to obtain an [`UnsafeWorldCell`] and calling [`increment_change_tick`](UnsafeWorldCell::increment_change_tick) on that.
3160 /// Note that this *can* be done in safe code, despite the name of the type.
3161 #[inline]
3162 pub fn increment_change_tick(&mut self) -> Tick {
3163 let change_tick = self.change_tick.get_mut();
3164 let prev_tick = *change_tick;
3165 *change_tick = change_tick.wrapping_add(1);
3166 Tick::new(prev_tick)
3167 }
3168
3169 /// Reads the current change tick of this world.
3170 ///
3171 /// If you have exclusive (`&mut`) access to the world, consider using [`change_tick()`](Self::change_tick),
3172 /// which is more efficient since it does not require atomic synchronization.
3173 #[inline]
3174 pub fn read_change_tick(&self) -> Tick {
3175 let tick = self.change_tick.load(Ordering::Acquire);
3176 Tick::new(tick)
3177 }
3178
3179 /// Reads the current change tick of this world.
3180 ///
3181 /// This does the same thing as [`read_change_tick()`](Self::read_change_tick), only this method
3182 /// is more efficient since it does not require atomic synchronization.
3183 #[inline]
3184 pub fn change_tick(&mut self) -> Tick {
3185 let tick = *self.change_tick.get_mut();
3186 Tick::new(tick)
3187 }
3188
3189 /// When called from within an exclusive system (a [`System`] that takes `&mut World` as its first
3190 /// parameter), this method returns the [`Tick`] indicating the last time the exclusive system was run.
3191 ///
3192 /// Otherwise, this returns the `Tick` indicating the last time that [`World::clear_trackers`] was called.
3193 ///
3194 /// [`System`]: crate::system::System
3195 #[inline]
3196 pub fn last_change_tick(&self) -> Tick {
3197 self.last_change_tick
3198 }
3199
3200 /// Returns the id of the last ECS event that was fired.
3201 /// Used internally to ensure observers don't trigger multiple times for the same event.
3202 #[inline]
3203 pub(crate) fn last_trigger_id(&self) -> u32 {
3204 self.last_trigger_id
3205 }
3206
3207 /// Sets [`World::last_change_tick()`] to the specified value during a scope.
3208 /// When the scope terminates, it will return to its old value.
3209 ///
3210 /// This is useful if you need a region of code to be able to react to earlier changes made in the same system.
3211 ///
3212 /// # Examples
3213 ///
3214 /// ```
3215 /// # use bevy_ecs::prelude::*;
3216 /// // This function runs an update loop repeatedly, allowing each iteration of the loop
3217 /// // to react to changes made in the previous loop iteration.
3218 /// fn update_loop(
3219 /// world: &mut World,
3220 /// mut update_fn: impl FnMut(&mut World) -> std::ops::ControlFlow<()>,
3221 /// ) {
3222 /// let mut last_change_tick = world.last_change_tick();
3223 ///
3224 /// // Repeatedly run the update function until it requests a break.
3225 /// loop {
3226 /// let control_flow = world.last_change_tick_scope(last_change_tick, |world| {
3227 /// // Increment the change tick so we can detect changes from the previous update.
3228 /// last_change_tick = world.change_tick();
3229 /// world.increment_change_tick();
3230 ///
3231 /// // Update once.
3232 /// update_fn(world)
3233 /// });
3234 ///
3235 /// // End the loop when the closure returns `ControlFlow::Break`.
3236 /// if control_flow.is_break() {
3237 /// break;
3238 /// }
3239 /// }
3240 /// }
3241 /// #
3242 /// # #[derive(Resource)] struct Count(u32);
3243 /// # let mut world = World::new();
3244 /// # world.insert_resource(Count(0));
3245 /// # let saved_last_tick = world.last_change_tick();
3246 /// # let mut num_updates = 0;
3247 /// # update_loop(&mut world, |world| {
3248 /// # let mut c = world.resource_mut::<Count>();
3249 /// # match c.0 {
3250 /// # 0 => {
3251 /// # assert_eq!(num_updates, 0);
3252 /// # assert!(c.is_added());
3253 /// # c.0 = 1;
3254 /// # }
3255 /// # 1 => {
3256 /// # assert_eq!(num_updates, 1);
3257 /// # assert!(!c.is_added());
3258 /// # assert!(c.is_changed());
3259 /// # c.0 = 2;
3260 /// # }
3261 /// # 2 if c.is_changed() => {
3262 /// # assert_eq!(num_updates, 2);
3263 /// # assert!(!c.is_added());
3264 /// # }
3265 /// # 2 => {
3266 /// # assert_eq!(num_updates, 3);
3267 /// # assert!(!c.is_changed());
3268 /// # world.remove_resource::<Count>();
3269 /// # world.insert_resource(Count(3));
3270 /// # }
3271 /// # 3 if c.is_changed() => {
3272 /// # assert_eq!(num_updates, 4);
3273 /// # assert!(c.is_added());
3274 /// # }
3275 /// # 3 => {
3276 /// # assert_eq!(num_updates, 5);
3277 /// # assert!(!c.is_added());
3278 /// # c.0 = 4;
3279 /// # return std::ops::ControlFlow::Break(());
3280 /// # }
3281 /// # _ => unreachable!(),
3282 /// # }
3283 /// # num_updates += 1;
3284 /// # std::ops::ControlFlow::Continue(())
3285 /// # });
3286 /// # assert_eq!(num_updates, 5);
3287 /// # assert_eq!(world.resource::<Count>().0, 4);
3288 /// # assert_eq!(world.last_change_tick(), saved_last_tick);
3289 /// ```
3290 pub fn last_change_tick_scope<T>(
3291 &mut self,
3292 last_change_tick: Tick,
3293 f: impl FnOnce(&mut World) -> T,
3294 ) -> T {
3295 struct LastTickGuard<'a> {
3296 world: &'a mut World,
3297 last_tick: Tick,
3298 }
3299
3300 // By setting the change tick in the drop impl, we ensure that
3301 // the change tick gets reset even if a panic occurs during the scope.
3302 impl Drop for LastTickGuard<'_> {
3303 fn drop(&mut self) {
3304 self.world.last_change_tick = self.last_tick;
3305 }
3306 }
3307
3308 let guard = LastTickGuard {
3309 last_tick: self.last_change_tick,
3310 world: self,
3311 };
3312
3313 guard.world.last_change_tick = last_change_tick;
3314
3315 f(guard.world)
3316 }
3317
3318 /// Iterates all component change ticks and clamps any older than [`MAX_CHANGE_AGE`](crate::change_detection::MAX_CHANGE_AGE).
3319 /// This also triggers [`CheckChangeTicks`] observers and returns the same event here.
3320 ///
3321 /// Calling this method prevents [`Tick`]s overflowing and thus prevents false positives when comparing them.
3322 ///
3323 /// **Note:** Does nothing and returns `None` if the [`World`] counter has not been incremented at least [`CHECK_TICK_THRESHOLD`]
3324 /// times since the previous pass.
3325 // TODO: benchmark and optimize
3326 pub fn check_change_ticks(&mut self) -> Option<CheckChangeTicks> {
3327 let change_tick = self.change_tick();
3328 if change_tick.relative_to(self.last_check_tick).get() < CHECK_TICK_THRESHOLD {
3329 return None;
3330 }
3331
3332 let check = CheckChangeTicks(change_tick);
3333
3334 let Storages {
3335 ref mut tables,
3336 ref mut sparse_sets,
3337 ref mut non_sends,
3338 } = self.storages;
3339
3340 #[cfg(feature = "trace")]
3341 let _span = tracing::info_span!("check component ticks").entered();
3342 tables.check_change_ticks(check);
3343 sparse_sets.check_change_ticks(check);
3344 non_sends.check_change_ticks(check);
3345 self.entities.check_change_ticks(check);
3346
3347 if let Some(mut schedules) = self.get_resource_mut::<Schedules>() {
3348 schedules.check_change_ticks(check);
3349 }
3350
3351 self.trigger(check);
3352 self.flush();
3353
3354 self.last_check_tick = change_tick;
3355
3356 Some(check)
3357 }
3358
3359 /// Clears all entities, resources, and non-send data.
3360 /// This invalidates all [`Entity`] and resource fetches such as [`Res`](crate::system::Res),
3361 /// [`ResMut`](crate::system::ResMut)
3362 pub fn clear_all(&mut self) {
3363 self.clear_entities();
3364 self.clear_non_send();
3365 }
3366
3367 /// Despawns all entities in this [`World`].
3368 ///
3369 /// **Note:** This includes all resources, as they are stored as components.
3370 /// Any resource fetch to this [`World`] will fail unless they are re-initialized,
3371 /// including engine-internal resources that are only initialized on app/world construction.
3372 ///
3373 /// This can easily cause systems expecting certain resources to immediately start panicking.
3374 /// Use with caution.
3375 pub fn clear_entities(&mut self) {
3376 self.storages.tables.clear();
3377 self.storages.sparse_sets.clear_entities();
3378 self.archetypes.clear_entities();
3379 self.entities.clear();
3380 self.entity_allocator.restart();
3381 }
3382
3383 /// Clears all resources in this [`World`].
3384 ///
3385 /// **Note:** Any resource fetch to this [`World`] will fail unless they are re-initialized,
3386 /// including engine-internal resources that are only initialized on app/world construction.
3387 ///
3388 /// This can easily cause systems expecting certain resources to immediately start panicking.
3389 /// Use with caution.
3390 pub fn clear_resources(&mut self) {
3391 let pairs: Vec<(ComponentId, Entity)> = self.resource_entities().iter().collect();
3392 for (component_id, entity) in pairs {
3393 self.entity_mut(entity).remove_by_id(component_id);
3394 }
3395 }
3396
3397 /// Clears all non-send data in this [`World`].
3398 pub fn clear_non_send(&mut self) {
3399 self.storages.non_sends.clear();
3400 }
3401
3402 /// Registers all of the components in the given [`Bundle`] and returns both the component
3403 /// ids and the bundle id.
3404 ///
3405 /// This is largely equivalent to calling [`register_component`](Self::register_component) on each
3406 /// component in the bundle.
3407 #[inline]
3408 pub fn register_bundle<B: Bundle>(&mut self) -> &BundleInfo {
3409 let id = self.register_bundle_info::<B>();
3410
3411 // SAFETY: We just initialized the bundle so its id should definitely be valid.
3412 unsafe { self.bundles.get(id).debug_checked_unwrap() }
3413 }
3414
3415 pub(crate) fn register_bundle_info<B: Bundle>(&mut self) -> BundleId {
3416 // SAFETY: These come from the same world. `Self.components_registrator` can't be used since we borrow other fields too.
3417 let mut registrator =
3418 unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) };
3419
3420 // SAFETY: `registrator`, `self.storages` and `self.bundles` all come from this world.
3421 unsafe {
3422 self.bundles
3423 .register_info::<B>(&mut registrator, &mut self.storages)
3424 }
3425 }
3426
3427 pub(crate) fn register_contributed_bundle_info<B: Bundle>(&mut self) -> BundleId {
3428 // SAFETY: These come from the same world. `Self.components_registrator` can't be used since we borrow other fields too.
3429 let mut registrator =
3430 unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) };
3431
3432 // SAFETY: `registrator`, `self.bundles` and `self.storages` are all from this world.
3433 unsafe {
3434 self.bundles
3435 .register_contributed_bundle_info::<B>(&mut registrator, &mut self.storages)
3436 }
3437 }
3438
3439 /// Registers the given [`ComponentId`]s as a dynamic bundle and returns both the required component ids and the bundle id.
3440 ///
3441 /// Note that the components need to be registered first, this function only creates a bundle combining them. Components
3442 /// can be registered with [`World::register_component`]/[`_with_descriptor`](World::register_component_with_descriptor).
3443 ///
3444 /// **You should prefer to use the typed API [`World::register_bundle`] where possible and only use this in cases where
3445 /// not all of the actual types are known at compile time.**
3446 ///
3447 /// # Panics
3448 /// This function will panic if any of the provided component ids do not belong to a component known to this [`World`].
3449 #[inline]
3450 pub fn register_dynamic_bundle(&mut self, component_ids: &[ComponentId]) -> &BundleInfo {
3451 let id =
3452 self.bundles
3453 .init_dynamic_info(&mut self.storages, &self.components, component_ids);
3454 // SAFETY: We just initialized the bundle so its id should definitely be valid.
3455 unsafe { self.bundles.get(id).debug_checked_unwrap() }
3456 }
3457
3458 /// Convenience method for accessing the world's fallback error handler,
3459 /// which can be overwritten with [`FallbackErrorHandler`].
3460 #[inline]
3461 pub fn fallback_error_handler(&self) -> ErrorHandler {
3462 self.get_resource::<FallbackErrorHandler>()
3463 .copied()
3464 .unwrap_or_default()
3465 .0
3466 }
3467}
3468
3469impl World {
3470 /// Gets a pointer to the resource with the id [`ComponentId`] if it exists.
3471 /// The returned pointer must not be used to modify the resource, and must not be
3472 /// dereferenced after the immutable borrow of the [`World`] ends.
3473 ///
3474 /// **You should prefer to use the typed API [`World::get_resource`] where possible and only
3475 /// use this in cases where the actual types are not known at compile time.**
3476 #[inline]
3477 pub fn get_resource_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
3478 // SAFETY:
3479 // - `as_unsafe_world_cell_readonly` gives permission to access the whole world immutably
3480 // - `&self` ensures there are no mutable borrows on world data
3481 unsafe {
3482 self.as_unsafe_world_cell_readonly()
3483 .get_resource_by_id(component_id)
3484 }
3485 }
3486
3487 /// Gets a pointer to the resource with the id [`ComponentId`] if it exists and is mutable.
3488 /// The returned pointer may be used to modify the resource, as long as the mutable borrow
3489 /// of the [`World`] is still valid.
3490 ///
3491 /// **You should prefer to use the typed API [`World::get_resource_mut`] where possible and only
3492 /// use this in cases where the actual types are not known at compile time.**
3493 #[inline]
3494 pub fn get_resource_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
3495 // SAFETY:
3496 // - `&mut self` ensures that all accessed data is unaliased
3497 // - `as_unsafe_world_cell` provides mutable permission to the whole world
3498 unsafe {
3499 self.as_unsafe_world_cell()
3500 .get_resource_mut_by_id(component_id)
3501 }
3502 }
3503
3504 /// Iterates over all resources in the world.
3505 ///
3506 /// The returned iterator provides lifetimed, but type-unsafe pointers. Actually reading the contents
3507 /// of each resource will require the use of unsafe code.
3508 ///
3509 /// # Examples
3510 ///
3511 /// ## Printing the size of all resources
3512 ///
3513 /// ```
3514 /// # use bevy_ecs::prelude::*;
3515 /// # #[derive(Resource)]
3516 /// # struct A(u32);
3517 /// # #[derive(Resource)]
3518 /// # struct B(u32);
3519 /// #
3520 /// # let mut world = World::new();
3521 /// # world.remove_resource::<bevy_ecs::entity_disabling::DefaultQueryFilters>();
3522 /// # world.insert_resource(A(1));
3523 /// # world.insert_resource(B(2));
3524 /// let mut total = 0;
3525 /// for (info, _) in world.iter_resources() {
3526 /// println!("Resource: {}", info.name());
3527 /// println!("Size: {} bytes", info.layout().size());
3528 /// total += info.layout().size();
3529 /// }
3530 /// println!("Total size: {} bytes", total);
3531 /// # assert_eq!(total, size_of::<A>() + size_of::<B>());
3532 /// ```
3533 ///
3534 /// ## Dynamically running closures for resources matching specific `TypeId`s
3535 ///
3536 /// ```
3537 /// # use bevy_ecs::prelude::*;
3538 /// # use std::collections::HashMap;
3539 /// # use std::any::TypeId;
3540 /// # use bevy_ptr::Ptr;
3541 /// # #[derive(Resource)]
3542 /// # struct A(u32);
3543 /// # #[derive(Resource)]
3544 /// # struct B(u32);
3545 /// #
3546 /// # let mut world = World::new();
3547 /// # world.insert_resource(A(1));
3548 /// # world.insert_resource(B(2));
3549 /// #
3550 /// // In this example, `A` and `B` are resources. We deliberately do not use the
3551 /// // `bevy_reflect` crate here to showcase the low-level [`Ptr`] usage. You should
3552 /// // probably use something like `ReflectFromPtr` in a real-world scenario.
3553 ///
3554 /// // Create the hash map that will store the closures for each resource type
3555 /// let mut closures: HashMap<TypeId, Box<dyn Fn(&Ptr<'_>)>> = HashMap::default();
3556 ///
3557 /// // Add closure for `A`
3558 /// closures.insert(TypeId::of::<A>(), Box::new(|ptr| {
3559 /// // SAFETY: We assert ptr is the same type of A with TypeId of A
3560 /// let a = unsafe { &ptr.deref::<A>() };
3561 /// # assert_eq!(a.0, 1);
3562 /// // ... do something with `a` here
3563 /// }));
3564 ///
3565 /// // Add closure for `B`
3566 /// closures.insert(TypeId::of::<B>(), Box::new(|ptr| {
3567 /// // SAFETY: We assert ptr is the same type of B with TypeId of B
3568 /// let b = unsafe { &ptr.deref::<B>() };
3569 /// # assert_eq!(b.0, 2);
3570 /// // ... do something with `b` here
3571 /// }));
3572 ///
3573 /// // Iterate all resources, in order to run the closures for each matching resource type
3574 /// for (info, ptr) in world.iter_resources() {
3575 /// let Some(type_id) = info.type_id() else {
3576 /// // It's possible for resources to not have a `TypeId` (e.g. non-Rust resources
3577 /// // dynamically inserted via a scripting language) in which case we can't match them.
3578 /// continue;
3579 /// };
3580 ///
3581 /// let Some(closure) = closures.get(&type_id) else {
3582 /// // No closure for this resource type, skip it.
3583 /// continue;
3584 /// };
3585 ///
3586 /// // Run the closure for the resource
3587 /// closure(&ptr);
3588 /// }
3589 /// ```
3590 #[inline]
3591 pub fn iter_resources(&self) -> impl Iterator<Item = (&ComponentInfo, Ptr<'_>)> {
3592 self.resource_entities
3593 .iter()
3594 .filter_map(|(component_id, entity)| {
3595 let component_info = self.components().get_info(component_id)?;
3596 let entity_cell = self.get_entity(entity).ok()?;
3597 let resource = entity_cell.get_by_id(component_id).ok()?;
3598 Some((component_info, resource))
3599 })
3600 }
3601
3602 /// Mutably iterates over all resources in the world.
3603 ///
3604 /// The returned iterator provides lifetimed, but type-unsafe pointers. Actually reading from or writing
3605 /// to the contents of each resource will require the use of unsafe code.
3606 ///
3607 /// # Example
3608 ///
3609 /// ```
3610 /// # use bevy_ecs::prelude::*;
3611 /// # use bevy_ecs::change_detection::MutUntyped;
3612 /// # use std::collections::HashMap;
3613 /// # use std::any::TypeId;
3614 /// # #[derive(Resource)]
3615 /// # struct A(u32);
3616 /// # #[derive(Resource)]
3617 /// # struct B(u32);
3618 /// #
3619 /// # let mut world = World::new();
3620 /// # world.insert_resource(A(1));
3621 /// # world.insert_resource(B(2));
3622 /// #
3623 /// // In this example, `A` and `B` are resources. We deliberately do not use the
3624 /// // `bevy_reflect` crate here to showcase the low-level `MutUntyped` usage. You should
3625 /// // probably use something like `ReflectFromPtr` in a real-world scenario.
3626 ///
3627 /// // Create the hash map that will store the mutator closures for each resource type
3628 /// let mut mutators: HashMap<TypeId, Box<dyn Fn(&mut MutUntyped<'_>)>> = HashMap::default();
3629 ///
3630 /// // Add mutator closure for `A`
3631 /// mutators.insert(TypeId::of::<A>(), Box::new(|mut_untyped| {
3632 /// // Note: `MutUntyped::as_mut()` automatically marks the resource as changed
3633 /// // for ECS change detection, and gives us a `PtrMut` we can use to mutate the resource.
3634 /// // SAFETY: We assert ptr is the same type of A with TypeId of A
3635 /// let a = unsafe { &mut mut_untyped.as_mut().deref_mut::<A>() };
3636 /// # a.0 += 1;
3637 /// // ... mutate `a` here
3638 /// }));
3639 ///
3640 /// // Add mutator closure for `B`
3641 /// mutators.insert(TypeId::of::<B>(), Box::new(|mut_untyped| {
3642 /// // SAFETY: We assert ptr is the same type of B with TypeId of B
3643 /// let b = unsafe { &mut mut_untyped.as_mut().deref_mut::<B>() };
3644 /// # b.0 += 1;
3645 /// // ... mutate `b` here
3646 /// }));
3647 ///
3648 /// // Iterate all resources, in order to run the mutator closures for each matching resource type
3649 /// for (info, mut mut_untyped) in world.iter_resources_mut() {
3650 /// let Some(type_id) = info.type_id() else {
3651 /// // It's possible for resources to not have a `TypeId` (e.g. non-Rust resources
3652 /// // dynamically inserted via a scripting language) in which case we can't match them.
3653 /// continue;
3654 /// };
3655 ///
3656 /// let Some(mutator) = mutators.get(&type_id) else {
3657 /// // No mutator closure for this resource type, skip it.
3658 /// continue;
3659 /// };
3660 ///
3661 /// // Run the mutator closure for the resource
3662 /// mutator(&mut mut_untyped);
3663 /// }
3664 /// # assert_eq!(world.resource::<A>().0, 2);
3665 /// # assert_eq!(world.resource::<B>().0, 3);
3666 /// ```
3667 pub fn iter_resources_mut(&mut self) -> impl Iterator<Item = (&ComponentInfo, MutUntyped<'_>)> {
3668 let unsafe_world = self.as_unsafe_world_cell();
3669 // SAFETY: exclusive world access to all resources
3670 let resource_entities = unsafe { unsafe_world.resource_entities() };
3671 let components = unsafe_world.components();
3672
3673 resource_entities
3674 .iter()
3675 .filter_map(move |(component_id, entity)| {
3676 // SAFETY: If a resource has been initialized, a corresponding ComponentInfo must exist with its ID.
3677 let component_info =
3678 unsafe { components.get_info(component_id).debug_checked_unwrap() };
3679
3680 let entity_cell = unsafe_world.get_entity(entity).ok()?;
3681
3682 // SAFETY:
3683 // - We have exclusive world access
3684 // - `UnsafeEntityCell::get_mut_by_id` doesn't access components
3685 // or resource_entities mutably
3686 // - `resource_entities` doesn't contain duplicate entities, so
3687 // no duplicate references are created
3688 let mut_untyped = unsafe { entity_cell.get_mut_by_id(component_id).ok()? };
3689
3690 Some((component_info, mut_untyped))
3691 })
3692 }
3693
3694 /// Gets a pointer to `!Send` data with the id [`ComponentId`] if it exists.
3695 /// The returned pointer must not be used to modify the resource, and must not be
3696 /// dereferenced after the immutable borrow of the [`World`] ends.
3697 ///
3698 /// **You should prefer to use the typed API [`World::get_non_send`] where possible and only
3699 /// use this in cases where the actual types are not known at compile time.**
3700 ///
3701 /// # Panics
3702 /// This function will panic if it isn't called from the same thread that the data was inserted from.
3703 #[inline]
3704 pub fn get_non_send_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
3705 // SAFETY:
3706 // - `as_unsafe_world_cell_readonly` gives permission to access the whole world immutably
3707 // - `&self` ensures there are no mutable borrows on world data
3708 unsafe {
3709 self.as_unsafe_world_cell_readonly()
3710 .get_non_send_by_id(component_id)
3711 }
3712 }
3713
3714 /// Gets mutable access to `!Send` data with the id [`ComponentId`] if it exists.
3715 /// The returned pointer may be used to modify the data, as long as the mutable borrow
3716 /// of the [`World`] is still valid.
3717 ///
3718 /// **You should prefer to use the typed API [`World::get_non_send_mut`] where possible and only
3719 /// use this in cases where the actual types are not known at compile time.**
3720 ///
3721 /// # Panics
3722 /// This function will panic if it isn't called from the same thread that the data was inserted from.
3723 #[inline]
3724 pub fn get_non_send_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
3725 // SAFETY:
3726 // - `&mut self` ensures that all accessed data is unaliased
3727 // - `as_unsafe_world_cell` provides mutable permission to the whole world
3728 unsafe {
3729 self.as_unsafe_world_cell()
3730 .get_non_send_mut_by_id(component_id)
3731 }
3732 }
3733
3734 /// Removes the resource of a given type, if it exists.
3735 /// Returns `true` if the resource is successfully removed and `false` if
3736 /// the entity does not exist.
3737 ///
3738 /// **You should prefer to use the typed API [`World::remove_resource`] where possible and only
3739 /// use this in cases where the actual types are not known at compile time.**
3740 pub fn remove_resource_by_id(&mut self, component_id: ComponentId) -> bool {
3741 if let Some(entity) = self.resource_entities.get(component_id)
3742 && let Ok(mut entity_mut) = self.get_entity_mut(entity)
3743 && entity_mut.contains_id(component_id)
3744 {
3745 entity_mut.remove_by_id(component_id);
3746 true
3747 } else {
3748 false
3749 }
3750 }
3751
3752 /// Removes the non-send data of a given type, if it exists. Otherwise returns `None`.
3753 ///
3754 /// **You should prefer to use the typed API [`World::remove_non_send`] where possible and only
3755 /// use this in cases where the actual types are not known at compile time.**
3756 ///
3757 /// # Panics
3758 /// This function will panic if it isn't called from the same thread that the data was inserted from.
3759 pub fn remove_non_send_by_id(&mut self, component_id: ComponentId) -> Option<()> {
3760 self.storages
3761 .non_sends
3762 .get_mut(component_id)?
3763 .remove_and_drop();
3764 Some(())
3765 }
3766
3767 /// Retrieves an immutable untyped reference to the given `entity`'s [`Component`] of the given [`ComponentId`].
3768 /// Returns `None` if the `entity` does not have a [`Component`] of the given type.
3769 ///
3770 /// **You should prefer to use the typed API [`World::get_mut`] where possible and only
3771 /// use this in cases where the actual types are not known at compile time.**
3772 ///
3773 /// # Panics
3774 /// This function will panic if it isn't called from the same thread that the resource was inserted from.
3775 #[inline]
3776 pub fn get_by_id(&self, entity: Entity, component_id: ComponentId) -> Option<Ptr<'_>> {
3777 self.get_entity(entity).ok()?.get_by_id(component_id).ok()
3778 }
3779
3780 /// Retrieves a mutable untyped reference to the given `entity`'s [`Component`] of the given [`ComponentId`].
3781 /// Returns `None` if the `entity` does not have a [`Component`] of the given type.
3782 ///
3783 /// **You should prefer to use the typed API [`World::get_mut`] where possible and only
3784 /// use this in cases where the actual types are not known at compile time.**
3785 #[inline]
3786 pub fn get_mut_by_id(
3787 &mut self,
3788 entity: Entity,
3789 component_id: ComponentId,
3790 ) -> Option<MutUntyped<'_>> {
3791 self.get_entity_mut(entity)
3792 .ok()?
3793 .into_mut_by_id(component_id)
3794 .ok()
3795 }
3796}
3797
3798// Schedule-related methods
3799impl World {
3800 /// Adds the specified [`Schedule`] to the world.
3801 /// If a schedule already exists with the same [label](Schedule::label), it will be replaced.
3802 ///
3803 /// The schedule can later be run
3804 /// by calling [`.run_schedule(label)`](Self::run_schedule) or by directly
3805 /// accessing the [`Schedules`] resource.
3806 ///
3807 /// The `Schedules` resource will be initialized if it does not already exist.
3808 ///
3809 /// An alternative to this is to call [`Schedules::add_systems()`] with some
3810 /// [`ScheduleLabel`] and let the schedule for that label be created if it
3811 /// does not already exist.
3812 pub fn add_schedule(&mut self, schedule: Schedule) {
3813 let mut schedules = self.get_resource_or_init::<Schedules>();
3814 schedules.insert(schedule);
3815 }
3816
3817 /// Temporarily removes the schedule associated with `label` from the world,
3818 /// runs user code, and finally re-adds the schedule.
3819 /// This returns a [`TryRunScheduleError`] if there is no schedule
3820 /// associated with `label`.
3821 ///
3822 /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3823 /// and system state is cached.
3824 ///
3825 /// For simple cases where you just need to call the schedule once,
3826 /// consider using [`World::try_run_schedule`] instead.
3827 /// For other use cases, see the example on [`World::schedule_scope`].
3828 pub fn try_schedule_scope<R>(
3829 &mut self,
3830 label: impl ScheduleLabel,
3831 f: impl FnOnce(&mut World, &mut Schedule) -> R,
3832 ) -> Result<R, TryRunScheduleError> {
3833 let label = label.intern();
3834 let Some(mut schedule) = self
3835 .get_resource_mut::<Schedules>()
3836 .and_then(|mut s| s.remove_temporarily(label))
3837 else {
3838 return Err(TryRunScheduleError(label));
3839 };
3840
3841 let value = f(self, &mut schedule);
3842
3843 let old = self.resource_mut::<Schedules>().reinsert(schedule);
3844 if old.is_some() {
3845 warn!("Schedule `{label:?}` was inserted during a call to `World::schedule_scope`: its value has been overwritten");
3846 }
3847
3848 Ok(value)
3849 }
3850
3851 /// Temporarily removes the schedule associated with `label` from the world,
3852 /// runs user code, and finally re-adds the schedule.
3853 ///
3854 /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3855 /// and system state is cached.
3856 ///
3857 /// # Examples
3858 ///
3859 /// ```
3860 /// # use bevy_ecs::{prelude::*, schedule::ScheduleLabel};
3861 /// # #[derive(ScheduleLabel, Debug, Clone, Copy, PartialEq, Eq, Hash)]
3862 /// # pub struct MySchedule;
3863 /// # #[derive(Resource)]
3864 /// # struct Counter(usize);
3865 /// #
3866 /// # let mut world = World::new();
3867 /// # world.insert_resource(Counter(0));
3868 /// # let mut schedule = Schedule::new(MySchedule);
3869 /// # schedule.add_systems(tick_counter);
3870 /// # world.init_resource::<Schedules>();
3871 /// # world.add_schedule(schedule);
3872 /// # fn tick_counter(mut counter: ResMut<Counter>) { counter.0 += 1; }
3873 /// // Run the schedule five times.
3874 /// world.schedule_scope(MySchedule, |world, schedule| {
3875 /// for _ in 0..5 {
3876 /// schedule.run(world);
3877 /// }
3878 /// });
3879 /// # assert_eq!(world.resource::<Counter>().0, 5);
3880 /// ```
3881 ///
3882 /// For simple cases where you just need to call the schedule once,
3883 /// consider using [`World::run_schedule`] instead.
3884 ///
3885 /// # Panics
3886 ///
3887 /// If the requested schedule does not exist.
3888 pub fn schedule_scope<R>(
3889 &mut self,
3890 label: impl ScheduleLabel,
3891 f: impl FnOnce(&mut World, &mut Schedule) -> R,
3892 ) -> R {
3893 self.try_schedule_scope(label, f)
3894 .unwrap_or_else(|e| panic!("{e}"))
3895 }
3896
3897 /// Attempts to run the [`Schedule`] associated with the `label` a single time,
3898 /// and returns a [`TryRunScheduleError`] if the schedule does not exist.
3899 ///
3900 /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3901 /// and system state is cached.
3902 ///
3903 /// For simple testing use cases, call [`Schedule::run(&mut world)`](Schedule::run) instead.
3904 pub fn try_run_schedule(
3905 &mut self,
3906 label: impl ScheduleLabel,
3907 ) -> Result<(), TryRunScheduleError> {
3908 self.try_schedule_scope(label, |world, sched| sched.run(world))
3909 }
3910
3911 /// Runs the [`Schedule`] associated with the `label` a single time.
3912 ///
3913 /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3914 /// and system state is cached.
3915 ///
3916 /// For simple testing use cases, call [`Schedule::run(&mut world)`](Schedule::run) instead.
3917 /// This avoids the need to create a unique [`ScheduleLabel`].
3918 ///
3919 /// # Panics
3920 ///
3921 /// If the requested schedule does not exist.
3922 pub fn run_schedule(&mut self, label: impl ScheduleLabel) {
3923 self.schedule_scope(label, |world, sched| sched.run(world));
3924 }
3925
3926 /// Ignore system order ambiguities caused by conflicts on [`Component`]s of type `T`.
3927 pub fn allow_ambiguous_component<T: Component>(&mut self) {
3928 let mut schedules = self.remove_resource::<Schedules>().unwrap_or_default();
3929 schedules.allow_ambiguous_component::<T>(self);
3930 self.insert_resource(schedules);
3931 }
3932
3933 /// Ignore system order ambiguities caused by conflicts on [`Resource`]s of type `T`.
3934 pub fn allow_ambiguous_resource<T: Resource>(&mut self) {
3935 let mut schedules = self.remove_resource::<Schedules>().unwrap_or_default();
3936 schedules.allow_ambiguous_resource::<T>(self);
3937 self.insert_resource(schedules);
3938 }
3939}
3940
3941impl fmt::Debug for World {
3942 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3943 // SAFETY: `UnsafeWorldCell` requires that this must only access metadata.
3944 // Accessing any data stored in the world would be unsound.
3945 f.debug_struct("World")
3946 .field("id", &self.id)
3947 .field("entity_count", &self.entities.count_spawned())
3948 .field("archetype_count", &self.archetypes.len())
3949 .field("component_count", &self.components.len())
3950 .finish()
3951 }
3952}
3953
3954// SAFETY: all methods on the world ensure that non-send resources are only accessible on the main thread
3955unsafe impl Send for World {}
3956// SAFETY: all methods on the world ensure that non-send resources are only accessible on the main thread
3957unsafe impl Sync for World {}
3958
3959/// Creates an instance of the type this trait is implemented for
3960/// using data from the supplied [`World`].
3961///
3962/// This can be helpful for complex initialization or context-aware defaults.
3963///
3964/// [`FromWorld`] is automatically implemented for any type implementing [`Default`]
3965/// and may also be derived for:
3966/// - any struct whose fields all implement `FromWorld`
3967/// - any enum where one variant has the attribute `#[from_world]`
3968///
3969/// ```rs
3970///
3971/// #[derive(Default)]
3972/// struct A;
3973///
3974/// #[derive(Default)]
3975/// struct B(Option<u32>)
3976///
3977/// struct C;
3978///
3979/// impl FromWorld for C {
3980/// fn from_world(_world: &mut World) -> Self {
3981/// Self
3982/// }
3983/// }
3984///
3985/// #[derive(FromWorld)]
3986/// struct D(A, B, C);
3987///
3988/// #[derive(FromWorld)]
3989/// enum E {
3990/// #[from_world]
3991/// F,
3992/// G
3993/// }
3994/// ```
3995pub trait FromWorld {
3996 /// Creates `Self` using data from the given [`World`].
3997 fn from_world(world: &mut World) -> Self;
3998}
3999
4000impl<T: Default> FromWorld for T {
4001 /// Creates `Self` using [`default()`](`Default::default`).
4002 #[track_caller]
4003 fn from_world(_world: &mut World) -> Self {
4004 T::default()
4005 }
4006}
4007
4008#[cfg(test)]
4009#[expect(clippy::print_stdout, reason = "Allowed in tests.")]
4010mod tests {
4011 use super::{FromWorld, World};
4012 use crate::{
4013 change_detection::{DetectChangesMut, MaybeLocation},
4014 component::{ComponentCloneBehavior, ComponentDescriptor, ComponentInfo, StorageType},
4015 entity::EntityHashSet,
4016 entity_disabling::{DefaultQueryFilters, Disabled},
4017 prelude::{DetectChanges, Event, Mut, On, Res},
4018 ptr::OwningPtr,
4019 resource::Resource,
4020 world::{error::EntityMutableFetchError, DeferredWorld},
4021 };
4022 use alloc::{
4023 borrow::ToOwned,
4024 string::{String, ToString},
4025 sync::Arc,
4026 vec,
4027 vec::Vec,
4028 };
4029 use bevy_ecs_macros::Component;
4030 use bevy_platform::collections::{HashMap, HashSet};
4031 use bevy_utils::prelude::DebugName;
4032 use core::{
4033 any::TypeId,
4034 panic,
4035 sync::atomic::{AtomicBool, AtomicU32, Ordering},
4036 };
4037 use std::{println, sync::Mutex};
4038
4039 type ID = u8;
4040
4041 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
4042 enum DropLogItem {
4043 Create(ID),
4044 Drop(ID),
4045 }
4046
4047 #[derive(Component)]
4048 struct MayPanicInDrop {
4049 drop_log: Arc<Mutex<Vec<DropLogItem>>>,
4050 expected_panic_flag: Arc<AtomicBool>,
4051 should_panic: bool,
4052 id: u8,
4053 }
4054
4055 impl MayPanicInDrop {
4056 fn new(
4057 drop_log: &Arc<Mutex<Vec<DropLogItem>>>,
4058 expected_panic_flag: &Arc<AtomicBool>,
4059 should_panic: bool,
4060 id: u8,
4061 ) -> Self {
4062 println!("creating component with id {id}");
4063 drop_log.lock().unwrap().push(DropLogItem::Create(id));
4064
4065 Self {
4066 drop_log: Arc::clone(drop_log),
4067 expected_panic_flag: Arc::clone(expected_panic_flag),
4068 should_panic,
4069 id,
4070 }
4071 }
4072 }
4073
4074 impl Drop for MayPanicInDrop {
4075 fn drop(&mut self) {
4076 println!("dropping component with id {}", self.id);
4077
4078 {
4079 let mut drop_log = self.drop_log.lock().unwrap();
4080 drop_log.push(DropLogItem::Drop(self.id));
4081 // Don't keep the mutex while panicking, or we'll poison it.
4082 drop(drop_log);
4083 }
4084
4085 if self.should_panic {
4086 self.expected_panic_flag.store(true, Ordering::SeqCst);
4087 panic!("testing what happens on panic inside drop");
4088 }
4089 }
4090 }
4091
4092 struct DropTestHelper {
4093 drop_log: Arc<Mutex<Vec<DropLogItem>>>,
4094 /// Set to `true` right before we intentionally panic, so that if we get
4095 /// a panic, we know if it was intended or not.
4096 expected_panic_flag: Arc<AtomicBool>,
4097 }
4098
4099 impl DropTestHelper {
4100 pub fn new() -> Self {
4101 Self {
4102 drop_log: Arc::new(Mutex::new(Vec::<DropLogItem>::new())),
4103 expected_panic_flag: Arc::new(AtomicBool::new(false)),
4104 }
4105 }
4106
4107 pub fn make_component(&self, should_panic: bool, id: ID) -> MayPanicInDrop {
4108 MayPanicInDrop::new(&self.drop_log, &self.expected_panic_flag, should_panic, id)
4109 }
4110
4111 pub fn finish(self, panic_res: std::thread::Result<()>) -> Vec<DropLogItem> {
4112 let drop_log = self.drop_log.lock().unwrap();
4113 let expected_panic_flag = self.expected_panic_flag.load(Ordering::SeqCst);
4114
4115 if !expected_panic_flag {
4116 match panic_res {
4117 Ok(()) => panic!("Expected a panic but it didn't happen"),
4118 Err(e) => std::panic::resume_unwind(e),
4119 }
4120 }
4121
4122 drop_log.to_owned()
4123 }
4124 }
4125
4126 #[test]
4127 fn panic_while_overwriting_component() {
4128 let helper = DropTestHelper::new();
4129
4130 let res = std::panic::catch_unwind(|| {
4131 let mut world = World::new();
4132 world
4133 .spawn_empty()
4134 .insert(helper.make_component(true, 0))
4135 .insert(helper.make_component(false, 1));
4136
4137 println!("Done inserting! Dropping world...");
4138 });
4139
4140 let drop_log = helper.finish(res);
4141
4142 assert_eq!(
4143 &*drop_log,
4144 [
4145 DropLogItem::Create(0),
4146 DropLogItem::Create(1),
4147 DropLogItem::Drop(0),
4148 DropLogItem::Drop(1),
4149 ]
4150 );
4151 }
4152
4153 #[derive(Resource)]
4154 struct TestResource(u32);
4155
4156 #[derive(Resource)]
4157 struct TestResource2(String);
4158
4159 #[derive(Resource)]
4160 struct TestResource3;
4161
4162 #[test]
4163 fn get_resource_by_id() {
4164 let mut world = World::new();
4165 world.insert_resource(TestResource(42));
4166 let component_id = world
4167 .components()
4168 .get_valid_id(TypeId::of::<TestResource>())
4169 .unwrap();
4170
4171 let resource = world.get_resource_by_id(component_id).unwrap();
4172 // SAFETY: `TestResource` is the correct resource type
4173 let resource = unsafe { resource.deref::<TestResource>() };
4174
4175 assert_eq!(resource.0, 42);
4176 }
4177
4178 #[test]
4179 fn get_resource_mut_by_id() {
4180 let mut world = World::new();
4181 world.insert_resource(TestResource(42));
4182 let component_id = world
4183 .components()
4184 .get_valid_id(TypeId::of::<TestResource>())
4185 .unwrap();
4186
4187 {
4188 let mut resource = world.get_resource_mut_by_id(component_id).unwrap();
4189 resource.set_changed();
4190 // SAFETY: `TestResource` is the correct resource type
4191 let resource = unsafe { resource.into_inner().deref_mut::<TestResource>() };
4192 resource.0 = 43;
4193 }
4194
4195 let resource = world.get_resource_by_id(component_id).unwrap();
4196 // SAFETY: `TestResource` is the correct resource type
4197 let resource = unsafe { resource.deref::<TestResource>() };
4198
4199 assert_eq!(resource.0, 43);
4200 }
4201
4202 #[test]
4203 fn iter_resources() {
4204 let mut world = World::new();
4205 // Remove DefaultQueryFilters so it doesn't show up in the iterator
4206 world.remove_resource::<DefaultQueryFilters>();
4207 world.insert_resource(TestResource(42));
4208 world.insert_resource(TestResource2("Hello, world!".to_string()));
4209 world.insert_resource(TestResource3);
4210 world.remove_resource::<TestResource3>();
4211
4212 let mut iter = world.iter_resources();
4213
4214 let (info, ptr) = iter.next().unwrap();
4215 assert_eq!(info.name(), DebugName::type_name::<TestResource>());
4216 // SAFETY: We know that the resource is of type `TestResource`
4217 assert_eq!(unsafe { ptr.deref::<TestResource>().0 }, 42);
4218
4219 let (info, ptr) = iter.next().unwrap();
4220 assert_eq!(info.name(), DebugName::type_name::<TestResource2>());
4221 assert_eq!(
4222 // SAFETY: We know that the resource is of type `TestResource2`
4223 unsafe { &ptr.deref::<TestResource2>().0 },
4224 &"Hello, world!".to_string()
4225 );
4226
4227 assert!(iter.next().is_none());
4228 }
4229
4230 #[test]
4231 fn iter_resources_mut() {
4232 let mut world = World::new();
4233 // Remove DefaultQueryFilters so it doesn't show up in the iterator
4234 world.remove_resource::<DefaultQueryFilters>();
4235 world.insert_resource(TestResource(42));
4236 world.insert_resource(TestResource2("Hello, world!".to_string()));
4237 world.insert_resource(TestResource3);
4238 world.remove_resource::<TestResource3>();
4239
4240 let mut iter = world.iter_resources_mut();
4241
4242 let (info, mut mut_untyped) = iter.next().unwrap();
4243 assert_eq!(info.name(), DebugName::type_name::<TestResource>());
4244 // SAFETY: We know that the resource is of type `TestResource`
4245 unsafe {
4246 mut_untyped.as_mut().deref_mut::<TestResource>().0 = 43;
4247 };
4248
4249 let (info, mut mut_untyped) = iter.next().unwrap();
4250 assert_eq!(info.name(), DebugName::type_name::<TestResource2>());
4251 // SAFETY: We know that the resource is of type `TestResource2`
4252 unsafe {
4253 mut_untyped.as_mut().deref_mut::<TestResource2>().0 = "Hello, world?".to_string();
4254 };
4255
4256 assert!(iter.next().is_none());
4257 drop(iter);
4258
4259 assert_eq!(world.resource::<TestResource>().0, 43);
4260 assert_eq!(
4261 world.resource::<TestResource2>().0,
4262 "Hello, world?".to_string()
4263 );
4264 }
4265
4266 #[test]
4267 fn custom_non_send_with_layout() {
4268 static DROP_COUNT: AtomicU32 = AtomicU32::new(0);
4269
4270 let mut world = World::new();
4271
4272 // SAFETY: the drop function is valid for the layout and the data will be safe to access from any thread
4273 let descriptor = unsafe {
4274 ComponentDescriptor::new_with_layout(
4275 "Custom Test Component".to_string(),
4276 StorageType::Table,
4277 core::alloc::Layout::new::<[u8; 8]>(),
4278 Some(|ptr| {
4279 let data = ptr.read::<[u8; 8]>();
4280 assert_eq!(data, [0, 1, 2, 3, 4, 5, 6, 7]);
4281 DROP_COUNT.fetch_add(1, Ordering::SeqCst);
4282 }),
4283 true,
4284 ComponentCloneBehavior::Default,
4285 None,
4286 )
4287 };
4288
4289 let component_id = world.register_component_with_descriptor(descriptor);
4290
4291 let value: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
4292 OwningPtr::make(value, |ptr| {
4293 // SAFETY: value is valid for the component layout
4294 unsafe {
4295 world.insert_non_send_by_id(component_id, ptr, MaybeLocation::caller());
4296 }
4297 });
4298
4299 // SAFETY: [u8; 8] is the correct type for the resource
4300 let data = unsafe {
4301 world
4302 .get_non_send_by_id(component_id)
4303 .unwrap()
4304 .deref::<[u8; 8]>()
4305 };
4306 assert_eq!(*data, [0, 1, 2, 3, 4, 5, 6, 7]);
4307
4308 assert!(world.remove_non_send_by_id(component_id).is_some());
4309
4310 assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1);
4311 }
4312
4313 #[derive(Resource)]
4314 struct TestFromWorld(u32);
4315 impl FromWorld for TestFromWorld {
4316 fn from_world(world: &mut World) -> Self {
4317 let b = world.resource::<TestResource>();
4318 Self(b.0)
4319 }
4320 }
4321
4322 #[test]
4323 fn init_resource_does_not_overwrite() {
4324 let mut world = World::new();
4325 world.insert_resource(TestResource(0));
4326 world.init_resource::<TestFromWorld>();
4327 world.insert_resource(TestResource(1));
4328 world.init_resource::<TestFromWorld>();
4329
4330 let resource = world.resource::<TestFromWorld>();
4331
4332 assert_eq!(resource.0, 0);
4333 }
4334
4335 #[test]
4336 fn init_non_send_does_not_overwrite() {
4337 let mut world = World::new();
4338 world.insert_resource(TestResource(0));
4339 world.init_non_send::<TestFromWorld>();
4340 world.insert_resource(TestResource(1));
4341 world.init_non_send::<TestFromWorld>();
4342
4343 let resource = world.non_send::<TestFromWorld>();
4344
4345 assert_eq!(resource.0, 0);
4346 }
4347
4348 #[derive(Component)]
4349 struct Foo;
4350
4351 #[derive(Component)]
4352 struct Bar;
4353
4354 #[derive(Component)]
4355 struct Baz;
4356
4357 #[test]
4358 fn inspect_entity_components() {
4359 let mut world = World::new();
4360 let ent0 = world.spawn((Foo, Bar, Baz)).id();
4361 let ent1 = world.spawn((Foo, Bar)).id();
4362 let ent2 = world.spawn((Bar, Baz)).id();
4363 let ent3 = world.spawn((Foo, Baz)).id();
4364 let ent4 = world.spawn(Foo).id();
4365 let ent5 = world.spawn(Bar).id();
4366 let ent6 = world.spawn(Baz).id();
4367
4368 fn to_type_ids(component_infos: Vec<&ComponentInfo>) -> HashSet<Option<TypeId>> {
4369 component_infos
4370 .into_iter()
4371 .map(ComponentInfo::type_id)
4372 .collect()
4373 }
4374
4375 let foo_id = TypeId::of::<Foo>();
4376 let bar_id = TypeId::of::<Bar>();
4377 let baz_id = TypeId::of::<Baz>();
4378 assert_eq!(
4379 to_type_ids(world.inspect_entity(ent0).unwrap().collect()),
4380 [Some(foo_id), Some(bar_id), Some(baz_id)]
4381 .into_iter()
4382 .collect::<HashSet<_>>()
4383 );
4384 assert_eq!(
4385 to_type_ids(world.inspect_entity(ent1).unwrap().collect()),
4386 [Some(foo_id), Some(bar_id)]
4387 .into_iter()
4388 .collect::<HashSet<_>>()
4389 );
4390 assert_eq!(
4391 to_type_ids(world.inspect_entity(ent2).unwrap().collect()),
4392 [Some(bar_id), Some(baz_id)]
4393 .into_iter()
4394 .collect::<HashSet<_>>()
4395 );
4396 assert_eq!(
4397 to_type_ids(world.inspect_entity(ent3).unwrap().collect()),
4398 [Some(foo_id), Some(baz_id)]
4399 .into_iter()
4400 .collect::<HashSet<_>>()
4401 );
4402 assert_eq!(
4403 to_type_ids(world.inspect_entity(ent4).unwrap().collect()),
4404 [Some(foo_id)].into_iter().collect::<HashSet<_>>()
4405 );
4406 assert_eq!(
4407 to_type_ids(world.inspect_entity(ent5).unwrap().collect()),
4408 [Some(bar_id)].into_iter().collect::<HashSet<_>>()
4409 );
4410 assert_eq!(
4411 to_type_ids(world.inspect_entity(ent6).unwrap().collect()),
4412 [Some(baz_id)].into_iter().collect::<HashSet<_>>()
4413 );
4414 }
4415
4416 #[test]
4417 fn iterate_entities() {
4418 let mut world = World::new();
4419 let mut entity_counters = <HashMap<_, _>>::default();
4420
4421 let iterate_and_count_entities = |world: &World, entity_counters: &mut HashMap<_, _>| {
4422 entity_counters.clear();
4423 for entity in world.iter_entities() {
4424 let counter = entity_counters.entry(entity.id()).or_insert(0);
4425 *counter += 1;
4426 }
4427 };
4428
4429 // Adding one entity and validating iteration
4430 let ent0 = world.spawn((Foo, Bar, Baz)).id();
4431
4432 iterate_and_count_entities(&world, &mut entity_counters);
4433 assert_eq!(entity_counters[&ent0], 1);
4434 assert_eq!(entity_counters.len(), 2);
4435
4436 // Spawning three more entities and then validating iteration
4437 let ent1 = world.spawn((Foo, Bar)).id();
4438 let ent2 = world.spawn((Bar, Baz)).id();
4439 let ent3 = world.spawn((Foo, Baz)).id();
4440
4441 iterate_and_count_entities(&world, &mut entity_counters);
4442
4443 assert_eq!(entity_counters[&ent0], 1);
4444 assert_eq!(entity_counters[&ent1], 1);
4445 assert_eq!(entity_counters[&ent2], 1);
4446 assert_eq!(entity_counters[&ent3], 1);
4447 assert_eq!(entity_counters.len(), 5);
4448
4449 // Despawning first entity and then validating the iteration
4450 assert!(world.despawn(ent0));
4451
4452 iterate_and_count_entities(&world, &mut entity_counters);
4453
4454 assert_eq!(entity_counters[&ent1], 1);
4455 assert_eq!(entity_counters[&ent2], 1);
4456 assert_eq!(entity_counters[&ent3], 1);
4457 assert_eq!(entity_counters.len(), 4);
4458
4459 // Spawning three more entities, despawning three and then validating the iteration
4460 let ent4 = world.spawn(Foo).id();
4461 let ent5 = world.spawn(Bar).id();
4462 let ent6 = world.spawn(Baz).id();
4463
4464 assert!(world.despawn(ent2));
4465 assert!(world.despawn(ent3));
4466 assert!(world.despawn(ent4));
4467
4468 iterate_and_count_entities(&world, &mut entity_counters);
4469
4470 assert_eq!(entity_counters[&ent1], 1);
4471 assert_eq!(entity_counters[&ent5], 1);
4472 assert_eq!(entity_counters[&ent6], 1);
4473 assert_eq!(entity_counters.len(), 4);
4474
4475 // Despawning remaining entities and then validating the iteration
4476 assert!(world.despawn(ent1));
4477 assert!(world.despawn(ent5));
4478 assert!(world.despawn(ent6));
4479
4480 iterate_and_count_entities(&world, &mut entity_counters);
4481
4482 assert_eq!(entity_counters.len(), 1);
4483 }
4484
4485 #[test]
4486 fn spawn_empty_bundle() {
4487 let mut world = World::new();
4488 world.spawn(());
4489 }
4490
4491 #[test]
4492 fn get_entity() {
4493 let mut world = World::new();
4494
4495 let e1 = world.spawn_empty().id();
4496 let e2 = world.spawn_empty().id();
4497
4498 assert!(world.get_entity(e1).is_ok());
4499 assert!(world.get_entity([e1, e2]).is_ok());
4500 assert!(world
4501 .get_entity(&[e1, e2] /* this is an array not a slice */)
4502 .is_ok());
4503 assert!(world.get_entity(&vec![e1, e2][..]).is_ok());
4504 assert!(world
4505 .get_entity(&EntityHashSet::from_iter([e1, e2]))
4506 .is_ok());
4507
4508 world.entity_mut(e1).despawn();
4509
4510 assert_eq!(
4511 Err(e1),
4512 world.get_entity(e1).map(|_| {}).map_err(|e| e.entity())
4513 );
4514 assert_eq!(
4515 Err(e1),
4516 world
4517 .get_entity([e1, e2])
4518 .map(|_| {})
4519 .map_err(|e| e.entity())
4520 );
4521 assert_eq!(
4522 Err(e1),
4523 world
4524 .get_entity(&[e1, e2] /* this is an array not a slice */)
4525 .map(|_| {})
4526 .map_err(|e| e.entity())
4527 );
4528 assert_eq!(
4529 Err(e1),
4530 world
4531 .get_entity(&vec![e1, e2][..])
4532 .map(|_| {})
4533 .map_err(|e| e.entity())
4534 );
4535 assert_eq!(
4536 Err(e1),
4537 world
4538 .get_entity(&EntityHashSet::from_iter([e1, e2]))
4539 .map(|_| {})
4540 .map_err(|e| e.entity())
4541 );
4542 }
4543
4544 #[test]
4545 fn get_entity_mut() {
4546 let mut world = World::new();
4547
4548 let e1 = world.spawn_empty().id();
4549 let e2 = world.spawn_empty().id();
4550
4551 assert!(world.get_entity_mut(e1).is_ok());
4552 assert!(world.get_entity_mut([e1, e2]).is_ok());
4553 assert!(world
4554 .get_entity_mut(&[e1, e2] /* this is an array not a slice */)
4555 .is_ok());
4556 assert!(world.get_entity_mut(&vec![e1, e2][..]).is_ok());
4557 assert!(world
4558 .get_entity_mut(&EntityHashSet::from_iter([e1, e2]))
4559 .is_ok());
4560
4561 assert_eq!(
4562 Err(EntityMutableFetchError::AliasedMutability(e1)),
4563 world.get_entity_mut([e1, e2, e1]).map(|_| {})
4564 );
4565 assert_eq!(
4566 Err(EntityMutableFetchError::AliasedMutability(e1)),
4567 world
4568 .get_entity_mut(&[e1, e2, e1] /* this is an array not a slice */)
4569 .map(|_| {})
4570 );
4571 assert_eq!(
4572 Err(EntityMutableFetchError::AliasedMutability(e1)),
4573 world.get_entity_mut(&vec![e1, e2, e1][..]).map(|_| {})
4574 );
4575 // Aliased mutability isn't allowed by HashSets
4576 assert!(world
4577 .get_entity_mut(&EntityHashSet::from_iter([e1, e2, e1]))
4578 .is_ok());
4579
4580 world.entity_mut(e1).despawn();
4581 assert!(world.get_entity_mut(e2).is_ok());
4582
4583 assert!(matches!(
4584 world.get_entity_mut(e1).map(|_| {}),
4585 Err(EntityMutableFetchError::NotSpawned(e)) if e.entity() == e1
4586 ));
4587 assert!(matches!(
4588 world.get_entity_mut([e1, e2]).map(|_| {}),
4589 Err(EntityMutableFetchError::NotSpawned(e)) if e.entity() == e1));
4590 assert!(matches!(
4591 world
4592 .get_entity_mut(&[e1, e2] /* this is an array not a slice */)
4593 .map(|_| {}),
4594 Err(EntityMutableFetchError::NotSpawned(e)) if e.entity() == e1));
4595 assert!(matches!(
4596 world.get_entity_mut(&vec![e1, e2][..]).map(|_| {}),
4597 Err(EntityMutableFetchError::NotSpawned(e)) if e.entity() == e1,
4598 ));
4599 assert!(matches!(
4600 world
4601 .get_entity_mut(&EntityHashSet::from_iter([e1, e2]))
4602 .map(|_| {}),
4603 Err(EntityMutableFetchError::NotSpawned(e)) if e.entity() == e1));
4604 }
4605
4606 #[test]
4607 #[track_caller]
4608 fn entity_spawn_despawn_tracking() {
4609 use core::panic::Location;
4610
4611 let mut world = World::new();
4612 let entity = world.spawn_empty().id();
4613 assert_eq!(
4614 world.entities.entity_get_spawned_or_despawned_by(entity),
4615 MaybeLocation::new(Some(Location::caller()))
4616 );
4617 assert_eq!(
4618 world.entities.entity_get_spawn_or_despawn_tick(entity),
4619 Some(world.change_tick())
4620 );
4621 let new = world.despawn_no_free(entity).unwrap();
4622 assert_eq!(
4623 world.entities.entity_get_spawned_or_despawned_by(entity),
4624 MaybeLocation::new(Some(Location::caller()))
4625 );
4626 assert_eq!(
4627 world.entities.entity_get_spawn_or_despawn_tick(entity),
4628 Some(world.change_tick())
4629 );
4630
4631 world.spawn_empty_at(new).unwrap();
4632 assert_eq!(entity.index(), new.index());
4633 assert_eq!(
4634 world.entities.entity_get_spawned_or_despawned_by(entity),
4635 MaybeLocation::new(None)
4636 );
4637 assert_eq!(
4638 world.entities.entity_get_spawn_or_despawn_tick(entity),
4639 None
4640 );
4641 world.despawn(new);
4642 assert_eq!(
4643 world.entities.entity_get_spawned_or_despawned_by(entity),
4644 MaybeLocation::new(None)
4645 );
4646 assert_eq!(
4647 world.entities.entity_get_spawn_or_despawn_tick(entity),
4648 None
4649 );
4650 }
4651
4652 #[test]
4653 fn new_world_has_disabling() {
4654 let mut world = World::new();
4655 world.spawn(Foo);
4656 world.spawn((Foo, Disabled));
4657 assert_eq!(1, world.query::<&Foo>().iter(&world).count());
4658
4659 // If we explicitly remove the resource, no entities should be filtered anymore
4660 world.remove_resource::<DefaultQueryFilters>();
4661 assert_eq!(2, world.query::<&Foo>().iter(&world).count());
4662 }
4663
4664 #[test]
4665 fn entities_and_commands() {
4666 #[derive(Component, PartialEq, Debug)]
4667 struct Foo(u32);
4668
4669 let mut world = World::new();
4670
4671 let eid = world.spawn(Foo(35)).id();
4672
4673 let (mut fetcher, mut commands) = world.entities_and_commands();
4674 let emut = fetcher.get_mut(eid).unwrap();
4675 commands.entity(eid).despawn();
4676 assert_eq!(emut.get::<Foo>().unwrap(), &Foo(35));
4677
4678 world.flush();
4679
4680 assert!(world.get_entity(eid).is_err());
4681 }
4682
4683 #[test]
4684 fn resource_query_after_resource_scope() {
4685 #[derive(Event)]
4686 struct EventA;
4687
4688 #[derive(Resource)]
4689 struct ResourceA;
4690
4691 let mut world = World::default();
4692
4693 world.insert_resource(ResourceA);
4694 world.add_observer(move |_event: On<EventA>, _res: Res<ResourceA>| {});
4695 world.resource_scope(|world, _res: Mut<ResourceA>| {
4696 // since we use commands, this should trigger outside of the resource_scope, so the observer should work.
4697 world.commands().trigger(EventA);
4698 });
4699 }
4700
4701 #[test]
4702 fn entities_and_commands_deferred() {
4703 #[derive(Component, PartialEq, Debug)]
4704 struct Foo(u32);
4705
4706 let mut world = World::new();
4707
4708 let eid = world.spawn(Foo(1)).id();
4709
4710 let mut dworld = DeferredWorld::from(&mut world);
4711
4712 let (mut fetcher, mut commands) = dworld.entities_and_commands();
4713 let emut = fetcher.get_mut(eid).unwrap();
4714 commands.entity(eid).despawn();
4715 assert_eq!(emut.get::<Foo>().unwrap(), &Foo(1));
4716
4717 world.flush();
4718
4719 assert!(world.get_entity(eid).is_err());
4720 }
4721
4722 #[test]
4723 fn resource_scope_ticks() {
4724 #[derive(Resource)]
4725 struct R;
4726
4727 let mut world = World::new();
4728 world.insert_resource(R);
4729 world.resource_scope(|world, r: Mut<R>| {
4730 assert_eq!(world.change_tick(), r.added());
4731 assert_eq!(world.change_tick(), r.last_changed());
4732 world.increment_change_tick();
4733 });
4734 assert_eq!(world.change_tick(), world.resource_ref::<R>().added());
4735 assert_eq!(
4736 world.change_tick(),
4737 world.resource_ref::<R>().last_changed()
4738 );
4739 }
4740}