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 /// Despawns the given [`Entity`], if it exists.
1480 /// This will also remove all of the entity's [`Components`](Component).
1481 ///
1482 /// Returns `true` if the entity is successfully despawned and `false` if
1483 /// the entity does not exist.
1484 /// This counts despawning a not constructed entity as a success, and frees it to the allocator.
1485 /// See [entity](crate::entity) module docs for more about construction.
1486 ///
1487 /// # Note
1488 ///
1489 /// This will also despawn the entities in any [`RelationshipTarget`](crate::relationship::RelationshipTarget) that is configured
1490 /// to despawn descendants. For example, this will recursively despawn [`Children`](crate::hierarchy::Children).
1491 ///
1492 /// ```
1493 /// use bevy_ecs::{component::Component, world::World};
1494 ///
1495 /// #[derive(Component)]
1496 /// struct Position {
1497 /// x: f32,
1498 /// y: f32,
1499 /// }
1500 ///
1501 /// let mut world = World::new();
1502 /// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
1503 /// assert!(world.despawn(entity));
1504 /// assert!(world.get_entity(entity).is_err());
1505 /// assert!(world.get::<Position>(entity).is_none());
1506 /// ```
1507 #[track_caller]
1508 #[inline]
1509 pub fn despawn(&mut self, entity: Entity) -> bool {
1510 if let Err(error) = self.despawn_with_caller(entity, MaybeLocation::caller()) {
1511 warn!("{error}");
1512 false
1513 } else {
1514 true
1515 }
1516 }
1517
1518 /// Despawns the given `entity`, if it exists. This will also remove all of the entity's
1519 /// [`Components`](Component).
1520 ///
1521 /// Returns an [`EntityDespawnError`] if the entity is not spawned to be despawned.
1522 ///
1523 /// # Note
1524 ///
1525 /// This will also despawn the entities in any [`RelationshipTarget`](crate::relationship::RelationshipTarget) that is configured
1526 /// to despawn descendants. For example, this will recursively despawn [`Children`](crate::hierarchy::Children).
1527 #[track_caller]
1528 #[inline]
1529 pub fn try_despawn(&mut self, entity: Entity) -> Result<(), EntityDespawnError> {
1530 self.despawn_with_caller(entity, MaybeLocation::caller())
1531 }
1532
1533 #[inline]
1534 pub(crate) fn despawn_with_caller(
1535 &mut self,
1536 entity: Entity,
1537 caller: MaybeLocation,
1538 ) -> Result<(), EntityDespawnError> {
1539 match self.get_entity_mut(entity) {
1540 Ok(entity) => {
1541 entity.despawn_with_caller(caller);
1542 Ok(())
1543 }
1544 // Only one entity.
1545 Err(EntityMutableFetchError::AliasedMutability(_)) => unreachable!(),
1546 Err(EntityMutableFetchError::NotSpawned(err)) => Err(EntityDespawnError(err)),
1547 }
1548 }
1549
1550 /// Performs [`try_despawn_no_free`](Self::try_despawn_no_free), warning on errors.
1551 /// See that method for more information.
1552 #[track_caller]
1553 #[inline]
1554 pub fn despawn_no_free(&mut self, entity: Entity) -> Option<Entity> {
1555 match self.despawn_no_free_with_caller(entity, MaybeLocation::caller()) {
1556 Ok(entity) => Some(entity),
1557 Err(error) => {
1558 warn!("{error}");
1559 None
1560 }
1561 }
1562 }
1563
1564 /// Despawns the given `entity`, if it exists.
1565 /// This will also remove all of the entity's [`Component`]s.
1566 ///
1567 /// The *only* difference between this and [despawning](Self::despawn) an entity is that this does not release the `entity` to be reused.
1568 /// 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.
1569 /// In general, [`despawn`](Self::despawn) should be used instead, which automatically allows the row to be reused.
1570 ///
1571 /// Returns the new [`Entity`] if of the despawned [`EntityIndex`](crate::entity::EntityIndex), which should eventually either be re-spawned or freed to the allocator.
1572 /// Returns an [`EntityDespawnError`] if the entity is not spawned.
1573 ///
1574 /// # Note
1575 ///
1576 /// This will also *despawn* the entities in any [`RelationshipTarget`](crate::relationship::RelationshipTarget) that is configured
1577 /// to despawn descendants. For example, this will recursively despawn [`Children`](crate::hierarchy::Children).
1578 ///
1579 /// # Example
1580 ///
1581 /// There is no simple example in which this would be practical, but one use for this is a custom entity allocator.
1582 /// Despawning internally calls this and frees the entity id to Bevy's default entity allocator.
1583 /// The same principal can be used to create custom allocators with additional properties.
1584 /// For example, this could be used to make an allocator that yields groups of consecutive [`EntityIndex`](crate::entity::EntityIndex)s, etc.
1585 /// See [`EntityAllocator::alloc`] for more on this.
1586 #[track_caller]
1587 #[inline]
1588 pub fn try_despawn_no_free(&mut self, entity: Entity) -> Result<Entity, EntityDespawnError> {
1589 self.despawn_no_free_with_caller(entity, MaybeLocation::caller())
1590 }
1591
1592 #[inline]
1593 pub(crate) fn despawn_no_free_with_caller(
1594 &mut self,
1595 entity: Entity,
1596 caller: MaybeLocation,
1597 ) -> Result<Entity, EntityDespawnError> {
1598 let mut entity = self.get_entity_mut(entity).map_err(|err| match err {
1599 EntityMutableFetchError::NotSpawned(err) => err,
1600 // Only one entity.
1601 EntityMutableFetchError::AliasedMutability(_) => unreachable!(),
1602 })?;
1603 entity.despawn_no_free_with_caller(caller);
1604 Ok(entity.id())
1605 }
1606
1607 /// Clears the internal component tracker state.
1608 ///
1609 /// The world maintains some internal state about changed and removed components. This state
1610 /// is used by [`RemovedComponents`] to provide access to the entities that had a specific type
1611 /// of component removed since last tick.
1612 ///
1613 /// The state is also used for change detection when accessing components and resources outside
1614 /// of a system, for example via [`World::get_mut()`] or [`World::get_resource_mut()`].
1615 ///
1616 /// By clearing this internal state, the world "forgets" about those changes, allowing a new round
1617 /// of detection to be recorded.
1618 ///
1619 /// When using `bevy_ecs` as part of the full Bevy engine, this method is called automatically
1620 /// by `bevy_app::App::update` and `bevy_app::SubApp::update`, so you don't need to call it manually.
1621 /// When using `bevy_ecs` as a separate standalone crate however, you do need to call this manually.
1622 ///
1623 /// ```
1624 /// # use bevy_ecs::prelude::*;
1625 /// # #[derive(Component, Default)]
1626 /// # struct Transform;
1627 /// // a whole new world
1628 /// let mut world = World::new();
1629 ///
1630 /// // you changed it
1631 /// let entity = world.spawn(Transform::default()).id();
1632 ///
1633 /// // change is detected
1634 /// let transform = world.get_mut::<Transform>(entity).unwrap();
1635 /// assert!(transform.is_changed());
1636 ///
1637 /// // update the last change tick
1638 /// world.clear_trackers();
1639 ///
1640 /// // change is no longer detected
1641 /// let transform = world.get_mut::<Transform>(entity).unwrap();
1642 /// assert!(!transform.is_changed());
1643 /// ```
1644 ///
1645 /// [`RemovedComponents`]: crate::lifecycle::RemovedComponents
1646 pub fn clear_trackers(&mut self) {
1647 self.removed_components.update();
1648 self.last_change_tick = self.increment_change_tick();
1649 }
1650
1651 /// Returns [`QueryState`] for the given [`QueryData`], which is used to efficiently
1652 /// run queries on the [`World`] by storing and reusing the [`QueryState`].
1653 /// ```
1654 /// use bevy_ecs::{component::Component, entity::Entity, world::World};
1655 ///
1656 /// #[derive(Component, Debug, PartialEq)]
1657 /// struct Position {
1658 /// x: f32,
1659 /// y: f32,
1660 /// }
1661 ///
1662 /// #[derive(Component)]
1663 /// struct Velocity {
1664 /// x: f32,
1665 /// y: f32,
1666 /// }
1667 ///
1668 /// let mut world = World::new();
1669 /// let entities = world.spawn_batch(vec![
1670 /// (Position { x: 0.0, y: 0.0}, Velocity { x: 1.0, y: 0.0 }),
1671 /// (Position { x: 0.0, y: 0.0}, Velocity { x: 0.0, y: 1.0 }),
1672 /// ]).collect::<Vec<Entity>>();
1673 ///
1674 /// let mut query = world.query::<(&mut Position, &Velocity)>();
1675 /// for (mut position, velocity) in query.iter_mut(&mut world) {
1676 /// position.x += velocity.x;
1677 /// position.y += velocity.y;
1678 /// }
1679 ///
1680 /// assert_eq!(world.get::<Position>(entities[0]).unwrap(), &Position { x: 1.0, y: 0.0 });
1681 /// assert_eq!(world.get::<Position>(entities[1]).unwrap(), &Position { x: 0.0, y: 1.0 });
1682 /// ```
1683 ///
1684 /// To iterate over entities in a deterministic order,
1685 /// sort the results of the query using the desired component as a key.
1686 /// Note that this requires fetching the whole result set from the query
1687 /// and allocation of a [`Vec`] to store it.
1688 ///
1689 /// ```
1690 /// use bevy_ecs::{component::Component, entity::Entity, world::World};
1691 ///
1692 /// #[derive(Component, PartialEq, Eq, PartialOrd, Ord, Debug)]
1693 /// struct Order(i32);
1694 /// #[derive(Component, PartialEq, Debug)]
1695 /// struct Label(&'static str);
1696 ///
1697 /// let mut world = World::new();
1698 /// let a = world.spawn((Order(2), Label("second"))).id();
1699 /// let b = world.spawn((Order(3), Label("third"))).id();
1700 /// let c = world.spawn((Order(1), Label("first"))).id();
1701 /// let mut entities = world.query::<(Entity, &Order, &Label)>()
1702 /// .iter(&world)
1703 /// .collect::<Vec<_>>();
1704 /// // Sort the query results by their `Order` component before comparing
1705 /// // to expected results. Query iteration order should not be relied on.
1706 /// entities.sort_by_key(|e| e.1);
1707 /// assert_eq!(entities, vec![
1708 /// (c, &Order(1), &Label("first")),
1709 /// (a, &Order(2), &Label("second")),
1710 /// (b, &Order(3), &Label("third")),
1711 /// ]);
1712 /// ```
1713 #[inline]
1714 pub fn query<D: QueryData>(&mut self) -> QueryState<D, ()> {
1715 self.query_filtered::<D, ()>()
1716 }
1717
1718 /// Returns [`QueryState`] for the given filtered [`QueryData`], which is used to efficiently
1719 /// run queries on the [`World`] by storing and reusing the [`QueryState`].
1720 /// ```
1721 /// use bevy_ecs::{component::Component, entity::Entity, world::World, query::With};
1722 ///
1723 /// #[derive(Component)]
1724 /// struct A;
1725 /// #[derive(Component)]
1726 /// struct B;
1727 ///
1728 /// let mut world = World::new();
1729 /// let e1 = world.spawn(A).id();
1730 /// let e2 = world.spawn((A, B)).id();
1731 ///
1732 /// let mut query = world.query_filtered::<Entity, With<B>>();
1733 /// let matching_entities = query.iter(&world).collect::<Vec<Entity>>();
1734 ///
1735 /// assert_eq!(matching_entities, vec![e2]);
1736 /// ```
1737 #[inline]
1738 pub fn query_filtered<D: QueryData, F: QueryFilter>(&mut self) -> QueryState<D, F> {
1739 QueryState::new(self)
1740 }
1741
1742 /// Returns [`QueryState`] for the given [`QueryData`], which is used to efficiently
1743 /// run queries on the [`World`] by storing and reusing the [`QueryState`].
1744 /// ```
1745 /// use bevy_ecs::{component::Component, entity::Entity, world::World};
1746 ///
1747 /// #[derive(Component, Debug, PartialEq)]
1748 /// struct Position {
1749 /// x: f32,
1750 /// y: f32,
1751 /// }
1752 ///
1753 /// let mut world = World::new();
1754 /// world.spawn_batch(vec![
1755 /// Position { x: 0.0, y: 0.0 },
1756 /// Position { x: 1.0, y: 1.0 },
1757 /// ]);
1758 ///
1759 /// fn get_positions(world: &World) -> Vec<(Entity, &Position)> {
1760 /// let mut query = world.try_query::<(Entity, &Position)>().unwrap();
1761 /// query.iter(world).collect()
1762 /// }
1763 ///
1764 /// let positions = get_positions(&world);
1765 ///
1766 /// assert_eq!(world.get::<Position>(positions[0].0).unwrap(), positions[0].1);
1767 /// assert_eq!(world.get::<Position>(positions[1].0).unwrap(), positions[1].1);
1768 /// ```
1769 ///
1770 /// Requires only an immutable world reference, but may fail if, for example,
1771 /// the components that make up this query have not been registered into the world.
1772 /// ```
1773 /// use bevy_ecs::{component::Component, entity::Entity, world::World};
1774 ///
1775 /// #[derive(Component)]
1776 /// struct A;
1777 ///
1778 /// let mut world = World::new();
1779 ///
1780 /// let none_query = world.try_query::<&A>();
1781 /// assert!(none_query.is_none());
1782 ///
1783 /// world.register_component::<A>();
1784 ///
1785 /// let some_query = world.try_query::<&A>();
1786 /// assert!(some_query.is_some());
1787 /// ```
1788 #[inline]
1789 pub fn try_query<D: QueryData>(&self) -> Option<QueryState<D, ()>> {
1790 self.try_query_filtered::<D, ()>()
1791 }
1792
1793 /// Returns [`QueryState`] for the given filtered [`QueryData`], which is used to efficiently
1794 /// run queries on the [`World`] by storing and reusing the [`QueryState`].
1795 /// ```
1796 /// use bevy_ecs::{component::Component, entity::Entity, world::World, query::With};
1797 ///
1798 /// #[derive(Component)]
1799 /// struct A;
1800 /// #[derive(Component)]
1801 /// struct B;
1802 ///
1803 /// let mut world = World::new();
1804 /// let e1 = world.spawn(A).id();
1805 /// let e2 = world.spawn((A, B)).id();
1806 ///
1807 /// let mut query = world.try_query_filtered::<Entity, With<B>>().unwrap();
1808 /// let matching_entities = query.iter(&world).collect::<Vec<Entity>>();
1809 ///
1810 /// assert_eq!(matching_entities, vec![e2]);
1811 /// ```
1812 ///
1813 /// Requires only an immutable world reference, but may fail if, for example,
1814 /// the components that make up this query have not been registered into the world.
1815 #[inline]
1816 pub fn try_query_filtered<D: QueryData, F: QueryFilter>(&self) -> Option<QueryState<D, F>> {
1817 QueryState::try_new(self)
1818 }
1819
1820 /// Returns an iterator of entities that had components of type `T` removed
1821 /// since the last call to [`World::clear_trackers`].
1822 pub fn removed<T: Component>(&self) -> impl Iterator<Item = Entity> + '_ {
1823 self.components
1824 .get_valid_id(TypeId::of::<T>())
1825 .map(|component_id| self.removed_with_id(component_id))
1826 .into_iter()
1827 .flatten()
1828 }
1829
1830 /// Returns an iterator of entities that had components with the given `component_id` removed
1831 /// since the last call to [`World::clear_trackers`].
1832 pub fn removed_with_id(&self, component_id: ComponentId) -> impl Iterator<Item = Entity> + '_ {
1833 self.removed_components
1834 .get(component_id)
1835 .map(|removed| removed.iter_current_update_messages().cloned())
1836 .into_iter()
1837 .flatten()
1838 .map(Into::into)
1839 }
1840
1841 /// Registers a new non-send resource type and returns the [`ComponentId`] created for it.
1842 ///
1843 /// This enables the dynamic registration of new non-send resources definitions at runtime for
1844 /// advanced use cases.
1845 ///
1846 /// # Note
1847 ///
1848 /// Registering a non-send resource does not insert it into [`World`]. For insertion, you could use
1849 /// [`World::insert_non_send_by_id`].
1850 pub fn register_non_send_with_descriptor(
1851 &mut self,
1852 descriptor: ComponentDescriptor,
1853 ) -> ComponentId {
1854 self.components_registrator()
1855 .register_component_with_descriptor(descriptor)
1856 }
1857
1858 fn insert_resource_if_not_exists_with_caller<R: Resource>(
1859 &mut self,
1860 func: impl FnOnce(&mut World) -> R,
1861 caller: MaybeLocation,
1862 ) -> (ComponentId, EntityWorldMut<'_>) {
1863 let resource_id = self.register_component::<R>();
1864
1865 if let Some(entity) = self.resource_entities.get(resource_id) {
1866 let entity_ref = self.get_entity(entity).expect("ResourceCache is in sync");
1867 if !entity_ref.contains_id(resource_id) {
1868 let resource = func(self);
1869 move_as_ptr!(resource);
1870 self.entity_mut(entity).insert_with_caller(
1871 resource,
1872 InsertMode::Replace,
1873 caller,
1874 RelationshipHookMode::Run,
1875 );
1876 }
1877 return (resource_id, self.entity_mut(entity));
1878 }
1879
1880 let resource = func(self);
1881 move_as_ptr!(resource);
1882 let entity_mut = self.spawn_with_caller(resource, caller); // ResourceCache is updated automatically
1883 (resource_id, entity_mut)
1884 }
1885
1886 /// Initializes a new resource and returns the [`ComponentId`] created for it.
1887 ///
1888 /// If the resource already exists, nothing happens.
1889 ///
1890 /// The value given by the [`FromWorld::from_world`] method will be used.
1891 /// Note that any resource with the [`Default`] trait automatically implements [`FromWorld`],
1892 /// and those default values will be here instead.
1893 #[inline]
1894 #[track_caller]
1895 pub fn init_resource<R: Resource + FromWorld>(&mut self) -> ComponentId {
1896 let caller = MaybeLocation::caller();
1897 self.insert_resource_if_not_exists_with_caller(R::from_world, caller)
1898 .0
1899 }
1900
1901 /// Inserts a new resource with the given `value`.
1902 ///
1903 /// Resources are "unique" data of a given type.
1904 /// If you insert a resource of a type that already exists,
1905 /// you will overwrite any existing data.
1906 #[inline]
1907 #[track_caller]
1908 pub fn insert_resource<R: Resource>(&mut self, value: R) {
1909 self.insert_resource_with_caller(value, MaybeLocation::caller());
1910 }
1911
1912 /// Split into a new function so we can pass the calling location into the function when using
1913 /// as a command.
1914 #[inline]
1915 pub(crate) fn insert_resource_with_caller<R: Resource>(
1916 &mut self,
1917 value: R,
1918 caller: MaybeLocation,
1919 ) {
1920 let component_id = self.components_registrator().register_component::<R>();
1921 OwningPtr::make(value, |ptr| {
1922 // SAFETY: component_id was just initialized and corresponds to resource of type R.
1923 unsafe {
1924 self.insert_resource_by_id(component_id, ptr, caller);
1925 }
1926 });
1927 }
1928
1929 /// Initializes a new non-send resource and returns the [`ComponentId`] created for it.
1930 #[deprecated(since = "0.19.0", note = "use World::init_non_send")]
1931 pub fn init_non_send_resource<R: 'static + FromWorld>(&mut self) -> ComponentId {
1932 self.init_non_send::<R>()
1933 }
1934
1935 /// Initializes new non-send data and returns the [`ComponentId`] created for it.
1936 ///
1937 /// If the data already exists, nothing happens.
1938 ///
1939 /// The value given by the [`FromWorld::from_world`] method will be used.
1940 /// Note that any non-send data with the `Default` trait automatically implements
1941 /// `FromWorld`, and those default values will be here instead.
1942 ///
1943 /// # Panics
1944 ///
1945 /// Panics if called from a thread other than the main thread.
1946 #[inline]
1947 #[track_caller]
1948 pub fn init_non_send<R: 'static + FromWorld>(&mut self) -> ComponentId {
1949 let caller = MaybeLocation::caller();
1950 let component_id = self.components_registrator().register_non_send::<R>();
1951 if self
1952 .storages
1953 .non_sends
1954 .get(component_id)
1955 .is_none_or(|data| !data.is_present())
1956 {
1957 let value = R::from_world(self);
1958 OwningPtr::make(value, |ptr| {
1959 // SAFETY: component_id was just initialized and corresponds to resource of type R.
1960 unsafe {
1961 self.insert_non_send_by_id(component_id, ptr, caller);
1962 }
1963 });
1964 }
1965 component_id
1966 }
1967
1968 /// Inserts a new non-send resource with the given `value`.
1969 #[deprecated(since = "0.19.0", note = "use World::insert_non_send")]
1970 pub fn insert_non_send_resource<R: 'static>(&mut self, value: R) {
1971 self.insert_non_send(value);
1972 }
1973
1974 /// Inserts new non-send data with the given `value`.
1975 ///
1976 /// `NonSend` data cannot be sent across threads,
1977 /// and do not need the `Send + Sync` bounds.
1978 /// Systems with `NonSend` resources are always scheduled on the main thread.
1979 ///
1980 /// # Panics
1981 /// If a value is already present, this function will panic if called
1982 /// from a different thread than where the original value was inserted from.
1983 #[inline]
1984 #[track_caller]
1985 pub fn insert_non_send<R: 'static>(&mut self, value: R) {
1986 let caller = MaybeLocation::caller();
1987 let component_id = self.components_registrator().register_non_send::<R>();
1988 OwningPtr::make(value, |ptr| {
1989 // SAFETY: component_id was just initialized and corresponds to the data of type R.
1990 unsafe {
1991 self.insert_non_send_by_id(component_id, ptr, caller);
1992 }
1993 });
1994 }
1995
1996 /// Removes the resource of a given type and returns it, if it exists. Otherwise returns `None`.
1997 #[inline]
1998 pub fn remove_resource<R: Resource>(&mut self) -> Option<R> {
1999 let resource_id = self.component_id::<R>()?;
2000 let entity = self.resource_entities.get(resource_id)?;
2001 let value = self
2002 .get_entity_mut(entity)
2003 .expect("ResourceCache is in sync")
2004 .take::<R>()?;
2005 Some(value)
2006 }
2007
2008 /// Removes a `!Send` resource from the world and returns it, if present.
2009 #[deprecated(since = "0.19.0", note = "use World::remove_non_send")]
2010 pub fn remove_non_send_resource<R: 'static>(&mut self) -> Option<R> {
2011 self.remove_non_send::<R>()
2012 }
2013
2014 /// Removes `!Send` data from the world and returns it, if present.
2015 ///
2016 /// `NonSend` resources cannot be sent across threads,
2017 /// and do not need the `Send + Sync` bounds.
2018 /// Systems with `NonSend` data are always scheduled on the main thread.
2019 ///
2020 /// Returns `None` if a value was not previously present.
2021 ///
2022 /// # Panics
2023 /// If a value is present, this function will panic if called from a different
2024 /// thread than where the value was inserted from.
2025 #[inline]
2026 pub fn remove_non_send<R: 'static>(&mut self) -> Option<R> {
2027 let component_id = self.components.get_valid_id(TypeId::of::<R>())?;
2028 let (ptr, _, _) = self.storages.non_sends.get_mut(component_id)?.remove()?;
2029 // SAFETY: `component_id` was gotten via looking up the `R` type
2030 unsafe { Some(ptr.read::<R>()) }
2031 }
2032
2033 /// Returns `true` if a resource of type `R` exists. Otherwise returns `false`.
2034 #[inline]
2035 pub fn contains_resource<R: Resource>(&self) -> bool {
2036 self.components
2037 .get_valid_id(TypeId::of::<R>())
2038 .is_some_and(|component_id| self.contains_resource_by_id(component_id))
2039 }
2040
2041 /// Returns `true` if a resource with provided `component_id` exists. Otherwise returns `false`.
2042 #[inline]
2043 pub fn contains_resource_by_id(&self, component_id: ComponentId) -> bool {
2044 if let Some(entity) = self.resource_entities.get(component_id)
2045 && let Ok(entity_ref) = self.get_entity(entity)
2046 {
2047 return entity_ref.contains_id(component_id);
2048 }
2049 false
2050 }
2051
2052 /// Returns `true` if `!Send` data of type `R` exists. Otherwise returns `false`.
2053 #[inline]
2054 pub fn contains_non_send<R: 'static>(&self) -> bool {
2055 self.components
2056 .get_valid_id(TypeId::of::<R>())
2057 .and_then(|component_id| self.storages.non_sends.get(component_id))
2058 .is_some_and(NonSendData::is_present)
2059 }
2060
2061 /// Returns `true` if `!Send` data with `component_id` exists. Otherwise returns `false`.
2062 #[inline]
2063 pub fn contains_non_send_by_id(&self, component_id: ComponentId) -> bool {
2064 self.storages
2065 .non_sends
2066 .get(component_id)
2067 .is_some_and(NonSendData::is_present)
2068 }
2069
2070 /// Returns `true` if a resource of type `R` exists and was added since the world's
2071 /// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
2072 ///
2073 /// This means that:
2074 /// - When called from an exclusive system, this will check for additions since the system last ran.
2075 /// - When called elsewhere, this will check for additions since the last time that [`World::clear_trackers`]
2076 /// was called.
2077 pub fn is_resource_added<R: Resource>(&self) -> bool {
2078 self.components
2079 .get_valid_id(TypeId::of::<R>())
2080 .is_some_and(|component_id| self.is_resource_added_by_id(component_id))
2081 }
2082
2083 /// Returns `true` if a resource with id `component_id` exists and was added since the world's
2084 /// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
2085 ///
2086 /// This means that:
2087 /// - When called from an exclusive system, this will check for additions since the system last ran.
2088 /// - When called elsewhere, this will check for additions since the last time that [`World::clear_trackers`]
2089 /// was called.
2090 pub fn is_resource_added_by_id(&self, component_id: ComponentId) -> bool {
2091 self.get_resource_change_ticks_by_id(component_id)
2092 .is_some_and(|ticks| ticks.is_added(self.last_change_tick(), self.read_change_tick()))
2093 }
2094
2095 /// Returns `true` if a resource of type `R` exists and was modified since the world's
2096 /// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
2097 ///
2098 /// This means that:
2099 /// - When called from an exclusive system, this will check for changes since the system last ran.
2100 /// - When called elsewhere, this will check for changes since the last time that [`World::clear_trackers`]
2101 /// was called.
2102 pub fn is_resource_changed<R: Resource>(&self) -> bool {
2103 self.components
2104 .get_valid_id(TypeId::of::<R>())
2105 .is_some_and(|component_id| self.is_resource_changed_by_id(component_id))
2106 }
2107
2108 /// Returns `true` if a resource with id `component_id` exists and was modified since the world's
2109 /// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
2110 ///
2111 /// This means that:
2112 /// - When called from an exclusive system, this will check for changes since the system last ran.
2113 /// - When called elsewhere, this will check for changes since the last time that [`World::clear_trackers`]
2114 /// was called.
2115 pub fn is_resource_changed_by_id(&self, component_id: ComponentId) -> bool {
2116 self.get_resource_change_ticks_by_id(component_id)
2117 .is_some_and(|ticks| ticks.is_changed(self.last_change_tick(), self.read_change_tick()))
2118 }
2119
2120 /// Retrieves the change ticks for the given resource.
2121 pub fn get_resource_change_ticks<R: Resource>(&self) -> Option<ComponentTicks> {
2122 self.components
2123 .get_valid_id(TypeId::of::<R>())
2124 .and_then(|component_id| self.get_resource_change_ticks_by_id(component_id))
2125 }
2126
2127 /// Retrieves the change ticks for the given [`ComponentId`].
2128 ///
2129 /// **You should prefer to use the typed API [`World::get_resource_change_ticks`] where possible.**
2130 pub fn get_resource_change_ticks_by_id(
2131 &self,
2132 component_id: ComponentId,
2133 ) -> Option<ComponentTicks> {
2134 let entity = self.resource_entities.get(component_id)?;
2135 let entity_ref = self.get_entity(entity).ok()?;
2136 entity_ref.get_change_ticks_by_id(component_id)
2137 }
2138
2139 /// Gets a reference to the resource of the given type
2140 ///
2141 /// # Panics
2142 ///
2143 /// Panics if the resource does not exist.
2144 /// Use [`get_resource`](World::get_resource) instead if you want to handle this case.
2145 ///
2146 /// If you want to instead insert a value if the resource does not exist,
2147 /// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
2148 #[inline]
2149 #[track_caller]
2150 pub fn resource<R: Resource>(&self) -> &R {
2151 match self.get_resource() {
2152 Some(x) => x,
2153 None => panic!(
2154 "Requested resource {} does not exist in the `World`.
2155 Did you forget to add it using `app.insert_resource` / `app.init_resource`?
2156 Resources are also implicitly added via `app.add_message`,
2157 and can be added by plugins.",
2158 DebugName::type_name::<R>()
2159 ),
2160 }
2161 }
2162
2163 /// Gets a reference to the resource of the given type
2164 ///
2165 /// # Panics
2166 ///
2167 /// Panics if the resource does not exist.
2168 /// Use [`get_resource_ref`](World::get_resource_ref) instead if you want to handle this case.
2169 ///
2170 /// If you want to instead insert a value if the resource does not exist,
2171 /// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
2172 #[inline]
2173 #[track_caller]
2174 pub fn resource_ref<R: Resource>(&self) -> Ref<'_, R> {
2175 match self.get_resource_ref() {
2176 Some(x) => x,
2177 None => panic!(
2178 "Requested resource {} does not exist in the `World`.
2179 Did you forget to add it using `app.insert_resource` / `app.init_resource`?
2180 Resources are also implicitly added via `app.add_message`,
2181 and can be added by plugins.",
2182 DebugName::type_name::<R>()
2183 ),
2184 }
2185 }
2186
2187 /// Gets a mutable reference to the resource of the given type
2188 ///
2189 /// # Panics
2190 ///
2191 /// Panics if the resource does not exist.
2192 /// Use [`get_resource_mut`](World::get_resource_mut) instead if you want to handle this case.
2193 ///
2194 /// If you want to instead insert a value if the resource does not exist,
2195 /// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
2196 #[inline]
2197 #[track_caller]
2198 pub fn resource_mut<R: Resource<Mutability = Mutable>>(&mut self) -> Mut<'_, R> {
2199 match self.get_resource_mut() {
2200 Some(x) => x,
2201 None => panic!(
2202 "Requested resource {} does not exist in the `World`.
2203 Did you forget to add it using `app.insert_resource` / `app.init_resource`?
2204 Resources are also implicitly added via `app.add_message`,
2205 and can be added by plugins.",
2206 DebugName::type_name::<R>()
2207 ),
2208 }
2209 }
2210
2211 /// Gets a reference to the resource of the given type if it exists
2212 #[inline]
2213 pub fn get_resource<R: Resource>(&self) -> Option<&R> {
2214 // SAFETY:
2215 // - `as_unsafe_world_cell_readonly` gives permission to access everything immutably
2216 // - `&self` ensures nothing in world is borrowed mutably
2217 unsafe { self.as_unsafe_world_cell_readonly().get_resource() }
2218 }
2219
2220 /// Gets a reference including change detection to the resource of the given type if it exists.
2221 #[inline]
2222 pub fn get_resource_ref<R: Resource>(&self) -> Option<Ref<'_, R>> {
2223 // SAFETY:
2224 // - `as_unsafe_world_cell_readonly` gives permission to access everything immutably
2225 // - `&self` ensures nothing in world is borrowed mutably
2226 unsafe { self.as_unsafe_world_cell_readonly().get_resource_ref() }
2227 }
2228
2229 /// Gets a mutable reference to the resource of the given type if it exists
2230 #[inline]
2231 pub fn get_resource_mut<R: Resource<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, R>> {
2232 // SAFETY:
2233 // - `as_unsafe_world_cell` gives permission to access everything mutably
2234 // - `&mut self` ensures nothing in world is borrowed
2235 unsafe { self.as_unsafe_world_cell().get_resource_mut() }
2236 }
2237
2238 /// Gets a mutable reference to the resource of type `T` if it exists,
2239 /// otherwise inserts the resource using the result of calling `func`.
2240 ///
2241 /// # Example
2242 ///
2243 /// ```
2244 /// # use bevy_ecs::prelude::*;
2245 /// #
2246 /// #[derive(Resource)]
2247 /// struct MyResource(i32);
2248 ///
2249 /// # let mut world = World::new();
2250 /// let my_res = world.get_resource_or_insert_with(|| MyResource(10));
2251 /// assert_eq!(my_res.0, 10);
2252 /// ```
2253 #[inline]
2254 #[track_caller]
2255 pub fn get_resource_or_insert_with<R: Resource<Mutability = Mutable>>(
2256 &mut self,
2257 func: impl FnOnce() -> R,
2258 ) -> Mut<'_, R> {
2259 let caller = MaybeLocation::caller();
2260 let (resource_id, entity) =
2261 self.insert_resource_if_not_exists_with_caller(|_world: &mut World| func(), caller);
2262 let untyped = entity
2263 .into_mut_by_id(resource_id)
2264 .expect("Resource must exist");
2265 // SAFETY: resource is of type R
2266 unsafe { untyped.with_type() }
2267 }
2268
2269 /// Gets a mutable reference to the resource of type `T` if it exists,
2270 /// otherwise initializes the resource by calling its [`FromWorld`]
2271 /// implementation.
2272 ///
2273 /// # Example
2274 ///
2275 /// ```
2276 /// # use bevy_ecs::prelude::*;
2277 /// #
2278 /// #[derive(Resource)]
2279 /// struct Foo(i32);
2280 ///
2281 /// impl Default for Foo {
2282 /// fn default() -> Self {
2283 /// Self(15)
2284 /// }
2285 /// }
2286 ///
2287 /// #[derive(Resource)]
2288 /// struct MyResource(i32);
2289 ///
2290 /// impl FromWorld for MyResource {
2291 /// fn from_world(world: &mut World) -> Self {
2292 /// let foo = world.get_resource_or_init::<Foo>();
2293 /// Self(foo.0 * 2)
2294 /// }
2295 /// }
2296 ///
2297 /// # let mut world = World::new();
2298 /// let my_res = world.get_resource_or_init::<MyResource>();
2299 /// assert_eq!(my_res.0, 30);
2300 /// ```
2301 #[track_caller]
2302 pub fn get_resource_or_init<R: Resource<Mutability = Mutable> + FromWorld>(
2303 &mut self,
2304 ) -> Mut<'_, R> {
2305 let caller = MaybeLocation::caller();
2306 let (resource_id, entity) =
2307 self.insert_resource_if_not_exists_with_caller(R::from_world, caller);
2308 let untyped = entity
2309 .into_mut_by_id(resource_id)
2310 .expect("Resource must exist");
2311 // SAFETY: resource is of type R
2312 unsafe { untyped.with_type() }
2313 }
2314
2315 /// Gets an immutable reference to a non-send resource of the given type, if it exists.
2316 #[deprecated(since = "0.19.0", note = "use World::non_send")]
2317 pub fn non_send_resource<R: 'static>(&self) -> &R {
2318 self.non_send::<R>()
2319 }
2320
2321 /// Gets an immutable reference to the non-send data of the given type, if it exists.
2322 ///
2323 /// # Panics
2324 ///
2325 /// Panics if the data does not exist.
2326 /// Use [`get_non_send`](World::get_non_send) instead if you want to handle this case.
2327 ///
2328 /// This function will panic if it isn't called from the same thread that the resource was inserted from.
2329 #[inline]
2330 #[track_caller]
2331 pub fn non_send<R: 'static>(&self) -> &R {
2332 match self.get_non_send() {
2333 Some(x) => x,
2334 None => panic!(
2335 "Requested non-send resource {} does not exist in the `World`.
2336 Did you forget to add it using `app.insert_non_send` / `app.init_non_send`?
2337 Non-send resources can also be added by plugins.",
2338 DebugName::type_name::<R>()
2339 ),
2340 }
2341 }
2342
2343 /// Gets a mutable reference to a non-send resource of the given type, if it exists.
2344 #[deprecated(since = "0.19.0", note = "use World::non_send_mut")]
2345 pub fn non_send_resource_mut<R: 'static>(&mut self) -> Mut<'_, R> {
2346 self.non_send_mut::<R>()
2347 }
2348
2349 /// Gets a mutable reference to the non-send data of the given type, if it exists.
2350 ///
2351 /// # Panics
2352 ///
2353 /// Panics if the data does not exist.
2354 /// Use [`get_non_send_mut`](World::get_non_send_mut) instead if you want to handle this case.
2355 ///
2356 /// This function will panic if it isn't called from the same thread that the resource was inserted from.
2357 #[inline]
2358 #[track_caller]
2359 pub fn non_send_mut<R: 'static>(&mut self) -> Mut<'_, R> {
2360 match self.get_non_send_mut() {
2361 Some(x) => x,
2362 None => panic!(
2363 "Requested non-send resource {} does not exist in the `World`.
2364 Did you forget to add it using `app.insert_non_send` / `app.init_non_send`?
2365 Non-send resources can also be added by plugins.",
2366 DebugName::type_name::<R>()
2367 ),
2368 }
2369 }
2370
2371 /// Gets a reference to a non-send resource of the given type, if it exists.
2372 /// Otherwise returns `None`.
2373 #[deprecated(since = "0.19.0", note = "use World::get_non_send")]
2374 pub fn get_non_send_resource<R: 'static>(&self) -> Option<&R> {
2375 self.get_non_send::<R>()
2376 }
2377
2378 /// Gets a reference to the non-send data of the given type, if it exists.
2379 /// Otherwise returns `None`.
2380 ///
2381 /// # Panics
2382 /// This function will panic if it isn't called from the same thread that the resource was inserted from.
2383 #[inline]
2384 pub fn get_non_send<R: 'static>(&self) -> Option<&R> {
2385 // SAFETY:
2386 // - `as_unsafe_world_cell_readonly` gives permission to access the entire world immutably
2387 // - `&self` ensures that there are no mutable borrows of world data
2388 unsafe { self.as_unsafe_world_cell_readonly().get_non_send() }
2389 }
2390
2391 /// Gets a mutable reference to a non-send resource of the given type, if it exists.
2392 /// Otherwise returns `None`.
2393 #[deprecated(since = "0.19.0", note = "use World::get_non_send_mut")]
2394 pub fn get_non_send_resource_mut<R: 'static>(&mut self) -> Option<Mut<'_, R>> {
2395 self.get_non_send_mut::<R>()
2396 }
2397
2398 /// Gets a mutable reference to the non-send data of the given type, if it exists.
2399 /// Otherwise returns `None`.
2400 ///
2401 /// # Panics
2402 /// This function will panic if it isn't called from the same thread that the resource was inserted from.
2403 #[inline]
2404 pub fn get_non_send_mut<R: 'static>(&mut self) -> Option<Mut<'_, R>> {
2405 // SAFETY:
2406 // - `as_unsafe_world_cell` gives permission to access the entire world mutably
2407 // - `&mut self` ensures that there are no borrows of world data
2408 unsafe { self.as_unsafe_world_cell().get_non_send_mut() }
2409 }
2410
2411 /// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2412 /// adds the `Bundle` of components to each `Entity`.
2413 /// This is faster than doing equivalent operations one-by-one.
2414 ///
2415 /// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2416 /// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2417 ///
2418 /// This will overwrite any previous values of components shared by the `Bundle`.
2419 /// See [`World::insert_batch_if_new`] to keep the old values instead.
2420 ///
2421 /// # Panics
2422 ///
2423 /// This function will panic if any of the associated entities do not exist.
2424 ///
2425 /// For the fallible version, see [`World::try_insert_batch`].
2426 #[track_caller]
2427 pub fn insert_batch<I, B>(&mut self, batch: I)
2428 where
2429 I: IntoIterator,
2430 I::IntoIter: Iterator<Item = (Entity, B)>,
2431 B: Bundle<Effect: NoBundleEffect>,
2432 {
2433 self.insert_batch_with_caller(batch, InsertMode::Replace, MaybeLocation::caller());
2434 }
2435
2436 /// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2437 /// adds the `Bundle` of components to each `Entity` without overwriting.
2438 /// This is faster than doing equivalent operations one-by-one.
2439 ///
2440 /// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2441 /// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2442 ///
2443 /// This is the same as [`World::insert_batch`], but in case of duplicate
2444 /// components it will leave the old values instead of replacing them with new ones.
2445 ///
2446 /// # Panics
2447 ///
2448 /// This function will panic if any of the associated entities do not exist.
2449 ///
2450 /// For the fallible version, see [`World::try_insert_batch_if_new`].
2451 #[track_caller]
2452 pub fn insert_batch_if_new<I, B>(&mut self, batch: I)
2453 where
2454 I: IntoIterator,
2455 I::IntoIter: Iterator<Item = (Entity, B)>,
2456 B: Bundle<Effect: NoBundleEffect>,
2457 {
2458 self.insert_batch_with_caller(batch, InsertMode::Keep, MaybeLocation::caller());
2459 }
2460
2461 /// Split into a new function so we can differentiate the calling location.
2462 ///
2463 /// This can be called by:
2464 /// - [`World::insert_batch`]
2465 /// - [`World::insert_batch_if_new`]
2466 #[inline]
2467 pub(crate) fn insert_batch_with_caller<I, B>(
2468 &mut self,
2469 batch: I,
2470 insert_mode: InsertMode,
2471 caller: MaybeLocation,
2472 ) where
2473 I: IntoIterator,
2474 I::IntoIter: Iterator<Item = (Entity, B)>,
2475 B: Bundle<Effect: NoBundleEffect>,
2476 {
2477 struct InserterArchetypeCache<'w> {
2478 inserter: BundleInserter<'w>,
2479 archetype_id: ArchetypeId,
2480 }
2481
2482 let change_tick = self.change_tick();
2483 let bundle_id = self.register_bundle_info::<B>();
2484
2485 let mut batch_iter = batch.into_iter();
2486
2487 if let Some((first_entity, first_bundle)) = batch_iter.next() {
2488 match self.entities().get_spawned(first_entity) {
2489 Err(err) => {
2490 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>());
2491 }
2492 Ok(first_location) => {
2493 let mut cache = InserterArchetypeCache {
2494 // SAFETY: we initialized this bundle_id in `register_info`
2495 inserter: unsafe {
2496 BundleInserter::new_with_id(
2497 self,
2498 first_location.archetype_id,
2499 bundle_id,
2500 change_tick,
2501 )
2502 },
2503 archetype_id: first_location.archetype_id,
2504 };
2505 move_as_ptr!(first_bundle);
2506 // SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
2507 unsafe {
2508 cache.inserter.insert(
2509 first_entity,
2510 first_location,
2511 first_bundle,
2512 insert_mode,
2513 caller,
2514 RelationshipHookMode::Run,
2515 )
2516 };
2517
2518 for (entity, bundle) in batch_iter {
2519 match cache.inserter.entities().get_spawned(entity) {
2520 Ok(location) => {
2521 if location.archetype_id != cache.archetype_id {
2522 cache = InserterArchetypeCache {
2523 // SAFETY: we initialized this bundle_id in `register_info`
2524 inserter: unsafe {
2525 BundleInserter::new_with_id(
2526 self,
2527 location.archetype_id,
2528 bundle_id,
2529 change_tick,
2530 )
2531 },
2532 archetype_id: location.archetype_id,
2533 }
2534 }
2535 move_as_ptr!(bundle);
2536 // SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
2537 unsafe {
2538 cache.inserter.insert(
2539 entity,
2540 location,
2541 bundle,
2542 insert_mode,
2543 caller,
2544 RelationshipHookMode::Run,
2545 )
2546 };
2547 }
2548 Err(err) => {
2549 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>());
2550 }
2551 }
2552 }
2553 }
2554 }
2555 }
2556 }
2557
2558 /// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2559 /// adds the `Bundle` of components to each `Entity`.
2560 /// This is faster than doing equivalent operations one-by-one.
2561 ///
2562 /// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2563 /// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2564 ///
2565 /// This will overwrite any previous values of components shared by the `Bundle`.
2566 /// See [`World::try_insert_batch_if_new`] to keep the old values instead.
2567 ///
2568 /// Returns a [`TryInsertBatchError`] if any of the provided entities do not exist.
2569 ///
2570 /// For the panicking version, see [`World::insert_batch`].
2571 #[track_caller]
2572 pub fn try_insert_batch<I, B>(&mut self, batch: I) -> Result<(), TryInsertBatchError>
2573 where
2574 I: IntoIterator,
2575 I::IntoIter: Iterator<Item = (Entity, B)>,
2576 B: Bundle<Effect: NoBundleEffect>,
2577 {
2578 self.try_insert_batch_with_caller(batch, InsertMode::Replace, MaybeLocation::caller())
2579 }
2580 /// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2581 /// adds the `Bundle` of components to each `Entity` without overwriting.
2582 /// This is faster than doing equivalent operations one-by-one.
2583 ///
2584 /// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2585 /// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2586 ///
2587 /// This is the same as [`World::try_insert_batch`], but in case of duplicate
2588 /// components it will leave the old values instead of replacing them with new ones.
2589 ///
2590 /// Returns a [`TryInsertBatchError`] if any of the provided entities do not exist.
2591 ///
2592 /// For the panicking version, see [`World::insert_batch_if_new`].
2593 #[track_caller]
2594 pub fn try_insert_batch_if_new<I, B>(&mut self, batch: I) -> Result<(), TryInsertBatchError>
2595 where
2596 I: IntoIterator,
2597 I::IntoIter: Iterator<Item = (Entity, B)>,
2598 B: Bundle<Effect: NoBundleEffect>,
2599 {
2600 self.try_insert_batch_with_caller(batch, InsertMode::Keep, MaybeLocation::caller())
2601 }
2602
2603 /// Split into a new function so we can differentiate the calling location.
2604 ///
2605 /// This can be called by:
2606 /// - [`World::try_insert_batch`]
2607 /// - [`World::try_insert_batch_if_new`]
2608 /// - [`Commands::insert_batch`]
2609 /// - [`Commands::insert_batch_if_new`]
2610 /// - [`Commands::try_insert_batch`]
2611 /// - [`Commands::try_insert_batch_if_new`]
2612 #[inline]
2613 pub(crate) fn try_insert_batch_with_caller<I, B>(
2614 &mut self,
2615 batch: I,
2616 insert_mode: InsertMode,
2617 caller: MaybeLocation,
2618 ) -> Result<(), TryInsertBatchError>
2619 where
2620 I: IntoIterator,
2621 I::IntoIter: Iterator<Item = (Entity, B)>,
2622 B: Bundle<Effect: NoBundleEffect>,
2623 {
2624 struct InserterArchetypeCache<'w> {
2625 inserter: BundleInserter<'w>,
2626 archetype_id: ArchetypeId,
2627 }
2628
2629 let change_tick = self.change_tick();
2630 let bundle_id = self.register_bundle_info::<B>();
2631
2632 let mut invalid_entities = Vec::<Entity>::new();
2633 let mut batch_iter = batch.into_iter();
2634
2635 // We need to find the first valid entity so we can initialize the bundle inserter.
2636 // This differs from `insert_batch_with_caller` because that method can just panic
2637 // if the first entity is invalid, whereas this method needs to keep going.
2638 let cache = loop {
2639 if let Some((first_entity, first_bundle)) = batch_iter.next() {
2640 if let Ok(first_location) = self.entities().get_spawned(first_entity) {
2641 let mut cache = InserterArchetypeCache {
2642 // SAFETY: we initialized this bundle_id in `register_bundle_info`
2643 inserter: unsafe {
2644 BundleInserter::new_with_id(
2645 self,
2646 first_location.archetype_id,
2647 bundle_id,
2648 change_tick,
2649 )
2650 },
2651 archetype_id: first_location.archetype_id,
2652 };
2653
2654 move_as_ptr!(first_bundle);
2655 // SAFETY:
2656 // - `entity` is valid, `location` matches entity, bundle matches inserter
2657 // - `apply_effect` is never called on this bundle.
2658 // - `first_bundle` is not be accessed or dropped after this.
2659 unsafe {
2660 cache.inserter.insert(
2661 first_entity,
2662 first_location,
2663 first_bundle,
2664 insert_mode,
2665 caller,
2666 RelationshipHookMode::Run,
2667 )
2668 };
2669 break Some(cache);
2670 }
2671 invalid_entities.push(first_entity);
2672 } else {
2673 // We reached the end of the entities the caller provided and none were valid.
2674 break None;
2675 }
2676 };
2677
2678 if let Some(mut cache) = cache {
2679 for (entity, bundle) in batch_iter {
2680 if let Ok(location) = cache.inserter.entities().get_spawned(entity) {
2681 if location.archetype_id != cache.archetype_id {
2682 cache = InserterArchetypeCache {
2683 // SAFETY: we initialized this bundle_id in `register_info`
2684 inserter: unsafe {
2685 BundleInserter::new_with_id(
2686 self,
2687 location.archetype_id,
2688 bundle_id,
2689 change_tick,
2690 )
2691 },
2692 archetype_id: location.archetype_id,
2693 }
2694 }
2695
2696 move_as_ptr!(bundle);
2697 // SAFETY:
2698 // - `entity` is valid, `location` matches entity, bundle matches inserter
2699 // - `apply_effect` is never called on this bundle.
2700 // - `bundle` is not be accessed or dropped after this.
2701 unsafe {
2702 cache.inserter.insert(
2703 entity,
2704 location,
2705 bundle,
2706 insert_mode,
2707 caller,
2708 RelationshipHookMode::Run,
2709 )
2710 };
2711 } else {
2712 invalid_entities.push(entity);
2713 }
2714 }
2715 }
2716
2717 if invalid_entities.is_empty() {
2718 Ok(())
2719 } else {
2720 Err(TryInsertBatchError {
2721 bundle_type: DebugName::type_name::<B>(),
2722 entities: invalid_entities,
2723 })
2724 }
2725 }
2726
2727 /// Temporarily removes the requested resource from this [`World`], runs custom user code,
2728 /// then re-adds the resource before returning.
2729 ///
2730 /// This enables safe simultaneous mutable access to both a resource and the rest of the [`World`].
2731 /// For more complex access patterns, consider using [`SystemState`](crate::system::SystemState).
2732 ///
2733 /// # Panics
2734 ///
2735 /// Panics if the resource does not exist.
2736 /// Use [`try_resource_scope`](Self::try_resource_scope) instead if you want to handle this case.
2737 ///
2738 /// # Example
2739 /// ```
2740 /// use bevy_ecs::prelude::*;
2741 /// #[derive(Resource)]
2742 /// struct A(u32);
2743 /// #[derive(Component)]
2744 /// struct B(u32);
2745 /// let mut world = World::new();
2746 /// world.insert_resource(A(1));
2747 /// let entity = world.spawn(B(1)).id();
2748 ///
2749 /// world.resource_scope(|world, mut a: Mut<A>| {
2750 /// let b = world.get_mut::<B>(entity).unwrap();
2751 /// a.0 += b.0;
2752 /// });
2753 /// assert_eq!(world.get_resource::<A>().unwrap().0, 2);
2754 /// ```
2755 ///
2756 /// # Note
2757 ///
2758 /// If the world's resource metadata is cleared within the scope, such as by calling
2759 /// [`World::clear_resources`] or [`World::clear_all`], the resource will *not* be re-inserted
2760 /// at the end of the scope.
2761 #[track_caller]
2762 pub fn resource_scope<R: Resource, U>(&mut self, f: impl FnOnce(&mut World, Mut<R>) -> U) -> U {
2763 self.try_resource_scope(f)
2764 .unwrap_or_else(|| panic!("resource does not exist: {}", DebugName::type_name::<R>()))
2765 }
2766
2767 /// Temporarily removes the requested resource from this [`World`] if it exists, runs custom user code,
2768 /// then re-adds the resource before returning. Returns `None` if the resource does not exist in this [`World`].
2769 ///
2770 /// This enables safe simultaneous mutable access to both a resource and the rest of the [`World`].
2771 /// For more complex access patterns, consider using [`SystemState`](crate::system::SystemState).
2772 ///
2773 /// See also [`resource_scope`](Self::resource_scope).
2774 ///
2775 /// # Note
2776 ///
2777 /// If the world's resource metadata is cleared within the scope, such as by calling
2778 /// [`World::clear_resources`] or [`World::clear_all`], the resource will *not* be re-inserted
2779 /// at the end of the scope.
2780 pub fn try_resource_scope<R: Resource, U>(
2781 &mut self,
2782 f: impl FnOnce(&mut World, Mut<R>) -> U,
2783 ) -> Option<U> {
2784 let last_change_tick = self.last_change_tick();
2785 let change_tick = self.change_tick();
2786
2787 let component_id = self.components.valid_component_id::<R>()?;
2788 let entity = self.resource_entities.get(component_id)?;
2789 let mut entity_mut = self.get_entity_mut(entity).ok()?;
2790
2791 let mut ticks = entity_mut.get_change_ticks::<R>()?;
2792 let changed_by = entity_mut.get_changed_by::<R>()?;
2793 let value = entity_mut.take::<R>()?;
2794
2795 // type used to manage reinserting the resource at the end of the scope. use of a drop impl means that
2796 // the resource is inserted even if the user-provided closure unwinds.
2797 // this facilitates localized panic recovery and makes app shutdown in response to a panic more graceful
2798 // by avoiding knock-on errors.
2799 struct ReinsertGuard<'a, R: Resource> {
2800 world: &'a mut World,
2801 entity: Entity,
2802 component_id: ComponentId,
2803 value: ManuallyDrop<R>,
2804 caller: MaybeLocation,
2805 }
2806 impl<R: Resource> Drop for ReinsertGuard<'_, R> {
2807 fn drop(&mut self) {
2808 // take ownership of the value first so it'll get dropped if we return early
2809 // SAFETY: drop semantics ensure that `self.value` will never be accessed again after this call
2810 let value = unsafe { ManuallyDrop::take(&mut self.value) };
2811
2812 let Ok(mut entity_mut) = self.world.get_entity_mut(self.entity) else {
2813 return;
2814 };
2815
2816 // in debug mode, raise a panic if user code re-inserted a resource of this type within the scope.
2817 // resource insertion usually indicates a logic error in user code, which is useful to catch at dev time,
2818 // however it does not inherently lead to corrupted state, so we avoid introducing an unnecessary crash
2819 // for production builds.
2820 if entity_mut.contains_id(self.component_id) {
2821 #[cfg(debug_assertions)]
2822 {
2823 // if we're already panicking, log an error instead of panicking, as double-panics result in an abort
2824 #[cfg(feature = "std")]
2825 if std::thread::panicking() {
2826 log::error!("Resource `{}` was inserted during a call to World::resource_scope, which may result in unexpected behavior.\n\
2827 In release builds, the value inserted will be overwritten at the end of the scope.",
2828 DebugName::type_name::<R>());
2829 // return early to maintain consistent behavior with non-panicking calls in debug builds
2830 return;
2831 }
2832
2833 panic!("Resource `{}` was inserted during a call to World::resource_scope, which may result in unexpected behavior.\n\
2834 In release builds, the value inserted will be overwritten at the end of the scope.",
2835 DebugName::type_name::<R>());
2836 }
2837 #[cfg(not(debug_assertions))]
2838 {
2839 #[cold]
2840 #[inline(never)]
2841 fn warn_reinsert(resource_name: &str) {
2842 warn!(
2843 "Resource `{resource_name}` was inserted during a call to World::resource_scope: the inserted value will be overwritten.",
2844 );
2845 }
2846
2847 warn_reinsert(&DebugName::type_name::<R>());
2848 }
2849 }
2850
2851 move_as_ptr!(value);
2852
2853 // See EntityWorldMut::insert_with_caller for the original code.
2854 // This is copied here to update the change ticks. This way we can ensure that the commands
2855 // ran during self.flush(), interact with the correct ticks on the resource component.
2856 {
2857 let location = entity_mut.location();
2858 // SAFETY:
2859 // - We update the entity location like in `EntityWorldMut::insert_with_caller`.
2860 let world = unsafe { entity_mut.world_mut() };
2861 let tick = world.change_tick();
2862 // SAFETY:
2863 // - `location.archetype_id` is part of a valid `EntityLocation`.
2864 let mut bundle_inserter =
2865 unsafe { BundleInserter::new::<R>(world, location.archetype_id, tick) };
2866 // SAFETY:
2867 // - `location` matches current entity and thus must currently exist in the source
2868 // archetype for this inserter and its location within the archetype.
2869 // - `T` matches the type used to create the `BundleInserter`.
2870 // - `apply_effect` is called exactly once after this function.
2871 // - The value pointed at by `bundle` is not accessed for anything other than `apply_effect`
2872 // and the caller ensures that the value is not accessed or dropped after this function
2873 // returns.
2874 let (bundle, _) = value.partial_move(|bundle| unsafe {
2875 bundle_inserter.insert(
2876 self.entity,
2877 location,
2878 bundle,
2879 InsertMode::Replace,
2880 self.caller,
2881 RelationshipHookMode::Run,
2882 )
2883 });
2884 entity_mut.update_location();
2885
2886 // SAFETY: We update the entity location afterwards.
2887 unsafe { entity_mut.world_mut() }.flush();
2888
2889 entity_mut.update_location();
2890 // SAFETY:
2891 // - This is called exactly once after the `BundleInsert::insert` call before returning to safe code.
2892 // - `bundle` points to the same `B` that `BundleInsert::insert` was called on.
2893 unsafe { R::apply_effect(bundle, &mut entity_mut) };
2894 }
2895 }
2896 }
2897
2898 let mut guard = ReinsertGuard {
2899 world: self,
2900 entity,
2901 component_id,
2902 value: ManuallyDrop::new(value),
2903 caller: changed_by,
2904 };
2905
2906 let value_mut = Mut {
2907 value: &mut *guard.value,
2908 ticks: ComponentTicksMut {
2909 added: &mut ticks.added,
2910 changed: &mut ticks.changed,
2911 changed_by: guard.caller.as_mut(),
2912 last_run: last_change_tick,
2913 this_run: change_tick,
2914 },
2915 };
2916
2917 let result = f(guard.world, value_mut);
2918
2919 Some(result)
2920 }
2921
2922 /// Writes a [`Message`].
2923 /// This method returns the [`MessageId`] of the written `message`,
2924 /// or [`None`] if the `message` could not be written.
2925 #[inline]
2926 pub fn write_message<M: Message>(&mut self, message: M) -> Option<MessageId<M>> {
2927 self.write_message_batch(core::iter::once(message))?.next()
2928 }
2929
2930 /// Writes the default value of the [`Message`] of type `M`.
2931 /// This method returns the [`MessageId`] of the written message,
2932 /// or [`None`] if the `event` could not be written.
2933 #[inline]
2934 pub fn write_message_default<M: Message + Default>(&mut self) -> Option<MessageId<M>> {
2935 self.write_message(M::default())
2936 }
2937
2938 /// Writes a batch of [`Message`]s from an iterator.
2939 /// This method returns the [IDs](`MessageId`) of the written `messages`,
2940 /// or [`None`] if the `events` could not be written.
2941 #[inline]
2942 pub fn write_message_batch<M: Message>(
2943 &mut self,
2944 messages: impl IntoIterator<Item = M>,
2945 ) -> Option<WriteBatchIds<M>> {
2946 let Some(mut events_resource) = self.get_resource_mut::<Messages<M>>() else {
2947 log::error!(
2948 "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 ",
2949 DebugName::type_name::<M>()
2950 );
2951 return None;
2952 };
2953 Some(events_resource.write_batch(messages))
2954 }
2955
2956 /// Inserts a new resource with the given `value`. Will replace the value if it already existed.
2957 ///
2958 /// **You should prefer to use the typed API [`World::insert_resource`] where possible and only
2959 /// use this in cases where the actual types are not known at compile time.**
2960 ///
2961 /// # Safety
2962 /// The value referenced by `value` must be valid for the given [`ComponentId`] of this world.
2963 #[inline]
2964 #[track_caller]
2965 pub unsafe fn insert_resource_by_id(
2966 &mut self,
2967 component_id: ComponentId,
2968 value: OwningPtr<'_>,
2969 caller: MaybeLocation,
2970 ) {
2971 // if the resource already exists, we replace it on the same entity
2972 let mut entity_mut = if let Some(entity) = self.resource_entities.get(component_id) {
2973 self.get_entity_mut(entity)
2974 .expect("ResourceCache is in sync")
2975 } else {
2976 self.spawn_empty()
2977 };
2978 entity_mut.insert_by_id_with_caller(
2979 component_id,
2980 value,
2981 InsertMode::Replace,
2982 caller,
2983 RelationshipHookMode::Run,
2984 );
2985 }
2986
2987 /// Inserts new `!Send` data with the given `value`. Will replace the value if it already
2988 /// existed.
2989 ///
2990 /// **You should prefer to use the typed API [`World::insert_non_send`] where possible and only
2991 /// use this in cases where the actual types are not known at compile time.**
2992 ///
2993 /// # Panics
2994 /// If a value is already present, this function will panic if not called from the same
2995 /// thread that the original value was inserted from.
2996 ///
2997 /// # Safety
2998 /// The value referenced by `value` must be valid for the given [`ComponentId`] of this world.
2999 #[inline]
3000 #[track_caller]
3001 pub unsafe fn insert_non_send_by_id(
3002 &mut self,
3003 component_id: ComponentId,
3004 value: OwningPtr<'_>,
3005 caller: MaybeLocation,
3006 ) {
3007 let change_tick = self.change_tick();
3008
3009 let resource = self.initialize_non_send_internal(component_id);
3010 // SAFETY: `value` is valid for `component_id`, ensured by caller
3011 unsafe {
3012 resource.insert(value, change_tick, caller);
3013 }
3014 }
3015
3016 /// # Panics
3017 /// Panics if `component_id` is not registered in this world
3018 #[inline]
3019 pub(crate) fn initialize_non_send_internal(
3020 &mut self,
3021 component_id: ComponentId,
3022 ) -> &mut NonSendData {
3023 self.flush_components();
3024 self.storages
3025 .non_sends
3026 .initialize_with(component_id, &self.components)
3027 }
3028
3029 /// Applies any commands in the world's internal [`CommandQueue`].
3030 /// This does not apply commands from any systems, only those stored in the world.
3031 ///
3032 /// # Panics
3033 /// This will panic if any of the queued commands are [`spawn`](Commands::spawn).
3034 /// If this is possible, you should instead use [`flush`](Self::flush).
3035 pub(crate) fn flush_commands(&mut self) {
3036 // SAFETY: `self.command_queue` is only de-allocated in `World`'s `Drop`
3037 if !unsafe { self.command_queue.is_empty() } {
3038 // SAFETY: `self.command_queue` is only de-allocated in `World`'s `Drop`
3039 unsafe {
3040 self.command_queue
3041 .clone()
3042 .apply_or_drop_queued(Some(self.into()));
3043 };
3044 }
3045 }
3046
3047 /// Applies any queued component registration.
3048 /// For spawning vanilla rust component types and resources, this is not strictly necessary.
3049 /// However, flushing components can make information available more quickly, and can have performance benefits.
3050 /// Additionally, for components and resources registered dynamically through a raw descriptor or similar,
3051 /// this is the only way to complete their registration.
3052 pub(crate) fn flush_components(&mut self) {
3053 self.components_registrator().apply_queued_registrations();
3054 }
3055
3056 /// Flushes queued entities and commands.
3057 ///
3058 /// Queued entities will be spawned, and then commands will be applied.
3059 #[inline]
3060 #[track_caller]
3061 pub fn flush(&mut self) {
3062 self.flush_components();
3063 self.flush_commands();
3064 }
3065
3066 /// Increments the world's current change tick and returns the old value.
3067 ///
3068 /// If you need to call this method, but do not have `&mut` access to the world,
3069 /// consider using [`as_unsafe_world_cell_readonly`](Self::as_unsafe_world_cell_readonly)
3070 /// to obtain an [`UnsafeWorldCell`] and calling [`increment_change_tick`](UnsafeWorldCell::increment_change_tick) on that.
3071 /// Note that this *can* be done in safe code, despite the name of the type.
3072 #[inline]
3073 pub fn increment_change_tick(&mut self) -> Tick {
3074 let change_tick = self.change_tick.get_mut();
3075 let prev_tick = *change_tick;
3076 *change_tick = change_tick.wrapping_add(1);
3077 Tick::new(prev_tick)
3078 }
3079
3080 /// Reads the current change tick of this world.
3081 ///
3082 /// If you have exclusive (`&mut`) access to the world, consider using [`change_tick()`](Self::change_tick),
3083 /// which is more efficient since it does not require atomic synchronization.
3084 #[inline]
3085 pub fn read_change_tick(&self) -> Tick {
3086 let tick = self.change_tick.load(Ordering::Acquire);
3087 Tick::new(tick)
3088 }
3089
3090 /// Reads the current change tick of this world.
3091 ///
3092 /// This does the same thing as [`read_change_tick()`](Self::read_change_tick), only this method
3093 /// is more efficient since it does not require atomic synchronization.
3094 #[inline]
3095 pub fn change_tick(&mut self) -> Tick {
3096 let tick = *self.change_tick.get_mut();
3097 Tick::new(tick)
3098 }
3099
3100 /// When called from within an exclusive system (a [`System`] that takes `&mut World` as its first
3101 /// parameter), this method returns the [`Tick`] indicating the last time the exclusive system was run.
3102 ///
3103 /// Otherwise, this returns the `Tick` indicating the last time that [`World::clear_trackers`] was called.
3104 ///
3105 /// [`System`]: crate::system::System
3106 #[inline]
3107 pub fn last_change_tick(&self) -> Tick {
3108 self.last_change_tick
3109 }
3110
3111 /// Returns the id of the last ECS event that was fired.
3112 /// Used internally to ensure observers don't trigger multiple times for the same event.
3113 #[inline]
3114 pub(crate) fn last_trigger_id(&self) -> u32 {
3115 self.last_trigger_id
3116 }
3117
3118 /// Sets [`World::last_change_tick()`] to the specified value during a scope.
3119 /// When the scope terminates, it will return to its old value.
3120 ///
3121 /// This is useful if you need a region of code to be able to react to earlier changes made in the same system.
3122 ///
3123 /// # Examples
3124 ///
3125 /// ```
3126 /// # use bevy_ecs::prelude::*;
3127 /// // This function runs an update loop repeatedly, allowing each iteration of the loop
3128 /// // to react to changes made in the previous loop iteration.
3129 /// fn update_loop(
3130 /// world: &mut World,
3131 /// mut update_fn: impl FnMut(&mut World) -> std::ops::ControlFlow<()>,
3132 /// ) {
3133 /// let mut last_change_tick = world.last_change_tick();
3134 ///
3135 /// // Repeatedly run the update function until it requests a break.
3136 /// loop {
3137 /// let control_flow = world.last_change_tick_scope(last_change_tick, |world| {
3138 /// // Increment the change tick so we can detect changes from the previous update.
3139 /// last_change_tick = world.change_tick();
3140 /// world.increment_change_tick();
3141 ///
3142 /// // Update once.
3143 /// update_fn(world)
3144 /// });
3145 ///
3146 /// // End the loop when the closure returns `ControlFlow::Break`.
3147 /// if control_flow.is_break() {
3148 /// break;
3149 /// }
3150 /// }
3151 /// }
3152 /// #
3153 /// # #[derive(Resource)] struct Count(u32);
3154 /// # let mut world = World::new();
3155 /// # world.insert_resource(Count(0));
3156 /// # let saved_last_tick = world.last_change_tick();
3157 /// # let mut num_updates = 0;
3158 /// # update_loop(&mut world, |world| {
3159 /// # let mut c = world.resource_mut::<Count>();
3160 /// # match c.0 {
3161 /// # 0 => {
3162 /// # assert_eq!(num_updates, 0);
3163 /// # assert!(c.is_added());
3164 /// # c.0 = 1;
3165 /// # }
3166 /// # 1 => {
3167 /// # assert_eq!(num_updates, 1);
3168 /// # assert!(!c.is_added());
3169 /// # assert!(c.is_changed());
3170 /// # c.0 = 2;
3171 /// # }
3172 /// # 2 if c.is_changed() => {
3173 /// # assert_eq!(num_updates, 2);
3174 /// # assert!(!c.is_added());
3175 /// # }
3176 /// # 2 => {
3177 /// # assert_eq!(num_updates, 3);
3178 /// # assert!(!c.is_changed());
3179 /// # world.remove_resource::<Count>();
3180 /// # world.insert_resource(Count(3));
3181 /// # }
3182 /// # 3 if c.is_changed() => {
3183 /// # assert_eq!(num_updates, 4);
3184 /// # assert!(c.is_added());
3185 /// # }
3186 /// # 3 => {
3187 /// # assert_eq!(num_updates, 5);
3188 /// # assert!(!c.is_added());
3189 /// # c.0 = 4;
3190 /// # return std::ops::ControlFlow::Break(());
3191 /// # }
3192 /// # _ => unreachable!(),
3193 /// # }
3194 /// # num_updates += 1;
3195 /// # std::ops::ControlFlow::Continue(())
3196 /// # });
3197 /// # assert_eq!(num_updates, 5);
3198 /// # assert_eq!(world.resource::<Count>().0, 4);
3199 /// # assert_eq!(world.last_change_tick(), saved_last_tick);
3200 /// ```
3201 pub fn last_change_tick_scope<T>(
3202 &mut self,
3203 last_change_tick: Tick,
3204 f: impl FnOnce(&mut World) -> T,
3205 ) -> T {
3206 struct LastTickGuard<'a> {
3207 world: &'a mut World,
3208 last_tick: Tick,
3209 }
3210
3211 // By setting the change tick in the drop impl, we ensure that
3212 // the change tick gets reset even if a panic occurs during the scope.
3213 impl Drop for LastTickGuard<'_> {
3214 fn drop(&mut self) {
3215 self.world.last_change_tick = self.last_tick;
3216 }
3217 }
3218
3219 let guard = LastTickGuard {
3220 last_tick: self.last_change_tick,
3221 world: self,
3222 };
3223
3224 guard.world.last_change_tick = last_change_tick;
3225
3226 f(guard.world)
3227 }
3228
3229 /// Iterates all component change ticks and clamps any older than [`MAX_CHANGE_AGE`](crate::change_detection::MAX_CHANGE_AGE).
3230 /// This also triggers [`CheckChangeTicks`] observers and returns the same event here.
3231 ///
3232 /// Calling this method prevents [`Tick`]s overflowing and thus prevents false positives when comparing them.
3233 ///
3234 /// **Note:** Does nothing and returns `None` if the [`World`] counter has not been incremented at least [`CHECK_TICK_THRESHOLD`]
3235 /// times since the previous pass.
3236 // TODO: benchmark and optimize
3237 pub fn check_change_ticks(&mut self) -> Option<CheckChangeTicks> {
3238 let change_tick = self.change_tick();
3239 if change_tick.relative_to(self.last_check_tick).get() < CHECK_TICK_THRESHOLD {
3240 return None;
3241 }
3242
3243 let check = CheckChangeTicks(change_tick);
3244
3245 let Storages {
3246 ref mut tables,
3247 ref mut sparse_sets,
3248 ref mut non_sends,
3249 } = self.storages;
3250
3251 #[cfg(feature = "trace")]
3252 let _span = tracing::info_span!("check component ticks").entered();
3253 tables.check_change_ticks(check);
3254 sparse_sets.check_change_ticks(check);
3255 non_sends.check_change_ticks(check);
3256 self.entities.check_change_ticks(check);
3257
3258 if let Some(mut schedules) = self.get_resource_mut::<Schedules>() {
3259 schedules.check_change_ticks(check);
3260 }
3261
3262 self.trigger(check);
3263 self.flush();
3264
3265 self.last_check_tick = change_tick;
3266
3267 Some(check)
3268 }
3269
3270 /// Clears all entities, resources, and non-send data.
3271 /// This invalidates all [`Entity`] and resource fetches such as [`Res`](crate::system::Res),
3272 /// [`ResMut`](crate::system::ResMut)
3273 pub fn clear_all(&mut self) {
3274 self.clear_entities();
3275 self.clear_non_send();
3276 }
3277
3278 /// Despawns all entities in this [`World`].
3279 ///
3280 /// **Note:** This includes all resources, as they are stored as components.
3281 /// Any resource fetch to this [`World`] will fail unless they are re-initialized,
3282 /// including engine-internal resources that are only initialized on app/world construction.
3283 ///
3284 /// This can easily cause systems expecting certain resources to immediately start panicking.
3285 /// Use with caution.
3286 pub fn clear_entities(&mut self) {
3287 self.storages.tables.clear();
3288 self.storages.sparse_sets.clear_entities();
3289 self.archetypes.clear_entities();
3290 self.entities.clear();
3291 self.entity_allocator.restart();
3292 }
3293
3294 /// Clears all resources in this [`World`].
3295 ///
3296 /// **Note:** Any resource fetch to this [`World`] will fail unless they are re-initialized,
3297 /// including engine-internal resources that are only initialized on app/world construction.
3298 ///
3299 /// This can easily cause systems expecting certain resources to immediately start panicking.
3300 /// Use with caution.
3301 pub fn clear_resources(&mut self) {
3302 let pairs: Vec<(ComponentId, Entity)> = self.resource_entities().iter().collect();
3303 for (component_id, entity) in pairs {
3304 self.entity_mut(entity).remove_by_id(component_id);
3305 }
3306 }
3307
3308 /// Clears all non-send data in this [`World`].
3309 pub fn clear_non_send(&mut self) {
3310 self.storages.non_sends.clear();
3311 }
3312
3313 /// Registers all of the components in the given [`Bundle`] and returns both the component
3314 /// ids and the bundle id.
3315 ///
3316 /// This is largely equivalent to calling [`register_component`](Self::register_component) on each
3317 /// component in the bundle.
3318 #[inline]
3319 pub fn register_bundle<B: Bundle>(&mut self) -> &BundleInfo {
3320 let id = self.register_bundle_info::<B>();
3321
3322 // SAFETY: We just initialized the bundle so its id should definitely be valid.
3323 unsafe { self.bundles.get(id).debug_checked_unwrap() }
3324 }
3325
3326 pub(crate) fn register_bundle_info<B: Bundle>(&mut self) -> BundleId {
3327 // SAFETY: These come from the same world. `Self.components_registrator` can't be used since we borrow other fields too.
3328 let mut registrator =
3329 unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) };
3330
3331 // SAFETY: `registrator`, `self.storages` and `self.bundles` all come from this world.
3332 unsafe {
3333 self.bundles
3334 .register_info::<B>(&mut registrator, &mut self.storages)
3335 }
3336 }
3337
3338 pub(crate) fn register_contributed_bundle_info<B: Bundle>(&mut self) -> BundleId {
3339 // SAFETY: These come from the same world. `Self.components_registrator` can't be used since we borrow other fields too.
3340 let mut registrator =
3341 unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) };
3342
3343 // SAFETY: `registrator`, `self.bundles` and `self.storages` are all from this world.
3344 unsafe {
3345 self.bundles
3346 .register_contributed_bundle_info::<B>(&mut registrator, &mut self.storages)
3347 }
3348 }
3349
3350 /// Registers the given [`ComponentId`]s as a dynamic bundle and returns both the required component ids and the bundle id.
3351 ///
3352 /// Note that the components need to be registered first, this function only creates a bundle combining them. Components
3353 /// can be registered with [`World::register_component`]/[`_with_descriptor`](World::register_component_with_descriptor).
3354 ///
3355 /// **You should prefer to use the typed API [`World::register_bundle`] where possible and only use this in cases where
3356 /// not all of the actual types are known at compile time.**
3357 ///
3358 /// # Panics
3359 /// This function will panic if any of the provided component ids do not belong to a component known to this [`World`].
3360 #[inline]
3361 pub fn register_dynamic_bundle(&mut self, component_ids: &[ComponentId]) -> &BundleInfo {
3362 let id =
3363 self.bundles
3364 .init_dynamic_info(&mut self.storages, &self.components, component_ids);
3365 // SAFETY: We just initialized the bundle so its id should definitely be valid.
3366 unsafe { self.bundles.get(id).debug_checked_unwrap() }
3367 }
3368
3369 /// Convenience method for accessing the world's fallback error handler,
3370 /// which can be overwritten with [`FallbackErrorHandler`].
3371 #[inline]
3372 pub fn fallback_error_handler(&self) -> ErrorHandler {
3373 self.get_resource::<FallbackErrorHandler>()
3374 .copied()
3375 .unwrap_or_default()
3376 .0
3377 }
3378}
3379
3380impl World {
3381 /// Gets a pointer to the resource with the id [`ComponentId`] if it exists.
3382 /// The returned pointer must not be used to modify the resource, and must not be
3383 /// dereferenced after the immutable borrow of the [`World`] ends.
3384 ///
3385 /// **You should prefer to use the typed API [`World::get_resource`] where possible and only
3386 /// use this in cases where the actual types are not known at compile time.**
3387 #[inline]
3388 pub fn get_resource_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
3389 // SAFETY:
3390 // - `as_unsafe_world_cell_readonly` gives permission to access the whole world immutably
3391 // - `&self` ensures there are no mutable borrows on world data
3392 unsafe {
3393 self.as_unsafe_world_cell_readonly()
3394 .get_resource_by_id(component_id)
3395 }
3396 }
3397
3398 /// Gets a pointer to the resource with the id [`ComponentId`] if it exists and is mutable.
3399 /// The returned pointer may be used to modify the resource, as long as the mutable borrow
3400 /// of the [`World`] is still valid.
3401 ///
3402 /// **You should prefer to use the typed API [`World::get_resource_mut`] where possible and only
3403 /// use this in cases where the actual types are not known at compile time.**
3404 #[inline]
3405 pub fn get_resource_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
3406 // SAFETY:
3407 // - `&mut self` ensures that all accessed data is unaliased
3408 // - `as_unsafe_world_cell` provides mutable permission to the whole world
3409 unsafe {
3410 self.as_unsafe_world_cell()
3411 .get_resource_mut_by_id(component_id)
3412 }
3413 }
3414
3415 /// Iterates over all resources in the world.
3416 ///
3417 /// The returned iterator provides lifetimed, but type-unsafe pointers. Actually reading the contents
3418 /// of each resource will require the use of unsafe code.
3419 ///
3420 /// # Examples
3421 ///
3422 /// ## Printing the size of all resources
3423 ///
3424 /// ```
3425 /// # use bevy_ecs::prelude::*;
3426 /// # #[derive(Resource)]
3427 /// # struct A(u32);
3428 /// # #[derive(Resource)]
3429 /// # struct B(u32);
3430 /// #
3431 /// # let mut world = World::new();
3432 /// # world.remove_resource::<bevy_ecs::entity_disabling::DefaultQueryFilters>();
3433 /// # world.insert_resource(A(1));
3434 /// # world.insert_resource(B(2));
3435 /// let mut total = 0;
3436 /// for (info, _) in world.iter_resources() {
3437 /// println!("Resource: {}", info.name());
3438 /// println!("Size: {} bytes", info.layout().size());
3439 /// total += info.layout().size();
3440 /// }
3441 /// println!("Total size: {} bytes", total);
3442 /// # assert_eq!(total, size_of::<A>() + size_of::<B>());
3443 /// ```
3444 ///
3445 /// ## Dynamically running closures for resources matching specific `TypeId`s
3446 ///
3447 /// ```
3448 /// # use bevy_ecs::prelude::*;
3449 /// # use std::collections::HashMap;
3450 /// # use std::any::TypeId;
3451 /// # use bevy_ptr::Ptr;
3452 /// # #[derive(Resource)]
3453 /// # struct A(u32);
3454 /// # #[derive(Resource)]
3455 /// # struct B(u32);
3456 /// #
3457 /// # let mut world = World::new();
3458 /// # world.insert_resource(A(1));
3459 /// # world.insert_resource(B(2));
3460 /// #
3461 /// // In this example, `A` and `B` are resources. We deliberately do not use the
3462 /// // `bevy_reflect` crate here to showcase the low-level [`Ptr`] usage. You should
3463 /// // probably use something like `ReflectFromPtr` in a real-world scenario.
3464 ///
3465 /// // Create the hash map that will store the closures for each resource type
3466 /// let mut closures: HashMap<TypeId, Box<dyn Fn(&Ptr<'_>)>> = HashMap::default();
3467 ///
3468 /// // Add closure for `A`
3469 /// closures.insert(TypeId::of::<A>(), Box::new(|ptr| {
3470 /// // SAFETY: We assert ptr is the same type of A with TypeId of A
3471 /// let a = unsafe { &ptr.deref::<A>() };
3472 /// # assert_eq!(a.0, 1);
3473 /// // ... do something with `a` here
3474 /// }));
3475 ///
3476 /// // Add closure for `B`
3477 /// closures.insert(TypeId::of::<B>(), Box::new(|ptr| {
3478 /// // SAFETY: We assert ptr is the same type of B with TypeId of B
3479 /// let b = unsafe { &ptr.deref::<B>() };
3480 /// # assert_eq!(b.0, 2);
3481 /// // ... do something with `b` here
3482 /// }));
3483 ///
3484 /// // Iterate all resources, in order to run the closures for each matching resource type
3485 /// for (info, ptr) in world.iter_resources() {
3486 /// let Some(type_id) = info.type_id() else {
3487 /// // It's possible for resources to not have a `TypeId` (e.g. non-Rust resources
3488 /// // dynamically inserted via a scripting language) in which case we can't match them.
3489 /// continue;
3490 /// };
3491 ///
3492 /// let Some(closure) = closures.get(&type_id) else {
3493 /// // No closure for this resource type, skip it.
3494 /// continue;
3495 /// };
3496 ///
3497 /// // Run the closure for the resource
3498 /// closure(&ptr);
3499 /// }
3500 /// ```
3501 #[inline]
3502 pub fn iter_resources(&self) -> impl Iterator<Item = (&ComponentInfo, Ptr<'_>)> {
3503 self.resource_entities
3504 .iter()
3505 .filter_map(|(component_id, entity)| {
3506 let component_info = self.components().get_info(component_id)?;
3507 let entity_cell = self.get_entity(entity).ok()?;
3508 let resource = entity_cell.get_by_id(component_id).ok()?;
3509 Some((component_info, resource))
3510 })
3511 }
3512
3513 /// Mutably iterates over all resources in the world.
3514 ///
3515 /// The returned iterator provides lifetimed, but type-unsafe pointers. Actually reading from or writing
3516 /// to the contents of each resource will require the use of unsafe code.
3517 ///
3518 /// # Example
3519 ///
3520 /// ```
3521 /// # use bevy_ecs::prelude::*;
3522 /// # use bevy_ecs::change_detection::MutUntyped;
3523 /// # use std::collections::HashMap;
3524 /// # use std::any::TypeId;
3525 /// # #[derive(Resource)]
3526 /// # struct A(u32);
3527 /// # #[derive(Resource)]
3528 /// # struct B(u32);
3529 /// #
3530 /// # let mut world = World::new();
3531 /// # world.insert_resource(A(1));
3532 /// # world.insert_resource(B(2));
3533 /// #
3534 /// // In this example, `A` and `B` are resources. We deliberately do not use the
3535 /// // `bevy_reflect` crate here to showcase the low-level `MutUntyped` usage. You should
3536 /// // probably use something like `ReflectFromPtr` in a real-world scenario.
3537 ///
3538 /// // Create the hash map that will store the mutator closures for each resource type
3539 /// let mut mutators: HashMap<TypeId, Box<dyn Fn(&mut MutUntyped<'_>)>> = HashMap::default();
3540 ///
3541 /// // Add mutator closure for `A`
3542 /// mutators.insert(TypeId::of::<A>(), Box::new(|mut_untyped| {
3543 /// // Note: `MutUntyped::as_mut()` automatically marks the resource as changed
3544 /// // for ECS change detection, and gives us a `PtrMut` we can use to mutate the resource.
3545 /// // SAFETY: We assert ptr is the same type of A with TypeId of A
3546 /// let a = unsafe { &mut mut_untyped.as_mut().deref_mut::<A>() };
3547 /// # a.0 += 1;
3548 /// // ... mutate `a` here
3549 /// }));
3550 ///
3551 /// // Add mutator closure for `B`
3552 /// mutators.insert(TypeId::of::<B>(), Box::new(|mut_untyped| {
3553 /// // SAFETY: We assert ptr is the same type of B with TypeId of B
3554 /// let b = unsafe { &mut mut_untyped.as_mut().deref_mut::<B>() };
3555 /// # b.0 += 1;
3556 /// // ... mutate `b` here
3557 /// }));
3558 ///
3559 /// // Iterate all resources, in order to run the mutator closures for each matching resource type
3560 /// for (info, mut mut_untyped) in world.iter_resources_mut() {
3561 /// let Some(type_id) = info.type_id() else {
3562 /// // It's possible for resources to not have a `TypeId` (e.g. non-Rust resources
3563 /// // dynamically inserted via a scripting language) in which case we can't match them.
3564 /// continue;
3565 /// };
3566 ///
3567 /// let Some(mutator) = mutators.get(&type_id) else {
3568 /// // No mutator closure for this resource type, skip it.
3569 /// continue;
3570 /// };
3571 ///
3572 /// // Run the mutator closure for the resource
3573 /// mutator(&mut mut_untyped);
3574 /// }
3575 /// # assert_eq!(world.resource::<A>().0, 2);
3576 /// # assert_eq!(world.resource::<B>().0, 3);
3577 /// ```
3578 pub fn iter_resources_mut(&mut self) -> impl Iterator<Item = (&ComponentInfo, MutUntyped<'_>)> {
3579 let unsafe_world = self.as_unsafe_world_cell();
3580 // SAFETY: exclusive world access to all resources
3581 let resource_entities = unsafe { unsafe_world.resource_entities() };
3582 let components = unsafe_world.components();
3583
3584 resource_entities
3585 .iter()
3586 .filter_map(move |(component_id, entity)| {
3587 // SAFETY: If a resource has been initialized, a corresponding ComponentInfo must exist with its ID.
3588 let component_info =
3589 unsafe { components.get_info(component_id).debug_checked_unwrap() };
3590
3591 let entity_cell = unsafe_world.get_entity(entity).ok()?;
3592
3593 // SAFETY:
3594 // - We have exclusive world access
3595 // - `UnsafeEntityCell::get_mut_by_id` doesn't access components
3596 // or resource_entities mutably
3597 // - `resource_entities` doesn't contain duplicate entities, so
3598 // no duplicate references are created
3599 let mut_untyped = unsafe { entity_cell.get_mut_by_id(component_id).ok()? };
3600
3601 Some((component_info, mut_untyped))
3602 })
3603 }
3604
3605 /// Gets a pointer to `!Send` data with the id [`ComponentId`] if it exists.
3606 /// The returned pointer must not be used to modify the resource, and must not be
3607 /// dereferenced after the immutable borrow of the [`World`] ends.
3608 ///
3609 /// **You should prefer to use the typed API [`World::get_non_send`] where possible and only
3610 /// use this in cases where the actual types are not known at compile time.**
3611 ///
3612 /// # Panics
3613 /// This function will panic if it isn't called from the same thread that the data was inserted from.
3614 #[inline]
3615 pub fn get_non_send_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
3616 // SAFETY:
3617 // - `as_unsafe_world_cell_readonly` gives permission to access the whole world immutably
3618 // - `&self` ensures there are no mutable borrows on world data
3619 unsafe {
3620 self.as_unsafe_world_cell_readonly()
3621 .get_non_send_by_id(component_id)
3622 }
3623 }
3624
3625 /// Gets mutable access to `!Send` data with the id [`ComponentId`] if it exists.
3626 /// The returned pointer may be used to modify the data, as long as the mutable borrow
3627 /// of the [`World`] is still valid.
3628 ///
3629 /// **You should prefer to use the typed API [`World::get_non_send_mut`] where possible and only
3630 /// use this in cases where the actual types are not known at compile time.**
3631 ///
3632 /// # Panics
3633 /// This function will panic if it isn't called from the same thread that the data was inserted from.
3634 #[inline]
3635 pub fn get_non_send_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
3636 // SAFETY:
3637 // - `&mut self` ensures that all accessed data is unaliased
3638 // - `as_unsafe_world_cell` provides mutable permission to the whole world
3639 unsafe {
3640 self.as_unsafe_world_cell()
3641 .get_non_send_mut_by_id(component_id)
3642 }
3643 }
3644
3645 /// Removes the resource of a given type, if it exists.
3646 /// Returns `true` if the resource is successfully removed and `false` if
3647 /// the entity does not exist.
3648 ///
3649 /// **You should prefer to use the typed API [`World::remove_resource`] where possible and only
3650 /// use this in cases where the actual types are not known at compile time.**
3651 pub fn remove_resource_by_id(&mut self, component_id: ComponentId) -> bool {
3652 if let Some(entity) = self.resource_entities.get(component_id)
3653 && let Ok(mut entity_mut) = self.get_entity_mut(entity)
3654 && entity_mut.contains_id(component_id)
3655 {
3656 entity_mut.remove_by_id(component_id);
3657 true
3658 } else {
3659 false
3660 }
3661 }
3662
3663 /// Removes the non-send data of a given type, if it exists. Otherwise returns `None`.
3664 ///
3665 /// **You should prefer to use the typed API [`World::remove_non_send`] where possible and only
3666 /// use this in cases where the actual types are not known at compile time.**
3667 ///
3668 /// # Panics
3669 /// This function will panic if it isn't called from the same thread that the data was inserted from.
3670 pub fn remove_non_send_by_id(&mut self, component_id: ComponentId) -> Option<()> {
3671 self.storages
3672 .non_sends
3673 .get_mut(component_id)?
3674 .remove_and_drop();
3675 Some(())
3676 }
3677
3678 /// Retrieves an immutable untyped reference to the given `entity`'s [`Component`] of the given [`ComponentId`].
3679 /// Returns `None` if the `entity` does not have a [`Component`] of the given type.
3680 ///
3681 /// **You should prefer to use the typed API [`World::get_mut`] where possible and only
3682 /// use this in cases where the actual types are not known at compile time.**
3683 ///
3684 /// # Panics
3685 /// This function will panic if it isn't called from the same thread that the resource was inserted from.
3686 #[inline]
3687 pub fn get_by_id(&self, entity: Entity, component_id: ComponentId) -> Option<Ptr<'_>> {
3688 self.get_entity(entity).ok()?.get_by_id(component_id).ok()
3689 }
3690
3691 /// Retrieves a mutable untyped reference to the given `entity`'s [`Component`] of the given [`ComponentId`].
3692 /// Returns `None` if the `entity` does not have a [`Component`] of the given type.
3693 ///
3694 /// **You should prefer to use the typed API [`World::get_mut`] where possible and only
3695 /// use this in cases where the actual types are not known at compile time.**
3696 #[inline]
3697 pub fn get_mut_by_id(
3698 &mut self,
3699 entity: Entity,
3700 component_id: ComponentId,
3701 ) -> Option<MutUntyped<'_>> {
3702 self.get_entity_mut(entity)
3703 .ok()?
3704 .into_mut_by_id(component_id)
3705 .ok()
3706 }
3707}
3708
3709// Schedule-related methods
3710impl World {
3711 /// Adds the specified [`Schedule`] to the world.
3712 /// If a schedule already exists with the same [label](Schedule::label), it will be replaced.
3713 ///
3714 /// The schedule can later be run
3715 /// by calling [`.run_schedule(label)`](Self::run_schedule) or by directly
3716 /// accessing the [`Schedules`] resource.
3717 ///
3718 /// The `Schedules` resource will be initialized if it does not already exist.
3719 ///
3720 /// An alternative to this is to call [`Schedules::add_systems()`] with some
3721 /// [`ScheduleLabel`] and let the schedule for that label be created if it
3722 /// does not already exist.
3723 pub fn add_schedule(&mut self, schedule: Schedule) {
3724 let mut schedules = self.get_resource_or_init::<Schedules>();
3725 schedules.insert(schedule);
3726 }
3727
3728 /// Temporarily removes the schedule associated with `label` from the world,
3729 /// runs user code, and finally re-adds the schedule.
3730 /// This returns a [`TryRunScheduleError`] if there is no schedule
3731 /// associated with `label`.
3732 ///
3733 /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3734 /// and system state is cached.
3735 ///
3736 /// For simple cases where you just need to call the schedule once,
3737 /// consider using [`World::try_run_schedule`] instead.
3738 /// For other use cases, see the example on [`World::schedule_scope`].
3739 pub fn try_schedule_scope<R>(
3740 &mut self,
3741 label: impl ScheduleLabel,
3742 f: impl FnOnce(&mut World, &mut Schedule) -> R,
3743 ) -> Result<R, TryRunScheduleError> {
3744 let label = label.intern();
3745 let Some(mut schedule) = self
3746 .get_resource_mut::<Schedules>()
3747 .and_then(|mut s| s.remove_temporarily(label))
3748 else {
3749 return Err(TryRunScheduleError(label));
3750 };
3751
3752 let value = f(self, &mut schedule);
3753
3754 let old = self.resource_mut::<Schedules>().reinsert(schedule);
3755 if old.is_some() {
3756 warn!("Schedule `{label:?}` was inserted during a call to `World::schedule_scope`: its value has been overwritten");
3757 }
3758
3759 Ok(value)
3760 }
3761
3762 /// Temporarily removes the schedule associated with `label` from the world,
3763 /// runs user code, and finally re-adds the schedule.
3764 ///
3765 /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3766 /// and system state is cached.
3767 ///
3768 /// # Examples
3769 ///
3770 /// ```
3771 /// # use bevy_ecs::{prelude::*, schedule::ScheduleLabel};
3772 /// # #[derive(ScheduleLabel, Debug, Clone, Copy, PartialEq, Eq, Hash)]
3773 /// # pub struct MySchedule;
3774 /// # #[derive(Resource)]
3775 /// # struct Counter(usize);
3776 /// #
3777 /// # let mut world = World::new();
3778 /// # world.insert_resource(Counter(0));
3779 /// # let mut schedule = Schedule::new(MySchedule);
3780 /// # schedule.add_systems(tick_counter);
3781 /// # world.init_resource::<Schedules>();
3782 /// # world.add_schedule(schedule);
3783 /// # fn tick_counter(mut counter: ResMut<Counter>) { counter.0 += 1; }
3784 /// // Run the schedule five times.
3785 /// world.schedule_scope(MySchedule, |world, schedule| {
3786 /// for _ in 0..5 {
3787 /// schedule.run(world);
3788 /// }
3789 /// });
3790 /// # assert_eq!(world.resource::<Counter>().0, 5);
3791 /// ```
3792 ///
3793 /// For simple cases where you just need to call the schedule once,
3794 /// consider using [`World::run_schedule`] instead.
3795 ///
3796 /// # Panics
3797 ///
3798 /// If the requested schedule does not exist.
3799 pub fn schedule_scope<R>(
3800 &mut self,
3801 label: impl ScheduleLabel,
3802 f: impl FnOnce(&mut World, &mut Schedule) -> R,
3803 ) -> R {
3804 self.try_schedule_scope(label, f)
3805 .unwrap_or_else(|e| panic!("{e}"))
3806 }
3807
3808 /// Attempts to run the [`Schedule`] associated with the `label` a single time,
3809 /// and returns a [`TryRunScheduleError`] if the schedule does not exist.
3810 ///
3811 /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3812 /// and system state is cached.
3813 ///
3814 /// For simple testing use cases, call [`Schedule::run(&mut world)`](Schedule::run) instead.
3815 pub fn try_run_schedule(
3816 &mut self,
3817 label: impl ScheduleLabel,
3818 ) -> Result<(), TryRunScheduleError> {
3819 self.try_schedule_scope(label, |world, sched| sched.run(world))
3820 }
3821
3822 /// Runs the [`Schedule`] associated with the `label` a single time.
3823 ///
3824 /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3825 /// and system state is cached.
3826 ///
3827 /// For simple testing use cases, call [`Schedule::run(&mut world)`](Schedule::run) instead.
3828 /// This avoids the need to create a unique [`ScheduleLabel`].
3829 ///
3830 /// # Panics
3831 ///
3832 /// If the requested schedule does not exist.
3833 pub fn run_schedule(&mut self, label: impl ScheduleLabel) {
3834 self.schedule_scope(label, |world, sched| sched.run(world));
3835 }
3836
3837 /// Ignore system order ambiguities caused by conflicts on [`Component`]s of type `T`.
3838 pub fn allow_ambiguous_component<T: Component>(&mut self) {
3839 let mut schedules = self.remove_resource::<Schedules>().unwrap_or_default();
3840 schedules.allow_ambiguous_component::<T>(self);
3841 self.insert_resource(schedules);
3842 }
3843
3844 /// Ignore system order ambiguities caused by conflicts on [`Resource`]s of type `T`.
3845 pub fn allow_ambiguous_resource<T: Resource>(&mut self) {
3846 let mut schedules = self.remove_resource::<Schedules>().unwrap_or_default();
3847 schedules.allow_ambiguous_resource::<T>(self);
3848 self.insert_resource(schedules);
3849 }
3850}
3851
3852impl fmt::Debug for World {
3853 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3854 // SAFETY: `UnsafeWorldCell` requires that this must only access metadata.
3855 // Accessing any data stored in the world would be unsound.
3856 f.debug_struct("World")
3857 .field("id", &self.id)
3858 .field("entity_count", &self.entities.count_spawned())
3859 .field("archetype_count", &self.archetypes.len())
3860 .field("component_count", &self.components.len())
3861 .finish()
3862 }
3863}
3864
3865// SAFETY: all methods on the world ensure that non-send resources are only accessible on the main thread
3866unsafe impl Send for World {}
3867// SAFETY: all methods on the world ensure that non-send resources are only accessible on the main thread
3868unsafe impl Sync for World {}
3869
3870/// Creates an instance of the type this trait is implemented for
3871/// using data from the supplied [`World`].
3872///
3873/// This can be helpful for complex initialization or context-aware defaults.
3874///
3875/// [`FromWorld`] is automatically implemented for any type implementing [`Default`]
3876/// and may also be derived for:
3877/// - any struct whose fields all implement `FromWorld`
3878/// - any enum where one variant has the attribute `#[from_world]`
3879///
3880/// ```rs
3881///
3882/// #[derive(Default)]
3883/// struct A;
3884///
3885/// #[derive(Default)]
3886/// struct B(Option<u32>)
3887///
3888/// struct C;
3889///
3890/// impl FromWorld for C {
3891/// fn from_world(_world: &mut World) -> Self {
3892/// Self
3893/// }
3894/// }
3895///
3896/// #[derive(FromWorld)]
3897/// struct D(A, B, C);
3898///
3899/// #[derive(FromWorld)]
3900/// enum E {
3901/// #[from_world]
3902/// F,
3903/// G
3904/// }
3905/// ```
3906pub trait FromWorld {
3907 /// Creates `Self` using data from the given [`World`].
3908 fn from_world(world: &mut World) -> Self;
3909}
3910
3911impl<T: Default> FromWorld for T {
3912 /// Creates `Self` using [`default()`](`Default::default`).
3913 #[track_caller]
3914 fn from_world(_world: &mut World) -> Self {
3915 T::default()
3916 }
3917}
3918
3919#[cfg(test)]
3920#[expect(clippy::print_stdout, reason = "Allowed in tests.")]
3921mod tests {
3922 use super::{FromWorld, World};
3923 use crate::{
3924 change_detection::{DetectChangesMut, MaybeLocation},
3925 component::{ComponentCloneBehavior, ComponentDescriptor, ComponentInfo, StorageType},
3926 entity::EntityHashSet,
3927 entity_disabling::{DefaultQueryFilters, Disabled},
3928 prelude::{DetectChanges, Event, Mut, On, Res},
3929 ptr::OwningPtr,
3930 resource::Resource,
3931 world::{error::EntityMutableFetchError, DeferredWorld},
3932 };
3933 use alloc::{
3934 borrow::ToOwned,
3935 string::{String, ToString},
3936 sync::Arc,
3937 vec,
3938 vec::Vec,
3939 };
3940 use bevy_ecs_macros::Component;
3941 use bevy_platform::collections::{HashMap, HashSet};
3942 use bevy_utils::prelude::DebugName;
3943 use core::{
3944 any::TypeId,
3945 panic,
3946 sync::atomic::{AtomicBool, AtomicU32, Ordering},
3947 };
3948 use std::{println, sync::Mutex};
3949
3950 type ID = u8;
3951
3952 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
3953 enum DropLogItem {
3954 Create(ID),
3955 Drop(ID),
3956 }
3957
3958 #[derive(Component)]
3959 struct MayPanicInDrop {
3960 drop_log: Arc<Mutex<Vec<DropLogItem>>>,
3961 expected_panic_flag: Arc<AtomicBool>,
3962 should_panic: bool,
3963 id: u8,
3964 }
3965
3966 impl MayPanicInDrop {
3967 fn new(
3968 drop_log: &Arc<Mutex<Vec<DropLogItem>>>,
3969 expected_panic_flag: &Arc<AtomicBool>,
3970 should_panic: bool,
3971 id: u8,
3972 ) -> Self {
3973 println!("creating component with id {id}");
3974 drop_log.lock().unwrap().push(DropLogItem::Create(id));
3975
3976 Self {
3977 drop_log: Arc::clone(drop_log),
3978 expected_panic_flag: Arc::clone(expected_panic_flag),
3979 should_panic,
3980 id,
3981 }
3982 }
3983 }
3984
3985 impl Drop for MayPanicInDrop {
3986 fn drop(&mut self) {
3987 println!("dropping component with id {}", self.id);
3988
3989 {
3990 let mut drop_log = self.drop_log.lock().unwrap();
3991 drop_log.push(DropLogItem::Drop(self.id));
3992 // Don't keep the mutex while panicking, or we'll poison it.
3993 drop(drop_log);
3994 }
3995
3996 if self.should_panic {
3997 self.expected_panic_flag.store(true, Ordering::SeqCst);
3998 panic!("testing what happens on panic inside drop");
3999 }
4000 }
4001 }
4002
4003 struct DropTestHelper {
4004 drop_log: Arc<Mutex<Vec<DropLogItem>>>,
4005 /// Set to `true` right before we intentionally panic, so that if we get
4006 /// a panic, we know if it was intended or not.
4007 expected_panic_flag: Arc<AtomicBool>,
4008 }
4009
4010 impl DropTestHelper {
4011 pub fn new() -> Self {
4012 Self {
4013 drop_log: Arc::new(Mutex::new(Vec::<DropLogItem>::new())),
4014 expected_panic_flag: Arc::new(AtomicBool::new(false)),
4015 }
4016 }
4017
4018 pub fn make_component(&self, should_panic: bool, id: ID) -> MayPanicInDrop {
4019 MayPanicInDrop::new(&self.drop_log, &self.expected_panic_flag, should_panic, id)
4020 }
4021
4022 pub fn finish(self, panic_res: std::thread::Result<()>) -> Vec<DropLogItem> {
4023 let drop_log = self.drop_log.lock().unwrap();
4024 let expected_panic_flag = self.expected_panic_flag.load(Ordering::SeqCst);
4025
4026 if !expected_panic_flag {
4027 match panic_res {
4028 Ok(()) => panic!("Expected a panic but it didn't happen"),
4029 Err(e) => std::panic::resume_unwind(e),
4030 }
4031 }
4032
4033 drop_log.to_owned()
4034 }
4035 }
4036
4037 #[test]
4038 fn panic_while_overwriting_component() {
4039 let helper = DropTestHelper::new();
4040
4041 let res = std::panic::catch_unwind(|| {
4042 let mut world = World::new();
4043 world
4044 .spawn_empty()
4045 .insert(helper.make_component(true, 0))
4046 .insert(helper.make_component(false, 1));
4047
4048 println!("Done inserting! Dropping world...");
4049 });
4050
4051 let drop_log = helper.finish(res);
4052
4053 assert_eq!(
4054 &*drop_log,
4055 [
4056 DropLogItem::Create(0),
4057 DropLogItem::Create(1),
4058 DropLogItem::Drop(0),
4059 DropLogItem::Drop(1),
4060 ]
4061 );
4062 }
4063
4064 #[derive(Resource)]
4065 struct TestResource(u32);
4066
4067 #[derive(Resource)]
4068 struct TestResource2(String);
4069
4070 #[derive(Resource)]
4071 struct TestResource3;
4072
4073 #[test]
4074 fn get_resource_by_id() {
4075 let mut world = World::new();
4076 world.insert_resource(TestResource(42));
4077 let component_id = world
4078 .components()
4079 .get_valid_id(TypeId::of::<TestResource>())
4080 .unwrap();
4081
4082 let resource = world.get_resource_by_id(component_id).unwrap();
4083 // SAFETY: `TestResource` is the correct resource type
4084 let resource = unsafe { resource.deref::<TestResource>() };
4085
4086 assert_eq!(resource.0, 42);
4087 }
4088
4089 #[test]
4090 fn get_resource_mut_by_id() {
4091 let mut world = World::new();
4092 world.insert_resource(TestResource(42));
4093 let component_id = world
4094 .components()
4095 .get_valid_id(TypeId::of::<TestResource>())
4096 .unwrap();
4097
4098 {
4099 let mut resource = world.get_resource_mut_by_id(component_id).unwrap();
4100 resource.set_changed();
4101 // SAFETY: `TestResource` is the correct resource type
4102 let resource = unsafe { resource.into_inner().deref_mut::<TestResource>() };
4103 resource.0 = 43;
4104 }
4105
4106 let resource = world.get_resource_by_id(component_id).unwrap();
4107 // SAFETY: `TestResource` is the correct resource type
4108 let resource = unsafe { resource.deref::<TestResource>() };
4109
4110 assert_eq!(resource.0, 43);
4111 }
4112
4113 #[test]
4114 fn iter_resources() {
4115 let mut world = World::new();
4116 // Remove DefaultQueryFilters so it doesn't show up in the iterator
4117 world.remove_resource::<DefaultQueryFilters>();
4118 world.insert_resource(TestResource(42));
4119 world.insert_resource(TestResource2("Hello, world!".to_string()));
4120 world.insert_resource(TestResource3);
4121 world.remove_resource::<TestResource3>();
4122
4123 let mut iter = world.iter_resources();
4124
4125 let (info, ptr) = iter.next().unwrap();
4126 assert_eq!(info.name(), DebugName::type_name::<TestResource>());
4127 // SAFETY: We know that the resource is of type `TestResource`
4128 assert_eq!(unsafe { ptr.deref::<TestResource>().0 }, 42);
4129
4130 let (info, ptr) = iter.next().unwrap();
4131 assert_eq!(info.name(), DebugName::type_name::<TestResource2>());
4132 assert_eq!(
4133 // SAFETY: We know that the resource is of type `TestResource2`
4134 unsafe { &ptr.deref::<TestResource2>().0 },
4135 &"Hello, world!".to_string()
4136 );
4137
4138 assert!(iter.next().is_none());
4139 }
4140
4141 #[test]
4142 fn iter_resources_mut() {
4143 let mut world = World::new();
4144 // Remove DefaultQueryFilters so it doesn't show up in the iterator
4145 world.remove_resource::<DefaultQueryFilters>();
4146 world.insert_resource(TestResource(42));
4147 world.insert_resource(TestResource2("Hello, world!".to_string()));
4148 world.insert_resource(TestResource3);
4149 world.remove_resource::<TestResource3>();
4150
4151 let mut iter = world.iter_resources_mut();
4152
4153 let (info, mut mut_untyped) = iter.next().unwrap();
4154 assert_eq!(info.name(), DebugName::type_name::<TestResource>());
4155 // SAFETY: We know that the resource is of type `TestResource`
4156 unsafe {
4157 mut_untyped.as_mut().deref_mut::<TestResource>().0 = 43;
4158 };
4159
4160 let (info, mut mut_untyped) = iter.next().unwrap();
4161 assert_eq!(info.name(), DebugName::type_name::<TestResource2>());
4162 // SAFETY: We know that the resource is of type `TestResource2`
4163 unsafe {
4164 mut_untyped.as_mut().deref_mut::<TestResource2>().0 = "Hello, world?".to_string();
4165 };
4166
4167 assert!(iter.next().is_none());
4168 drop(iter);
4169
4170 assert_eq!(world.resource::<TestResource>().0, 43);
4171 assert_eq!(
4172 world.resource::<TestResource2>().0,
4173 "Hello, world?".to_string()
4174 );
4175 }
4176
4177 #[test]
4178 fn custom_non_send_with_layout() {
4179 static DROP_COUNT: AtomicU32 = AtomicU32::new(0);
4180
4181 let mut world = World::new();
4182
4183 // SAFETY: the drop function is valid for the layout and the data will be safe to access from any thread
4184 let descriptor = unsafe {
4185 ComponentDescriptor::new_with_layout(
4186 "Custom Test Component".to_string(),
4187 StorageType::Table,
4188 core::alloc::Layout::new::<[u8; 8]>(),
4189 Some(|ptr| {
4190 let data = ptr.read::<[u8; 8]>();
4191 assert_eq!(data, [0, 1, 2, 3, 4, 5, 6, 7]);
4192 DROP_COUNT.fetch_add(1, Ordering::SeqCst);
4193 }),
4194 true,
4195 ComponentCloneBehavior::Default,
4196 None,
4197 )
4198 };
4199
4200 let component_id = world.register_component_with_descriptor(descriptor);
4201
4202 let value: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
4203 OwningPtr::make(value, |ptr| {
4204 // SAFETY: value is valid for the component layout
4205 unsafe {
4206 world.insert_non_send_by_id(component_id, ptr, MaybeLocation::caller());
4207 }
4208 });
4209
4210 // SAFETY: [u8; 8] is the correct type for the resource
4211 let data = unsafe {
4212 world
4213 .get_non_send_by_id(component_id)
4214 .unwrap()
4215 .deref::<[u8; 8]>()
4216 };
4217 assert_eq!(*data, [0, 1, 2, 3, 4, 5, 6, 7]);
4218
4219 assert!(world.remove_non_send_by_id(component_id).is_some());
4220
4221 assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1);
4222 }
4223
4224 #[derive(Resource)]
4225 struct TestFromWorld(u32);
4226 impl FromWorld for TestFromWorld {
4227 fn from_world(world: &mut World) -> Self {
4228 let b = world.resource::<TestResource>();
4229 Self(b.0)
4230 }
4231 }
4232
4233 #[test]
4234 fn init_resource_does_not_overwrite() {
4235 let mut world = World::new();
4236 world.insert_resource(TestResource(0));
4237 world.init_resource::<TestFromWorld>();
4238 world.insert_resource(TestResource(1));
4239 world.init_resource::<TestFromWorld>();
4240
4241 let resource = world.resource::<TestFromWorld>();
4242
4243 assert_eq!(resource.0, 0);
4244 }
4245
4246 #[test]
4247 fn init_non_send_does_not_overwrite() {
4248 let mut world = World::new();
4249 world.insert_resource(TestResource(0));
4250 world.init_non_send::<TestFromWorld>();
4251 world.insert_resource(TestResource(1));
4252 world.init_non_send::<TestFromWorld>();
4253
4254 let resource = world.non_send::<TestFromWorld>();
4255
4256 assert_eq!(resource.0, 0);
4257 }
4258
4259 #[derive(Component)]
4260 struct Foo;
4261
4262 #[derive(Component)]
4263 struct Bar;
4264
4265 #[derive(Component)]
4266 struct Baz;
4267
4268 #[test]
4269 fn inspect_entity_components() {
4270 let mut world = World::new();
4271 let ent0 = world.spawn((Foo, Bar, Baz)).id();
4272 let ent1 = world.spawn((Foo, Bar)).id();
4273 let ent2 = world.spawn((Bar, Baz)).id();
4274 let ent3 = world.spawn((Foo, Baz)).id();
4275 let ent4 = world.spawn(Foo).id();
4276 let ent5 = world.spawn(Bar).id();
4277 let ent6 = world.spawn(Baz).id();
4278
4279 fn to_type_ids(component_infos: Vec<&ComponentInfo>) -> HashSet<Option<TypeId>> {
4280 component_infos
4281 .into_iter()
4282 .map(ComponentInfo::type_id)
4283 .collect()
4284 }
4285
4286 let foo_id = TypeId::of::<Foo>();
4287 let bar_id = TypeId::of::<Bar>();
4288 let baz_id = TypeId::of::<Baz>();
4289 assert_eq!(
4290 to_type_ids(world.inspect_entity(ent0).unwrap().collect()),
4291 [Some(foo_id), Some(bar_id), Some(baz_id)]
4292 .into_iter()
4293 .collect::<HashSet<_>>()
4294 );
4295 assert_eq!(
4296 to_type_ids(world.inspect_entity(ent1).unwrap().collect()),
4297 [Some(foo_id), Some(bar_id)]
4298 .into_iter()
4299 .collect::<HashSet<_>>()
4300 );
4301 assert_eq!(
4302 to_type_ids(world.inspect_entity(ent2).unwrap().collect()),
4303 [Some(bar_id), Some(baz_id)]
4304 .into_iter()
4305 .collect::<HashSet<_>>()
4306 );
4307 assert_eq!(
4308 to_type_ids(world.inspect_entity(ent3).unwrap().collect()),
4309 [Some(foo_id), Some(baz_id)]
4310 .into_iter()
4311 .collect::<HashSet<_>>()
4312 );
4313 assert_eq!(
4314 to_type_ids(world.inspect_entity(ent4).unwrap().collect()),
4315 [Some(foo_id)].into_iter().collect::<HashSet<_>>()
4316 );
4317 assert_eq!(
4318 to_type_ids(world.inspect_entity(ent5).unwrap().collect()),
4319 [Some(bar_id)].into_iter().collect::<HashSet<_>>()
4320 );
4321 assert_eq!(
4322 to_type_ids(world.inspect_entity(ent6).unwrap().collect()),
4323 [Some(baz_id)].into_iter().collect::<HashSet<_>>()
4324 );
4325 }
4326
4327 #[test]
4328 fn iterate_entities() {
4329 let mut world = World::new();
4330 let mut entity_counters = <HashMap<_, _>>::default();
4331
4332 let iterate_and_count_entities = |world: &World, entity_counters: &mut HashMap<_, _>| {
4333 entity_counters.clear();
4334 for entity in world.iter_entities() {
4335 let counter = entity_counters.entry(entity.id()).or_insert(0);
4336 *counter += 1;
4337 }
4338 };
4339
4340 // Adding one entity and validating iteration
4341 let ent0 = world.spawn((Foo, Bar, Baz)).id();
4342
4343 iterate_and_count_entities(&world, &mut entity_counters);
4344 assert_eq!(entity_counters[&ent0], 1);
4345 assert_eq!(entity_counters.len(), 2);
4346
4347 // Spawning three more entities and then validating iteration
4348 let ent1 = world.spawn((Foo, Bar)).id();
4349 let ent2 = world.spawn((Bar, Baz)).id();
4350 let ent3 = world.spawn((Foo, Baz)).id();
4351
4352 iterate_and_count_entities(&world, &mut entity_counters);
4353
4354 assert_eq!(entity_counters[&ent0], 1);
4355 assert_eq!(entity_counters[&ent1], 1);
4356 assert_eq!(entity_counters[&ent2], 1);
4357 assert_eq!(entity_counters[&ent3], 1);
4358 assert_eq!(entity_counters.len(), 5);
4359
4360 // Despawning first entity and then validating the iteration
4361 assert!(world.despawn(ent0));
4362
4363 iterate_and_count_entities(&world, &mut entity_counters);
4364
4365 assert_eq!(entity_counters[&ent1], 1);
4366 assert_eq!(entity_counters[&ent2], 1);
4367 assert_eq!(entity_counters[&ent3], 1);
4368 assert_eq!(entity_counters.len(), 4);
4369
4370 // Spawning three more entities, despawning three and then validating the iteration
4371 let ent4 = world.spawn(Foo).id();
4372 let ent5 = world.spawn(Bar).id();
4373 let ent6 = world.spawn(Baz).id();
4374
4375 assert!(world.despawn(ent2));
4376 assert!(world.despawn(ent3));
4377 assert!(world.despawn(ent4));
4378
4379 iterate_and_count_entities(&world, &mut entity_counters);
4380
4381 assert_eq!(entity_counters[&ent1], 1);
4382 assert_eq!(entity_counters[&ent5], 1);
4383 assert_eq!(entity_counters[&ent6], 1);
4384 assert_eq!(entity_counters.len(), 4);
4385
4386 // Despawning remaining entities and then validating the iteration
4387 assert!(world.despawn(ent1));
4388 assert!(world.despawn(ent5));
4389 assert!(world.despawn(ent6));
4390
4391 iterate_and_count_entities(&world, &mut entity_counters);
4392
4393 assert_eq!(entity_counters.len(), 1);
4394 }
4395
4396 #[test]
4397 fn spawn_empty_bundle() {
4398 let mut world = World::new();
4399 world.spawn(());
4400 }
4401
4402 #[test]
4403 fn get_entity() {
4404 let mut world = World::new();
4405
4406 let e1 = world.spawn_empty().id();
4407 let e2 = world.spawn_empty().id();
4408
4409 assert!(world.get_entity(e1).is_ok());
4410 assert!(world.get_entity([e1, e2]).is_ok());
4411 assert!(world
4412 .get_entity(&[e1, e2] /* this is an array not a slice */)
4413 .is_ok());
4414 assert!(world.get_entity(&vec![e1, e2][..]).is_ok());
4415 assert!(world
4416 .get_entity(&EntityHashSet::from_iter([e1, e2]))
4417 .is_ok());
4418
4419 world.entity_mut(e1).despawn();
4420
4421 assert_eq!(
4422 Err(e1),
4423 world.get_entity(e1).map(|_| {}).map_err(|e| e.entity())
4424 );
4425 assert_eq!(
4426 Err(e1),
4427 world
4428 .get_entity([e1, e2])
4429 .map(|_| {})
4430 .map_err(|e| e.entity())
4431 );
4432 assert_eq!(
4433 Err(e1),
4434 world
4435 .get_entity(&[e1, e2] /* this is an array not a slice */)
4436 .map(|_| {})
4437 .map_err(|e| e.entity())
4438 );
4439 assert_eq!(
4440 Err(e1),
4441 world
4442 .get_entity(&vec![e1, e2][..])
4443 .map(|_| {})
4444 .map_err(|e| e.entity())
4445 );
4446 assert_eq!(
4447 Err(e1),
4448 world
4449 .get_entity(&EntityHashSet::from_iter([e1, e2]))
4450 .map(|_| {})
4451 .map_err(|e| e.entity())
4452 );
4453 }
4454
4455 #[test]
4456 fn get_entity_mut() {
4457 let mut world = World::new();
4458
4459 let e1 = world.spawn_empty().id();
4460 let e2 = world.spawn_empty().id();
4461
4462 assert!(world.get_entity_mut(e1).is_ok());
4463 assert!(world.get_entity_mut([e1, e2]).is_ok());
4464 assert!(world
4465 .get_entity_mut(&[e1, e2] /* this is an array not a slice */)
4466 .is_ok());
4467 assert!(world.get_entity_mut(&vec![e1, e2][..]).is_ok());
4468 assert!(world
4469 .get_entity_mut(&EntityHashSet::from_iter([e1, e2]))
4470 .is_ok());
4471
4472 assert_eq!(
4473 Err(EntityMutableFetchError::AliasedMutability(e1)),
4474 world.get_entity_mut([e1, e2, e1]).map(|_| {})
4475 );
4476 assert_eq!(
4477 Err(EntityMutableFetchError::AliasedMutability(e1)),
4478 world
4479 .get_entity_mut(&[e1, e2, e1] /* this is an array not a slice */)
4480 .map(|_| {})
4481 );
4482 assert_eq!(
4483 Err(EntityMutableFetchError::AliasedMutability(e1)),
4484 world.get_entity_mut(&vec![e1, e2, e1][..]).map(|_| {})
4485 );
4486 // Aliased mutability isn't allowed by HashSets
4487 assert!(world
4488 .get_entity_mut(&EntityHashSet::from_iter([e1, e2, e1]))
4489 .is_ok());
4490
4491 world.entity_mut(e1).despawn();
4492 assert!(world.get_entity_mut(e2).is_ok());
4493
4494 assert!(matches!(
4495 world.get_entity_mut(e1).map(|_| {}),
4496 Err(EntityMutableFetchError::NotSpawned(e)) if e.entity() == e1
4497 ));
4498 assert!(matches!(
4499 world.get_entity_mut([e1, e2]).map(|_| {}),
4500 Err(EntityMutableFetchError::NotSpawned(e)) if e.entity() == e1));
4501 assert!(matches!(
4502 world
4503 .get_entity_mut(&[e1, e2] /* this is an array not a slice */)
4504 .map(|_| {}),
4505 Err(EntityMutableFetchError::NotSpawned(e)) if e.entity() == e1));
4506 assert!(matches!(
4507 world.get_entity_mut(&vec![e1, e2][..]).map(|_| {}),
4508 Err(EntityMutableFetchError::NotSpawned(e)) if e.entity() == e1,
4509 ));
4510 assert!(matches!(
4511 world
4512 .get_entity_mut(&EntityHashSet::from_iter([e1, e2]))
4513 .map(|_| {}),
4514 Err(EntityMutableFetchError::NotSpawned(e)) if e.entity() == e1));
4515 }
4516
4517 #[test]
4518 #[track_caller]
4519 fn entity_spawn_despawn_tracking() {
4520 use core::panic::Location;
4521
4522 let mut world = World::new();
4523 let entity = world.spawn_empty().id();
4524 assert_eq!(
4525 world.entities.entity_get_spawned_or_despawned_by(entity),
4526 MaybeLocation::new(Some(Location::caller()))
4527 );
4528 assert_eq!(
4529 world.entities.entity_get_spawn_or_despawn_tick(entity),
4530 Some(world.change_tick())
4531 );
4532 let new = world.despawn_no_free(entity).unwrap();
4533 assert_eq!(
4534 world.entities.entity_get_spawned_or_despawned_by(entity),
4535 MaybeLocation::new(Some(Location::caller()))
4536 );
4537 assert_eq!(
4538 world.entities.entity_get_spawn_or_despawn_tick(entity),
4539 Some(world.change_tick())
4540 );
4541
4542 world.spawn_empty_at(new).unwrap();
4543 assert_eq!(entity.index(), new.index());
4544 assert_eq!(
4545 world.entities.entity_get_spawned_or_despawned_by(entity),
4546 MaybeLocation::new(None)
4547 );
4548 assert_eq!(
4549 world.entities.entity_get_spawn_or_despawn_tick(entity),
4550 None
4551 );
4552 world.despawn(new);
4553 assert_eq!(
4554 world.entities.entity_get_spawned_or_despawned_by(entity),
4555 MaybeLocation::new(None)
4556 );
4557 assert_eq!(
4558 world.entities.entity_get_spawn_or_despawn_tick(entity),
4559 None
4560 );
4561 }
4562
4563 #[test]
4564 fn new_world_has_disabling() {
4565 let mut world = World::new();
4566 world.spawn(Foo);
4567 world.spawn((Foo, Disabled));
4568 assert_eq!(1, world.query::<&Foo>().iter(&world).count());
4569
4570 // If we explicitly remove the resource, no entities should be filtered anymore
4571 world.remove_resource::<DefaultQueryFilters>();
4572 assert_eq!(2, world.query::<&Foo>().iter(&world).count());
4573 }
4574
4575 #[test]
4576 fn entities_and_commands() {
4577 #[derive(Component, PartialEq, Debug)]
4578 struct Foo(u32);
4579
4580 let mut world = World::new();
4581
4582 let eid = world.spawn(Foo(35)).id();
4583
4584 let (mut fetcher, mut commands) = world.entities_and_commands();
4585 let emut = fetcher.get_mut(eid).unwrap();
4586 commands.entity(eid).despawn();
4587 assert_eq!(emut.get::<Foo>().unwrap(), &Foo(35));
4588
4589 world.flush();
4590
4591 assert!(world.get_entity(eid).is_err());
4592 }
4593
4594 #[test]
4595 fn resource_query_after_resource_scope() {
4596 #[derive(Event)]
4597 struct EventA;
4598
4599 #[derive(Resource)]
4600 struct ResourceA;
4601
4602 let mut world = World::default();
4603
4604 world.insert_resource(ResourceA);
4605 world.add_observer(move |_event: On<EventA>, _res: Res<ResourceA>| {});
4606 world.resource_scope(|world, _res: Mut<ResourceA>| {
4607 // since we use commands, this should trigger outside of the resource_scope, so the observer should work.
4608 world.commands().trigger(EventA);
4609 });
4610 }
4611
4612 #[test]
4613 fn entities_and_commands_deferred() {
4614 #[derive(Component, PartialEq, Debug)]
4615 struct Foo(u32);
4616
4617 let mut world = World::new();
4618
4619 let eid = world.spawn(Foo(1)).id();
4620
4621 let mut dworld = DeferredWorld::from(&mut world);
4622
4623 let (mut fetcher, mut commands) = dworld.entities_and_commands();
4624 let emut = fetcher.get_mut(eid).unwrap();
4625 commands.entity(eid).despawn();
4626 assert_eq!(emut.get::<Foo>().unwrap(), &Foo(1));
4627
4628 world.flush();
4629
4630 assert!(world.get_entity(eid).is_err());
4631 }
4632
4633 #[test]
4634 fn resource_scope_ticks() {
4635 #[derive(Resource)]
4636 struct R;
4637
4638 let mut world = World::new();
4639 world.insert_resource(R);
4640 world.resource_scope(|world, r: Mut<R>| {
4641 assert_eq!(world.change_tick(), r.added());
4642 assert_eq!(world.change_tick(), r.last_changed());
4643 world.increment_change_tick();
4644 });
4645 assert_eq!(world.change_tick(), world.resource_ref::<R>().added());
4646 assert_eq!(
4647 world.change_tick(),
4648 world.resource_ref::<R>().last_changed()
4649 );
4650 }
4651}