bevy_ecs/system/commands/
mod.rs

1pub mod command;
2pub mod entity_command;
3
4#[cfg(feature = "std")]
5mod parallel_scope;
6
7pub use command::Command;
8pub use entity_command::EntityCommand;
9
10#[cfg(feature = "std")]
11pub use parallel_scope::*;
12
13use alloc::boxed::Box;
14use core::marker::PhantomData;
15use log::error;
16
17use crate::{
18    self as bevy_ecs,
19    bundle::{Bundle, InsertMode, NoBundleEffect},
20    change_detection::{MaybeLocation, Mut},
21    component::{Component, ComponentId, Mutable},
22    entity::{Entities, Entity, EntityClonerBuilder, EntityDoesNotExistError},
23    error::{ignore, warn, BevyError, CommandWithEntity, ErrorContext, HandleError},
24    event::Event,
25    observer::{Observer, TriggerTargets},
26    resource::Resource,
27    schedule::ScheduleLabel,
28    system::{
29        Deferred, IntoObserverSystem, IntoSystem, RegisteredSystem, SystemId, SystemInput,
30        SystemParamValidationError,
31    },
32    world::{
33        command_queue::RawCommandQueue, unsafe_world_cell::UnsafeWorldCell, CommandQueue,
34        EntityWorldMut, FromWorld, World,
35    },
36};
37
38/// A [`Command`] queue to perform structural changes to the [`World`].
39///
40/// Since each command requires exclusive access to the `World`,
41/// all queued commands are automatically applied in sequence
42/// when the `ApplyDeferred` system runs (see [`ApplyDeferred`] documentation for more details).
43///
44/// Each command can be used to modify the [`World`] in arbitrary ways:
45/// * spawning or despawning entities
46/// * inserting components on new or existing entities
47/// * inserting resources
48/// * etc.
49///
50/// For a version of [`Commands`] that works in parallel contexts (such as
51/// within [`Query::par_iter`](crate::system::Query::par_iter)) see
52/// [`ParallelCommands`]
53///
54/// # Usage
55///
56/// Add `mut commands: Commands` as a function argument to your system to get a
57/// copy of this struct that will be applied the next time a copy of [`ApplyDeferred`] runs.
58/// Commands are almost always used as a [`SystemParam`](crate::system::SystemParam).
59///
60/// ```
61/// # use bevy_ecs::prelude::*;
62/// fn my_system(mut commands: Commands) {
63///    // ...
64/// }
65/// # bevy_ecs::system::assert_is_system(my_system);
66/// ```
67///
68/// # Implementing
69///
70/// Each built-in command is implemented as a separate method, e.g. [`Commands::spawn`].
71/// In addition to the pre-defined command methods, you can add commands with any arbitrary
72/// behavior using [`Commands::queue`], which accepts any type implementing [`Command`].
73///
74/// Since closures and other functions implement this trait automatically, this allows one-shot,
75/// anonymous custom commands.
76///
77/// ```
78/// # use bevy_ecs::prelude::*;
79/// # fn foo(mut commands: Commands) {
80/// // NOTE: type inference fails here, so annotations are required on the closure.
81/// commands.queue(|w: &mut World| {
82///     // Mutate the world however you want...
83/// });
84/// # }
85/// ```
86///
87/// # Error handling
88///
89/// A [`Command`] can return a [`Result`](crate::error::Result),
90/// which will be passed to an [error handler](crate::error) if the `Result` is an error.
91///
92/// The [default error handler](crate::error::default_error_handler) panics.
93/// It can be configured by setting the `GLOBAL_ERROR_HANDLER`.
94///
95/// Alternatively, you can customize the error handler for a specific command
96/// by calling [`Commands::queue_handled`].
97///
98/// The [`error`](crate::error) module provides some simple error handlers for convenience.
99///
100/// [`ApplyDeferred`]: crate::schedule::ApplyDeferred
101pub struct Commands<'w, 's> {
102    queue: InternalQueue<'s>,
103    entities: &'w Entities,
104}
105
106// SAFETY: All commands [`Command`] implement [`Send`]
107unsafe impl Send for Commands<'_, '_> {}
108
109// SAFETY: `Commands` never gives access to the inner commands.
110unsafe impl Sync for Commands<'_, '_> {}
111
112const _: () = {
113    type __StructFieldsAlias<'w, 's> = (Deferred<'s, CommandQueue>, &'w Entities);
114    #[doc(hidden)]
115    pub struct FetchState {
116        state: <__StructFieldsAlias<'static, 'static> as bevy_ecs::system::SystemParam>::State,
117    }
118    // SAFETY: Only reads Entities
119    unsafe impl bevy_ecs::system::SystemParam for Commands<'_, '_> {
120        type State = FetchState;
121
122        type Item<'w, 's> = Commands<'w, 's>;
123
124        fn init_state(
125            world: &mut World,
126            system_meta: &mut bevy_ecs::system::SystemMeta,
127        ) -> Self::State {
128            FetchState {
129                state: <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::init_state(
130                    world,
131                    system_meta,
132                ),
133            }
134        }
135
136        unsafe fn new_archetype(
137            state: &mut Self::State,
138            archetype: &bevy_ecs::archetype::Archetype,
139            system_meta: &mut bevy_ecs::system::SystemMeta,
140        ) {
141            // SAFETY: Caller guarantees the archetype is from the world used in `init_state`
142            unsafe {
143                <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::new_archetype(
144                    &mut state.state,
145                    archetype,
146                    system_meta,
147                );
148            };
149        }
150
151        fn apply(
152            state: &mut Self::State,
153            system_meta: &bevy_ecs::system::SystemMeta,
154            world: &mut World,
155        ) {
156            <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::apply(
157                &mut state.state,
158                system_meta,
159                world,
160            );
161        }
162
163        fn queue(
164            state: &mut Self::State,
165            system_meta: &bevy_ecs::system::SystemMeta,
166            world: bevy_ecs::world::DeferredWorld,
167        ) {
168            <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::queue(
169                &mut state.state,
170                system_meta,
171                world,
172            );
173        }
174
175        #[inline]
176        unsafe fn validate_param(
177            state: &Self::State,
178            system_meta: &bevy_ecs::system::SystemMeta,
179            world: UnsafeWorldCell,
180        ) -> Result<(), SystemParamValidationError> {
181            <(Deferred<CommandQueue>, &Entities) as bevy_ecs::system::SystemParam>::validate_param(
182                &state.state,
183                system_meta,
184                world,
185            )
186        }
187
188        #[inline]
189        unsafe fn get_param<'w, 's>(
190            state: &'s mut Self::State,
191            system_meta: &bevy_ecs::system::SystemMeta,
192            world: UnsafeWorldCell<'w>,
193            change_tick: bevy_ecs::component::Tick,
194        ) -> Self::Item<'w, 's> {
195            let(f0, f1) =  <(Deferred<'s, CommandQueue>, &'w Entities) as bevy_ecs::system::SystemParam>::get_param(&mut state.state, system_meta, world, change_tick);
196            Commands {
197                queue: InternalQueue::CommandQueue(f0),
198                entities: f1,
199            }
200        }
201    }
202    // SAFETY: Only reads Entities
203    unsafe impl<'w, 's> bevy_ecs::system::ReadOnlySystemParam for Commands<'w, 's>
204    where
205        Deferred<'s, CommandQueue>: bevy_ecs::system::ReadOnlySystemParam,
206        &'w Entities: bevy_ecs::system::ReadOnlySystemParam,
207    {
208    }
209};
210
211enum InternalQueue<'s> {
212    CommandQueue(Deferred<'s, CommandQueue>),
213    RawCommandQueue(RawCommandQueue),
214}
215
216impl<'w, 's> Commands<'w, 's> {
217    /// Returns a new `Commands` instance from a [`CommandQueue`] and a [`World`].
218    pub fn new(queue: &'s mut CommandQueue, world: &'w World) -> Self {
219        Self::new_from_entities(queue, &world.entities)
220    }
221
222    /// Returns a new `Commands` instance from a [`CommandQueue`] and an [`Entities`] reference.
223    pub fn new_from_entities(queue: &'s mut CommandQueue, entities: &'w Entities) -> Self {
224        Self {
225            queue: InternalQueue::CommandQueue(Deferred(queue)),
226            entities,
227        }
228    }
229
230    /// Returns a new `Commands` instance from a [`RawCommandQueue`] and an [`Entities`] reference.
231    ///
232    /// This is used when constructing [`Commands`] from a [`DeferredWorld`](crate::world::DeferredWorld).
233    ///
234    /// # Safety
235    ///
236    /// * Caller ensures that `queue` must outlive `'w`
237    pub(crate) unsafe fn new_raw_from_entities(
238        queue: RawCommandQueue,
239        entities: &'w Entities,
240    ) -> Self {
241        Self {
242            queue: InternalQueue::RawCommandQueue(queue),
243            entities,
244        }
245    }
246
247    /// Returns a [`Commands`] with a smaller lifetime.
248    ///
249    /// This is useful if you have `&mut Commands` but need `Commands`.
250    ///
251    /// # Example
252    ///
253    /// ```
254    /// # use bevy_ecs::prelude::*;
255    /// fn my_system(mut commands: Commands) {
256    ///     // We do our initialization in a separate function,
257    ///     // which expects an owned `Commands`.
258    ///     do_initialization(commands.reborrow());
259    ///
260    ///     // Since we only reborrowed the commands instead of moving them, we can still use them.
261    ///     commands.spawn_empty();
262    /// }
263    /// #
264    /// # fn do_initialization(_: Commands) {}
265    /// ```
266    pub fn reborrow(&mut self) -> Commands<'w, '_> {
267        Commands {
268            queue: match &mut self.queue {
269                InternalQueue::CommandQueue(queue) => InternalQueue::CommandQueue(queue.reborrow()),
270                InternalQueue::RawCommandQueue(queue) => {
271                    InternalQueue::RawCommandQueue(queue.clone())
272                }
273            },
274            entities: self.entities,
275        }
276    }
277
278    /// Take all commands from `other` and append them to `self`, leaving `other` empty.
279    pub fn append(&mut self, other: &mut CommandQueue) {
280        match &mut self.queue {
281            InternalQueue::CommandQueue(queue) => queue.bytes.append(&mut other.bytes),
282            InternalQueue::RawCommandQueue(queue) => {
283                // SAFETY: Pointers in `RawCommandQueue` are never null
284                unsafe { queue.bytes.as_mut() }.append(&mut other.bytes);
285            }
286        }
287    }
288
289    /// Spawns a new empty [`Entity`] and returns its corresponding [`EntityCommands`].
290    ///
291    /// # Example
292    ///
293    /// ```
294    /// # use bevy_ecs::prelude::*;
295    /// #[derive(Component)]
296    /// struct Label(&'static str);
297    /// #[derive(Component)]
298    /// struct Strength(u32);
299    /// #[derive(Component)]
300    /// struct Agility(u32);
301    ///
302    /// fn example_system(mut commands: Commands) {
303    ///     // Create a new empty entity.
304    ///     commands.spawn_empty();
305    ///
306    ///     // Create another empty entity.
307    ///     commands.spawn_empty()
308    ///         // Add a new component bundle to the entity.
309    ///         .insert((Strength(1), Agility(2)))
310    ///         // Add a single component to the entity.
311    ///         .insert(Label("hello world"));
312    /// }
313    /// # bevy_ecs::system::assert_is_system(example_system);
314    /// ```
315    ///
316    /// # See also
317    ///
318    /// - [`spawn`](Self::spawn) to spawn an entity with components.
319    /// - [`spawn_batch`](Self::spawn_batch) to spawn many entities
320    ///   with the same combination of components.
321    pub fn spawn_empty(&mut self) -> EntityCommands {
322        let entity = self.entities.reserve_entity();
323        EntityCommands {
324            entity,
325            commands: self.reborrow(),
326        }
327    }
328
329    /// Spawns a new [`Entity`] with the given components
330    /// and returns the entity's corresponding [`EntityCommands`].
331    ///
332    /// To spawn many entities with the same combination of components,
333    /// [`spawn_batch`](Self::spawn_batch) can be used for better performance.
334    ///
335    /// # Example
336    ///
337    /// ```
338    /// # use bevy_ecs::prelude::*;
339    /// #[derive(Component)]
340    /// struct ComponentA(u32);
341    /// #[derive(Component)]
342    /// struct ComponentB(u32);
343    ///
344    /// #[derive(Bundle)]
345    /// struct ExampleBundle {
346    ///     a: ComponentA,
347    ///     b: ComponentB,
348    /// }
349    ///
350    /// fn example_system(mut commands: Commands) {
351    ///     // Create a new entity with a single component.
352    ///     commands.spawn(ComponentA(1));
353    ///
354    ///     // Create a new entity with two components using a "tuple bundle".
355    ///     commands.spawn((ComponentA(2), ComponentB(1)));
356    ///
357    ///     // Create a new entity with a component bundle.
358    ///     commands.spawn(ExampleBundle {
359    ///         a: ComponentA(3),
360    ///         b: ComponentB(2),
361    ///     });
362    /// }
363    /// # bevy_ecs::system::assert_is_system(example_system);
364    /// ```
365    ///
366    /// # See also
367    ///
368    /// - [`spawn_empty`](Self::spawn_empty) to spawn an entity without any components.
369    /// - [`spawn_batch`](Self::spawn_batch) to spawn many entities
370    ///   with the same combination of components.
371    #[track_caller]
372    pub fn spawn<T: Bundle>(&mut self, bundle: T) -> EntityCommands {
373        let mut entity = self.spawn_empty();
374        entity.insert(bundle);
375        entity
376    }
377
378    /// Returns the [`EntityCommands`] for the given [`Entity`].
379    ///
380    /// This method does not guarantee that commands queued by the returned `EntityCommands`
381    /// will be successful, since the entity could be despawned before they are executed.
382    ///
383    /// # Example
384    ///
385    /// ```
386    /// # use bevy_ecs::prelude::*;
387    /// #[derive(Resource)]
388    /// struct PlayerEntity {
389    ///     entity: Entity
390    /// }
391    ///
392    /// #[derive(Component)]
393    /// struct Label(&'static str);
394    ///
395    /// fn example_system(mut commands: Commands, player: Res<PlayerEntity>) {
396    ///     // Get the entity and add a component.
397    ///     commands.entity(player.entity).insert(Label("hello world"));
398    /// }
399    /// # bevy_ecs::system::assert_is_system(example_system);
400    /// ```
401    ///
402    /// # See also
403    ///
404    /// - [`get_entity`](Self::get_entity) for the fallible version.
405    #[inline]
406    #[track_caller]
407    pub fn entity(&mut self, entity: Entity) -> EntityCommands {
408        EntityCommands {
409            entity,
410            commands: self.reborrow(),
411        }
412    }
413
414    /// Returns the [`EntityCommands`] for the requested [`Entity`] if it exists.
415    ///
416    /// This method does not guarantee that commands queued by the returned `EntityCommands`
417    /// will be successful, since the entity could be despawned before they are executed.
418    ///
419    /// # Errors
420    ///
421    /// Returns [`EntityDoesNotExistError`] if the requested entity does not exist.
422    ///
423    /// # Example
424    ///
425    /// ```
426    /// # use bevy_ecs::prelude::*;
427    /// #[derive(Resource)]
428    /// struct PlayerEntity {
429    ///     entity: Entity
430    /// }
431    ///
432    /// #[derive(Component)]
433    /// struct Label(&'static str);
434    ///
435    /// fn example_system(mut commands: Commands, player: Res<PlayerEntity>) -> Result {
436    ///     // Get the entity if it still exists and store the `EntityCommands`.
437    ///     // If it doesn't exist, the `?` operator will propagate the returned error
438    ///     // to the system, and the system will pass it to an error handler.
439    ///     let mut entity_commands = commands.get_entity(player.entity)?;
440    ///
441    ///     // Add a component to the entity.
442    ///     entity_commands.insert(Label("hello world"));
443    ///
444    ///     // Return from the system successfully.
445    ///     Ok(())
446    /// }
447    /// # bevy_ecs::system::assert_is_system(example_system);
448    /// ```
449    ///
450    /// # See also
451    ///
452    /// - [`entity`](Self::entity) for the infallible version.
453    #[inline]
454    #[track_caller]
455    pub fn get_entity(
456        &mut self,
457        entity: Entity,
458    ) -> Result<EntityCommands, EntityDoesNotExistError> {
459        if self.entities.contains(entity) {
460            Ok(EntityCommands {
461                entity,
462                commands: self.reborrow(),
463            })
464        } else {
465            Err(EntityDoesNotExistError::new(entity, self.entities))
466        }
467    }
468
469    /// Spawns multiple entities with the same combination of components,
470    /// based on a batch of [`Bundles`](Bundle).
471    ///
472    /// A batch can be any type that implements [`IntoIterator`] and contains bundles,
473    /// such as a [`Vec<Bundle>`](alloc::vec::Vec) or an array `[Bundle; N]`.
474    ///
475    /// This method is equivalent to iterating the batch
476    /// and calling [`spawn`](Self::spawn) for each bundle,
477    /// but is faster by pre-allocating memory and having exclusive [`World`] access.
478    ///
479    /// # Example
480    ///
481    /// ```
482    /// use bevy_ecs::prelude::*;
483    ///
484    /// #[derive(Component)]
485    /// struct Score(u32);
486    ///
487    /// fn example_system(mut commands: Commands) {
488    ///     commands.spawn_batch([
489    ///         (Name::new("Alice"), Score(0)),
490    ///         (Name::new("Bob"), Score(0)),
491    ///     ]);
492    /// }
493    /// # bevy_ecs::system::assert_is_system(example_system);
494    /// ```
495    ///
496    /// # See also
497    ///
498    /// - [`spawn`](Self::spawn) to spawn an entity with components.
499    /// - [`spawn_empty`](Self::spawn_empty) to spawn an entity without components.
500    #[track_caller]
501    pub fn spawn_batch<I>(&mut self, batch: I)
502    where
503        I: IntoIterator + Send + Sync + 'static,
504        I::Item: Bundle<Effect: NoBundleEffect>,
505    {
506        self.queue(command::spawn_batch(batch));
507    }
508
509    /// Pushes a generic [`Command`] to the command queue.
510    ///
511    /// If the [`Command`] returns a [`Result`],
512    /// it will be handled using the [default error handler](crate::error::default_error_handler).
513    ///
514    /// To use a custom error handler, see [`Commands::queue_handled`].
515    ///
516    /// The command can be:
517    /// - A custom struct that implements [`Command`].
518    /// - A closure or function that matches one of the following signatures:
519    ///   - [`(&mut World)`](World)
520    /// - A built-in command from the [`command`] module.
521    ///
522    /// # Example
523    ///
524    /// ```
525    /// # use bevy_ecs::prelude::*;
526    /// #[derive(Resource, Default)]
527    /// struct Counter(u64);
528    ///
529    /// struct AddToCounter(String);
530    ///
531    /// impl Command<Result> for AddToCounter {
532    ///     fn apply(self, world: &mut World) -> Result {
533    ///         let mut counter = world.get_resource_or_insert_with(Counter::default);
534    ///         let amount: u64 = self.0.parse()?;
535    ///         counter.0 += amount;
536    ///         Ok(())
537    ///     }
538    /// }
539    ///
540    /// fn add_three_to_counter_system(mut commands: Commands) {
541    ///     commands.queue(AddToCounter("3".to_string()));
542    /// }
543    ///
544    /// fn add_twenty_five_to_counter_system(mut commands: Commands) {
545    ///     commands.queue(|world: &mut World| {
546    ///         let mut counter = world.get_resource_or_insert_with(Counter::default);
547    ///         counter.0 += 25;
548    ///     });
549    /// }
550    /// # bevy_ecs::system::assert_is_system(add_three_to_counter_system);
551    /// # bevy_ecs::system::assert_is_system(add_twenty_five_to_counter_system);
552    /// ```
553    pub fn queue<C: Command<T> + HandleError<T>, T>(&mut self, command: C) {
554        self.queue_internal(command.handle_error());
555    }
556
557    /// Pushes a generic [`Command`] to the command queue.
558    ///
559    /// If the [`Command`] returns a [`Result`],
560    /// the given `error_handler` will be used to handle error cases.
561    ///
562    /// To implicitly use the default error handler, see [`Commands::queue`].
563    ///
564    /// The command can be:
565    /// - A custom struct that implements [`Command`].
566    /// - A closure or function that matches one of the following signatures:
567    ///   - [`(&mut World)`](World)
568    ///   - [`(&mut World)`](World) `->` [`Result`]
569    /// - A built-in command from the [`command`] module.
570    ///
571    /// # Example
572    ///
573    /// ```
574    /// # use bevy_ecs::prelude::*;
575    /// use bevy_ecs::error::warn;
576    ///
577    /// #[derive(Resource, Default)]
578    /// struct Counter(u64);
579    ///
580    /// struct AddToCounter(String);
581    ///
582    /// impl Command<Result> for AddToCounter {
583    ///     fn apply(self, world: &mut World) -> Result {
584    ///         let mut counter = world.get_resource_or_insert_with(Counter::default);
585    ///         let amount: u64 = self.0.parse()?;
586    ///         counter.0 += amount;
587    ///         Ok(())
588    ///     }
589    /// }
590    ///
591    /// fn add_three_to_counter_system(mut commands: Commands) {
592    ///     commands.queue_handled(AddToCounter("3".to_string()), warn);
593    /// }
594    ///
595    /// fn add_twenty_five_to_counter_system(mut commands: Commands) {
596    ///     commands.queue(|world: &mut World| {
597    ///         let mut counter = world.get_resource_or_insert_with(Counter::default);
598    ///         counter.0 += 25;
599    ///     });
600    /// }
601    /// # bevy_ecs::system::assert_is_system(add_three_to_counter_system);
602    /// # bevy_ecs::system::assert_is_system(add_twenty_five_to_counter_system);
603    /// ```
604    pub fn queue_handled<C: Command<T> + HandleError<T>, T>(
605        &mut self,
606        command: C,
607        error_handler: fn(BevyError, ErrorContext),
608    ) {
609        self.queue_internal(command.handle_error_with(error_handler));
610    }
611
612    fn queue_internal(&mut self, command: impl Command) {
613        match &mut self.queue {
614            InternalQueue::CommandQueue(queue) => {
615                queue.push(command);
616            }
617            InternalQueue::RawCommandQueue(queue) => {
618                // SAFETY: `RawCommandQueue` is only every constructed in `Commands::new_raw_from_entities`
619                // where the caller of that has ensured that `queue` outlives `self`
620                unsafe {
621                    queue.push(command);
622                }
623            }
624        }
625    }
626
627    /// Pushes a [`Command`] to the queue for creating entities, if needed,
628    /// and for adding a bundle to each entity.
629    ///
630    /// `bundles_iter` is a type that can be converted into an ([`Entity`], [`Bundle`]) iterator
631    /// (it can also be a collection).
632    ///
633    /// When the command is applied,
634    /// for each (`Entity`, `Bundle`) pair in the given `bundles_iter`,
635    /// the `Entity` is spawned, if it does not exist already.
636    /// Then, the `Bundle` is added to the entity.
637    ///
638    /// This method is equivalent to iterating `bundles_iter`,
639    /// calling [`spawn`](Self::spawn) for each bundle,
640    /// and passing it to [`insert`](EntityCommands::insert),
641    /// but it is faster due to memory pre-allocation.
642    ///
643    /// # Note
644    ///
645    /// Spawning a specific `entity` value is rarely the right choice. Most apps should use [`Commands::spawn_batch`].
646    /// This method should generally only be used for sharing entities across apps, and only when they have a scheme
647    /// worked out to share an ID space (which doesn't happen by default).
648    #[track_caller]
649    #[deprecated(
650        since = "0.16.0",
651        note = "This can cause extreme performance problems when used with lots of arbitrary free entities. See #18054 on GitHub."
652    )]
653    pub fn insert_or_spawn_batch<I, B>(&mut self, bundles_iter: I)
654    where
655        I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static,
656        B: Bundle<Effect: NoBundleEffect>,
657    {
658        let caller = MaybeLocation::caller();
659        self.queue(move |world: &mut World| {
660
661            #[expect(
662                deprecated,
663                reason = "This needs to be supported for now, and the outer item is deprecated too."
664            )]
665            if let Err(invalid_entities) = world.insert_or_spawn_batch_with_caller(
666                bundles_iter,
667                caller,
668            ) {
669                error!(
670                    "{caller}: Failed to 'insert or spawn' bundle of type {} into the following invalid entities: {:?}",
671                    core::any::type_name::<B>(),
672                    invalid_entities
673                );
674            }
675        });
676    }
677
678    /// Adds a series of [`Bundles`](Bundle) to each [`Entity`] they are paired with,
679    /// based on a batch of `(Entity, Bundle)` pairs.
680    ///
681    /// A batch can be any type that implements [`IntoIterator`]
682    /// and contains `(Entity, Bundle)` tuples,
683    /// such as a [`Vec<(Entity, Bundle)>`](alloc::vec::Vec)
684    /// or an array `[(Entity, Bundle); N]`.
685    ///
686    /// This will overwrite any pre-existing components shared by the [`Bundle`] type.
687    /// Use [`Commands::insert_batch_if_new`] to keep the pre-existing components instead.
688    ///
689    /// This method is equivalent to iterating the batch
690    /// and calling [`insert`](EntityCommands::insert) for each pair,
691    /// but is faster by caching data that is shared between entities.
692    ///
693    /// # Fallible
694    ///
695    /// This command will fail if any of the given entities do not exist.
696    ///
697    /// It will internally return a [`TryInsertBatchError`](crate::world::error::TryInsertBatchError),
698    /// which will be handled by the [default error handler](crate::error::default_error_handler).
699    #[track_caller]
700    pub fn insert_batch<I, B>(&mut self, batch: I)
701    where
702        I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static,
703        B: Bundle<Effect: NoBundleEffect>,
704    {
705        self.queue(command::insert_batch(batch, InsertMode::Replace));
706    }
707
708    /// Adds a series of [`Bundles`](Bundle) to each [`Entity`] they are paired with,
709    /// based on a batch of `(Entity, Bundle)` pairs.
710    ///
711    /// A batch can be any type that implements [`IntoIterator`]
712    /// and contains `(Entity, Bundle)` tuples,
713    /// such as a [`Vec<(Entity, Bundle)>`](alloc::vec::Vec)
714    /// or an array `[(Entity, Bundle); N]`.
715    ///
716    /// This will keep any pre-existing components shared by the [`Bundle`] type
717    /// and discard the new values.
718    /// Use [`Commands::insert_batch`] to overwrite the pre-existing components instead.
719    ///
720    /// This method is equivalent to iterating the batch
721    /// and calling [`insert_if_new`](EntityCommands::insert_if_new) for each pair,
722    /// but is faster by caching data that is shared between entities.
723    ///
724    /// # Fallible
725    ///
726    /// This command will fail if any of the given entities do not exist.
727    ///
728    /// It will internally return a [`TryInsertBatchError`](crate::world::error::TryInsertBatchError),
729    /// which will be handled by the [default error handler](crate::error::default_error_handler).
730    #[track_caller]
731    pub fn insert_batch_if_new<I, B>(&mut self, batch: I)
732    where
733        I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static,
734        B: Bundle<Effect: NoBundleEffect>,
735    {
736        self.queue(command::insert_batch(batch, InsertMode::Keep));
737    }
738
739    /// Adds a series of [`Bundles`](Bundle) to each [`Entity`] they are paired with,
740    /// based on a batch of `(Entity, Bundle)` pairs.
741    ///
742    /// A batch can be any type that implements [`IntoIterator`]
743    /// and contains `(Entity, Bundle)` tuples,
744    /// such as a [`Vec<(Entity, Bundle)>`](alloc::vec::Vec)
745    /// or an array `[(Entity, Bundle); N]`.
746    ///
747    /// This will overwrite any pre-existing components shared by the [`Bundle`] type.
748    /// Use [`Commands::try_insert_batch_if_new`] to keep the pre-existing components instead.
749    ///
750    /// This method is equivalent to iterating the batch
751    /// and calling [`insert`](EntityCommands::insert) for each pair,
752    /// but is faster by caching data that is shared between entities.
753    ///
754    /// # Fallible
755    ///
756    /// This command will fail if any of the given entities do not exist.
757    ///
758    /// It will internally return a [`TryInsertBatchError`](crate::world::error::TryInsertBatchError),
759    /// which will be handled by [logging the error at the `warn` level](warn).
760    #[track_caller]
761    pub fn try_insert_batch<I, B>(&mut self, batch: I)
762    where
763        I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static,
764        B: Bundle<Effect: NoBundleEffect>,
765    {
766        self.queue(command::insert_batch(batch, InsertMode::Replace).handle_error_with(warn));
767    }
768
769    /// Adds a series of [`Bundles`](Bundle) to each [`Entity`] they are paired with,
770    /// based on a batch of `(Entity, Bundle)` pairs.
771    ///
772    /// A batch can be any type that implements [`IntoIterator`]
773    /// and contains `(Entity, Bundle)` tuples,
774    /// such as a [`Vec<(Entity, Bundle)>`](alloc::vec::Vec)
775    /// or an array `[(Entity, Bundle); N]`.
776    ///
777    /// This will keep any pre-existing components shared by the [`Bundle`] type
778    /// and discard the new values.
779    /// Use [`Commands::try_insert_batch`] to overwrite the pre-existing components instead.
780    ///
781    /// This method is equivalent to iterating the batch
782    /// and calling [`insert_if_new`](EntityCommands::insert_if_new) for each pair,
783    /// but is faster by caching data that is shared between entities.
784    ///
785    /// # Fallible
786    ///
787    /// This command will fail if any of the given entities do not exist.
788    ///
789    /// It will internally return a [`TryInsertBatchError`](crate::world::error::TryInsertBatchError),
790    /// which will be handled by [logging the error at the `warn` level](warn).
791    #[track_caller]
792    pub fn try_insert_batch_if_new<I, B>(&mut self, batch: I)
793    where
794        I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static,
795        B: Bundle<Effect: NoBundleEffect>,
796    {
797        self.queue(command::insert_batch(batch, InsertMode::Keep).handle_error_with(warn));
798    }
799
800    /// Inserts a [`Resource`] into the [`World`] with an inferred value.
801    ///
802    /// The inferred value is determined by the [`FromWorld`] trait of the resource.
803    /// Note that any resource with the [`Default`] trait automatically implements [`FromWorld`],
804    /// and those default values will be used.
805    ///
806    /// If the resource already exists when the command is applied, nothing happens.
807    ///
808    /// # Example
809    ///
810    /// ```
811    /// # use bevy_ecs::prelude::*;
812    /// #[derive(Resource, Default)]
813    /// struct Scoreboard {
814    ///     current_score: u32,
815    ///     high_score: u32,
816    /// }
817    ///
818    /// fn initialize_scoreboard(mut commands: Commands) {
819    ///     commands.init_resource::<Scoreboard>();
820    /// }
821    /// # bevy_ecs::system::assert_is_system(initialize_scoreboard);
822    /// ```
823    #[track_caller]
824    pub fn init_resource<R: Resource + FromWorld>(&mut self) {
825        self.queue(command::init_resource::<R>());
826    }
827
828    /// Inserts a [`Resource`] into the [`World`] with a specific value.
829    ///
830    /// This will overwrite any previous value of the same resource type.
831    ///
832    /// # Example
833    ///
834    /// ```
835    /// # use bevy_ecs::prelude::*;
836    /// #[derive(Resource)]
837    /// struct Scoreboard {
838    ///     current_score: u32,
839    ///     high_score: u32,
840    /// }
841    ///
842    /// fn system(mut commands: Commands) {
843    ///     commands.insert_resource(Scoreboard {
844    ///         current_score: 0,
845    ///         high_score: 0,
846    ///     });
847    /// }
848    /// # bevy_ecs::system::assert_is_system(system);
849    /// ```
850    #[track_caller]
851    pub fn insert_resource<R: Resource>(&mut self, resource: R) {
852        self.queue(command::insert_resource(resource));
853    }
854
855    /// Removes a [`Resource`] from the [`World`].
856    ///
857    /// # Example
858    ///
859    /// ```
860    /// # use bevy_ecs::prelude::*;
861    /// #[derive(Resource)]
862    /// struct Scoreboard {
863    ///     current_score: u32,
864    ///     high_score: u32,
865    /// }
866    ///
867    /// fn system(mut commands: Commands) {
868    ///     commands.remove_resource::<Scoreboard>();
869    /// }
870    /// # bevy_ecs::system::assert_is_system(system);
871    /// ```
872    pub fn remove_resource<R: Resource>(&mut self) {
873        self.queue(command::remove_resource::<R>());
874    }
875
876    /// Runs the system corresponding to the given [`SystemId`].
877    /// Before running a system, it must first be registered via
878    /// [`Commands::register_system`] or [`World::register_system`].
879    ///
880    /// The system is run in an exclusive and single-threaded way.
881    /// Running slow systems can become a bottleneck.
882    ///
883    /// There is no way to get the output of a system when run as a command, because the
884    /// execution of the system happens later. To get the output of a system, use
885    /// [`World::run_system`] or [`World::run_system_with`] instead of running the system as a command.
886    ///
887    /// # Fallible
888    ///
889    /// This command will fail if the given [`SystemId`]
890    /// does not correspond to a [`System`](crate::system::System).
891    ///
892    /// It will internally return a [`RegisteredSystemError`](crate::system::system_registry::RegisteredSystemError),
893    /// which will be handled by [logging the error at the `warn` level](warn).
894    pub fn run_system(&mut self, id: SystemId) {
895        self.queue(command::run_system(id).handle_error_with(warn));
896    }
897
898    /// Runs the system corresponding to the given [`SystemId`] with input.
899    /// Before running a system, it must first be registered via
900    /// [`Commands::register_system`] or [`World::register_system`].
901    ///
902    /// The system is run in an exclusive and single-threaded way.
903    /// Running slow systems can become a bottleneck.
904    ///
905    /// There is no way to get the output of a system when run as a command, because the
906    /// execution of the system happens later. To get the output of a system, use
907    /// [`World::run_system`] or [`World::run_system_with`] instead of running the system as a command.
908    ///
909    /// # Fallible
910    ///
911    /// This command will fail if the given [`SystemId`]
912    /// does not correspond to a [`System`](crate::system::System).
913    ///
914    /// It will internally return a [`RegisteredSystemError`](crate::system::system_registry::RegisteredSystemError),
915    /// which will be handled by [logging the error at the `warn` level](warn).
916    pub fn run_system_with<I>(&mut self, id: SystemId<I>, input: I::Inner<'static>)
917    where
918        I: SystemInput<Inner<'static>: Send> + 'static,
919    {
920        self.queue(command::run_system_with(id, input).handle_error_with(warn));
921    }
922
923    /// Registers a system and returns its [`SystemId`] so it can later be called by
924    /// [`Commands::run_system`] or [`World::run_system`].
925    ///
926    /// This is different from adding systems to a [`Schedule`](crate::schedule::Schedule),
927    /// because the [`SystemId`] that is returned can be used anywhere in the [`World`] to run the associated system.
928    ///
929    /// Using a [`Schedule`](crate::schedule::Schedule) is still preferred for most cases
930    /// due to its better performance and ability to run non-conflicting systems simultaneously.
931    ///
932    /// # Note
933    ///
934    /// If the same system is registered more than once,
935    /// each registration will be considered a different system,
936    /// and they will each be given their own [`SystemId`].
937    ///
938    /// If you want to avoid registering the same system multiple times,
939    /// consider using [`Commands::run_system_cached`] or storing the [`SystemId`]
940    /// in a [`Local`](crate::system::Local).
941    ///
942    /// # Example
943    ///
944    /// ```
945    /// # use bevy_ecs::{prelude::*, world::CommandQueue, system::SystemId};
946    /// #[derive(Resource)]
947    /// struct Counter(i32);
948    ///
949    /// fn register_system(
950    ///     mut commands: Commands,
951    ///     mut local_system: Local<Option<SystemId>>,
952    /// ) {
953    ///     if let Some(system) = *local_system {
954    ///         commands.run_system(system);
955    ///     } else {
956    ///         *local_system = Some(commands.register_system(increment_counter));
957    ///     }
958    /// }
959    ///
960    /// fn increment_counter(mut value: ResMut<Counter>) {
961    ///     value.0 += 1;
962    /// }
963    ///
964    /// # let mut world = World::default();
965    /// # world.insert_resource(Counter(0));
966    /// # let mut queue_1 = CommandQueue::default();
967    /// # let systemid = {
968    /// #   let mut commands = Commands::new(&mut queue_1, &world);
969    /// #   commands.register_system(increment_counter)
970    /// # };
971    /// # let mut queue_2 = CommandQueue::default();
972    /// # {
973    /// #   let mut commands = Commands::new(&mut queue_2, &world);
974    /// #   commands.run_system(systemid);
975    /// # }
976    /// # queue_1.append(&mut queue_2);
977    /// # queue_1.apply(&mut world);
978    /// # assert_eq!(1, world.resource::<Counter>().0);
979    /// # bevy_ecs::system::assert_is_system(register_system);
980    /// ```
981    pub fn register_system<I, O, M>(
982        &mut self,
983        system: impl IntoSystem<I, O, M> + 'static,
984    ) -> SystemId<I, O>
985    where
986        I: SystemInput + Send + 'static,
987        O: Send + 'static,
988    {
989        let entity = self.spawn_empty().id();
990        let system = RegisteredSystem::<I, O>::new(Box::new(IntoSystem::into_system(system)));
991        self.entity(entity).insert(system);
992        SystemId::from_entity(entity)
993    }
994
995    /// Removes a system previously registered with [`Commands::register_system`]
996    /// or [`World::register_system`].
997    ///
998    /// After removing a system, the [`SystemId`] becomes invalid
999    /// and attempting to use it afterwards will result in an error.
1000    /// Re-adding the removed system will register it with a new `SystemId`.
1001    ///
1002    /// # Fallible
1003    ///
1004    /// This command will fail if the given [`SystemId`]
1005    /// does not correspond to a [`System`](crate::system::System).
1006    ///
1007    /// It will internally return a [`RegisteredSystemError`](crate::system::system_registry::RegisteredSystemError),
1008    /// which will be handled by [logging the error at the `warn` level](warn).
1009    pub fn unregister_system<I, O>(&mut self, system_id: SystemId<I, O>)
1010    where
1011        I: SystemInput + Send + 'static,
1012        O: Send + 'static,
1013    {
1014        self.queue(command::unregister_system(system_id).handle_error_with(warn));
1015    }
1016
1017    /// Removes a system previously registered with one of the following:
1018    /// - [`Commands::run_system_cached`]
1019    /// - [`World::run_system_cached`]
1020    /// - [`World::register_system_cached`]
1021    ///
1022    /// # Fallible
1023    ///
1024    /// This command will fail if the given system
1025    /// is not currently cached in a [`CachedSystemId`](crate::system::CachedSystemId) resource.
1026    ///
1027    /// It will internally return a [`RegisteredSystemError`](crate::system::system_registry::RegisteredSystemError),
1028    /// which will be handled by [logging the error at the `warn` level](warn).
1029    pub fn unregister_system_cached<I, O, M, S>(&mut self, system: S)
1030    where
1031        I: SystemInput + Send + 'static,
1032        O: 'static,
1033        M: 'static,
1034        S: IntoSystem<I, O, M> + Send + 'static,
1035    {
1036        self.queue(command::unregister_system_cached(system).handle_error_with(warn));
1037    }
1038
1039    /// Runs a cached system, registering it if necessary.
1040    ///
1041    /// Unlike [`Commands::run_system`], this method does not require manual registration.
1042    ///
1043    /// The first time this method is called for a particular system,
1044    /// it will register the system and store its [`SystemId`] in a
1045    /// [`CachedSystemId`](crate::system::CachedSystemId) resource for later.
1046    ///
1047    /// If you would rather manage the [`SystemId`] yourself,
1048    /// or register multiple copies of the same system,
1049    /// use [`Commands::register_system`] instead.
1050    ///
1051    /// # Limitations
1052    ///
1053    /// This method only accepts ZST (zero-sized) systems to guarantee that any two systems of
1054    /// the same type must be equal. This means that closures that capture the environment, and
1055    /// function pointers, are not accepted.
1056    ///
1057    /// If you want to access values from the environment within a system,
1058    /// consider passing them in as inputs via [`Commands::run_system_cached_with`].
1059    ///
1060    /// If that's not an option, consider [`Commands::register_system`] instead.
1061    pub fn run_system_cached<M, S>(&mut self, system: S)
1062    where
1063        M: 'static,
1064        S: IntoSystem<(), (), M> + Send + 'static,
1065    {
1066        self.queue(command::run_system_cached(system).handle_error_with(warn));
1067    }
1068
1069    /// Runs a cached system with an input, registering it if necessary.
1070    ///
1071    /// Unlike [`Commands::run_system_with`], this method does not require manual registration.
1072    ///
1073    /// The first time this method is called for a particular system,
1074    /// it will register the system and store its [`SystemId`] in a
1075    /// [`CachedSystemId`](crate::system::CachedSystemId) resource for later.
1076    ///
1077    /// If you would rather manage the [`SystemId`] yourself,
1078    /// or register multiple copies of the same system,
1079    /// use [`Commands::register_system`] instead.
1080    ///
1081    /// # Limitations
1082    ///
1083    /// This method only accepts ZST (zero-sized) systems to guarantee that any two systems of
1084    /// the same type must be equal. This means that closures that capture the environment, and
1085    /// function pointers, are not accepted.
1086    ///
1087    /// If you want to access values from the environment within a system,
1088    /// consider passing them in as inputs.
1089    ///
1090    /// If that's not an option, consider [`Commands::register_system`] instead.
1091    pub fn run_system_cached_with<I, M, S>(&mut self, system: S, input: I::Inner<'static>)
1092    where
1093        I: SystemInput<Inner<'static>: Send> + Send + 'static,
1094        M: 'static,
1095        S: IntoSystem<I, (), M> + Send + 'static,
1096    {
1097        self.queue(command::run_system_cached_with(system, input).handle_error_with(warn));
1098    }
1099
1100    /// Sends a "global" [`Trigger`](crate::observer::Trigger) without any targets.
1101    ///
1102    /// This will run any [`Observer`] of the given [`Event`] that isn't scoped to specific targets.
1103    #[track_caller]
1104    pub fn trigger(&mut self, event: impl Event) {
1105        self.queue(command::trigger(event));
1106    }
1107
1108    /// Sends a [`Trigger`](crate::observer::Trigger) for the given targets.
1109    ///
1110    /// This will run any [`Observer`] of the given [`Event`] watching those targets.
1111    #[track_caller]
1112    pub fn trigger_targets(
1113        &mut self,
1114        event: impl Event,
1115        targets: impl TriggerTargets + Send + Sync + 'static,
1116    ) {
1117        self.queue(command::trigger_targets(event, targets));
1118    }
1119
1120    /// Spawns an [`Observer`] and returns the [`EntityCommands`] associated
1121    /// with the entity that stores the observer.
1122    ///
1123    /// **Calling [`observe`](EntityCommands::observe) on the returned
1124    /// [`EntityCommands`] will observe the observer itself, which you very
1125    /// likely do not want.**
1126    pub fn add_observer<E: Event, B: Bundle, M>(
1127        &mut self,
1128        observer: impl IntoObserverSystem<E, B, M>,
1129    ) -> EntityCommands {
1130        self.spawn(Observer::new(observer))
1131    }
1132
1133    /// Sends an arbitrary [`Event`].
1134    ///
1135    /// This is a convenience method for sending events
1136    /// without requiring an [`EventWriter`](crate::event::EventWriter).
1137    ///
1138    /// # Performance
1139    ///
1140    /// Since this is a command, exclusive world access is used, which means that it will not profit from
1141    /// system-level parallelism on supported platforms.
1142    ///
1143    /// If these events are performance-critical or very frequently sent,
1144    /// consider using a typed [`EventWriter`](crate::event::EventWriter) instead.
1145    #[track_caller]
1146    pub fn send_event<E: Event>(&mut self, event: E) -> &mut Self {
1147        self.queue(command::send_event(event));
1148        self
1149    }
1150
1151    /// Runs the schedule corresponding to the given [`ScheduleLabel`].
1152    ///
1153    /// Calls [`World::try_run_schedule`](World::try_run_schedule).
1154    ///
1155    /// # Fallible
1156    ///
1157    /// This command will fail if the given [`ScheduleLabel`]
1158    /// does not correspond to a [`Schedule`](crate::schedule::Schedule).
1159    ///
1160    /// It will internally return a [`TryRunScheduleError`](crate::world::error::TryRunScheduleError),
1161    /// which will be handled by [logging the error at the `warn` level](warn).
1162    ///
1163    /// # Example
1164    ///
1165    /// ```
1166    /// # use bevy_ecs::prelude::*;
1167    /// # use bevy_ecs::schedule::ScheduleLabel;
1168    /// # #[derive(Default, Resource)]
1169    /// # struct Counter(u32);
1170    /// #[derive(ScheduleLabel, Hash, Debug, PartialEq, Eq, Clone, Copy)]
1171    /// struct FooSchedule;
1172    ///
1173    /// # fn foo_system(mut counter: ResMut<Counter>) {
1174    /// #     counter.0 += 1;
1175    /// # }
1176    /// #
1177    /// # let mut schedule = Schedule::new(FooSchedule);
1178    /// # schedule.add_systems(foo_system);
1179    /// #
1180    /// # let mut world = World::default();
1181    /// #
1182    /// # world.init_resource::<Counter>();
1183    /// # world.add_schedule(schedule);
1184    /// #
1185    /// # assert_eq!(world.resource::<Counter>().0, 0);
1186    /// #
1187    /// # let mut commands = world.commands();
1188    /// commands.run_schedule(FooSchedule);
1189    /// #
1190    /// # world.flush();
1191    /// #
1192    /// # assert_eq!(world.resource::<Counter>().0, 1);
1193    /// ```
1194    pub fn run_schedule(&mut self, label: impl ScheduleLabel) {
1195        self.queue(command::run_schedule(label).handle_error_with(warn));
1196    }
1197}
1198
1199/// A list of commands that will be run to modify an [`Entity`].
1200///
1201/// # Note
1202///
1203/// Most [`Commands`] (and thereby [`EntityCommands`]) are deferred:
1204/// when you call the command, if it requires mutable access to the [`World`]
1205/// (that is, if it removes, adds, or changes something), it's not executed immediately.
1206///
1207/// Instead, the command is added to a "command queue."
1208/// The command queue is applied later
1209/// when the [`ApplyDeferred`](crate::schedule::ApplyDeferred) system runs.
1210/// Commands are executed one-by-one so that
1211/// each command can have exclusive access to the `World`.
1212///
1213/// # Fallible
1214///
1215/// Due to their deferred nature, an entity you're trying to change with an [`EntityCommand`]
1216/// can be despawned by the time the command is executed.
1217///
1218/// All deferred entity commands will check whether the entity exists at the time of execution
1219/// and will return an error if it doesn't.
1220///
1221/// # Error handling
1222///
1223/// An [`EntityCommand`] can return a [`Result`](crate::error::Result),
1224/// which will be passed to an [error handler](crate::error) if the `Result` is an error.
1225///
1226/// The [default error handler](crate::error::default_error_handler) panics.
1227/// It can be configured by setting the `GLOBAL_ERROR_HANDLER`.
1228///
1229/// Alternatively, you can customize the error handler for a specific command
1230/// by calling [`EntityCommands::queue_handled`].
1231///
1232/// The [`error`](crate::error) module provides some simple error handlers for convenience.
1233pub struct EntityCommands<'a> {
1234    pub(crate) entity: Entity,
1235    pub(crate) commands: Commands<'a, 'a>,
1236}
1237
1238impl<'a> EntityCommands<'a> {
1239    /// Returns the [`Entity`] id of the entity.
1240    ///
1241    /// # Example
1242    ///
1243    /// ```
1244    /// # use bevy_ecs::prelude::*;
1245    /// #
1246    /// fn my_system(mut commands: Commands) {
1247    ///     let entity_id = commands.spawn_empty().id();
1248    /// }
1249    /// # bevy_ecs::system::assert_is_system(my_system);
1250    /// ```
1251    #[inline]
1252    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
1253    pub fn id(&self) -> Entity {
1254        self.entity
1255    }
1256
1257    /// Returns an [`EntityCommands`] with a smaller lifetime.
1258    ///
1259    /// This is useful if you have `&mut EntityCommands` but you need `EntityCommands`.
1260    pub fn reborrow(&mut self) -> EntityCommands {
1261        EntityCommands {
1262            entity: self.entity,
1263            commands: self.commands.reborrow(),
1264        }
1265    }
1266
1267    /// Get an [`EntityEntryCommands`] for the [`Component`] `T`,
1268    /// allowing you to modify it or insert it if it isn't already present.
1269    ///
1270    /// See also [`insert_if_new`](Self::insert_if_new),
1271    /// which lets you insert a [`Bundle`] without overwriting it.
1272    ///
1273    /// # Example
1274    ///
1275    /// ```
1276    /// # use bevy_ecs::prelude::*;
1277    /// # #[derive(Resource)]
1278    /// # struct PlayerEntity { entity: Entity }
1279    /// #[derive(Component)]
1280    /// struct Level(u32);
1281    ///
1282    /// fn level_up_system(mut commands: Commands, player: Res<PlayerEntity>) {
1283    ///     commands
1284    ///         .entity(player.entity)
1285    ///         .entry::<Level>()
1286    ///         // Modify the component if it exists.
1287    ///         .and_modify(|mut lvl| lvl.0 += 1)
1288    ///         // Otherwise, insert a default value.
1289    ///         .or_insert(Level(0));
1290    /// }
1291    /// # bevy_ecs::system::assert_is_system(level_up_system);
1292    /// ```
1293    pub fn entry<T: Component>(&mut self) -> EntityEntryCommands<T> {
1294        EntityEntryCommands {
1295            entity_commands: self.reborrow(),
1296            marker: PhantomData,
1297        }
1298    }
1299
1300    /// Adds a [`Bundle`] of components to the entity.
1301    ///
1302    /// This will overwrite any previous value(s) of the same component type.
1303    /// See [`EntityCommands::insert_if_new`] to keep the old value instead.
1304    ///
1305    /// # Example
1306    ///
1307    /// ```
1308    /// # use bevy_ecs::prelude::*;
1309    /// # #[derive(Resource)]
1310    /// # struct PlayerEntity { entity: Entity }
1311    /// #[derive(Component)]
1312    /// struct Health(u32);
1313    /// #[derive(Component)]
1314    /// struct Strength(u32);
1315    /// #[derive(Component)]
1316    /// struct Defense(u32);
1317    ///
1318    /// #[derive(Bundle)]
1319    /// struct CombatBundle {
1320    ///     health: Health,
1321    ///     strength: Strength,
1322    /// }
1323    ///
1324    /// fn add_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
1325    ///     commands
1326    ///         .entity(player.entity)
1327    ///         // You can insert individual components:
1328    ///         .insert(Defense(10))
1329    ///         // You can also insert pre-defined bundles of components:
1330    ///         .insert(CombatBundle {
1331    ///             health: Health(100),
1332    ///             strength: Strength(40),
1333    ///         })
1334    ///         // You can also insert tuples of components and bundles.
1335    ///         // This is equivalent to the calls above:
1336    ///         .insert((
1337    ///             Defense(10),
1338    ///             CombatBundle {
1339    ///                 health: Health(100),
1340    ///                 strength: Strength(40),
1341    ///             },
1342    ///         ));
1343    /// }
1344    /// # bevy_ecs::system::assert_is_system(add_combat_stats_system);
1345    /// ```
1346    #[track_caller]
1347    pub fn insert(&mut self, bundle: impl Bundle) -> &mut Self {
1348        self.queue(entity_command::insert(bundle, InsertMode::Replace))
1349    }
1350
1351    /// Adds a [`Bundle`] of components to the entity if the predicate returns true.
1352    ///
1353    /// This is useful for chaining method calls.
1354    ///
1355    /// # Example
1356    ///
1357    /// ```
1358    /// # use bevy_ecs::prelude::*;
1359    /// # #[derive(Resource)]
1360    /// # struct PlayerEntity { entity: Entity }
1361    /// # impl PlayerEntity { fn is_spectator(&self) -> bool { true } }
1362    /// #[derive(Component)]
1363    /// struct StillLoadingStats;
1364    /// #[derive(Component)]
1365    /// struct Health(u32);
1366    ///
1367    /// fn add_health_system(mut commands: Commands, player: Res<PlayerEntity>) {
1368    ///     commands
1369    ///         .entity(player.entity)
1370    ///         .insert_if(Health(10), || !player.is_spectator())
1371    ///         .remove::<StillLoadingStats>();
1372    /// }
1373    /// # bevy_ecs::system::assert_is_system(add_health_system);
1374    /// ```
1375    #[track_caller]
1376    pub fn insert_if<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
1377    where
1378        F: FnOnce() -> bool,
1379    {
1380        if condition() {
1381            self.insert(bundle)
1382        } else {
1383            self
1384        }
1385    }
1386
1387    /// Adds a [`Bundle`] of components to the entity without overwriting.
1388    ///
1389    /// This is the same as [`EntityCommands::insert`], but in case of duplicate
1390    /// components will leave the old values instead of replacing them with new ones.
1391    ///
1392    /// See also [`entry`](Self::entry), which lets you modify a [`Component`] if it's present,
1393    /// as well as initialize it with a default value.
1394    #[track_caller]
1395    pub fn insert_if_new(&mut self, bundle: impl Bundle) -> &mut Self {
1396        self.queue(entity_command::insert(bundle, InsertMode::Keep))
1397    }
1398
1399    /// Adds a [`Bundle`] of components to the entity without overwriting if the
1400    /// predicate returns true.
1401    ///
1402    /// This is the same as [`EntityCommands::insert_if`], but in case of duplicate
1403    /// components will leave the old values instead of replacing them with new ones.
1404    #[track_caller]
1405    pub fn insert_if_new_and<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
1406    where
1407        F: FnOnce() -> bool,
1408    {
1409        if condition() {
1410            self.insert_if_new(bundle)
1411        } else {
1412            self
1413        }
1414    }
1415
1416    /// Adds a dynamic [`Component`] to the entity.
1417    ///
1418    /// This will overwrite any previous value(s) of the same component type.
1419    ///
1420    /// You should prefer to use the typed API [`EntityCommands::insert`] where possible.
1421    ///
1422    /// # Safety
1423    ///
1424    /// - [`ComponentId`] must be from the same world as `self`.
1425    /// - `T` must have the same layout as the one passed during `component_id` creation.
1426    #[track_caller]
1427    pub unsafe fn insert_by_id<T: Send + 'static>(
1428        &mut self,
1429        component_id: ComponentId,
1430        value: T,
1431    ) -> &mut Self {
1432        self.queue(
1433            // SAFETY:
1434            // - `ComponentId` safety is ensured by the caller.
1435            // - `T` safety is ensured by the caller.
1436            unsafe { entity_command::insert_by_id(component_id, value, InsertMode::Replace) },
1437        )
1438    }
1439
1440    /// Adds a dynamic [`Component`] to the entity.
1441    ///
1442    /// This will overwrite any previous value(s) of the same component type.
1443    ///
1444    /// You should prefer to use the typed API [`EntityCommands::try_insert`] where possible.
1445    ///
1446    /// # Note
1447    ///
1448    /// If the entity does not exist when this command is executed,
1449    /// the resulting error will be ignored.
1450    ///
1451    /// # Safety
1452    ///
1453    /// - [`ComponentId`] must be from the same world as `self`.
1454    /// - `T` must have the same layout as the one passed during `component_id` creation.
1455    #[track_caller]
1456    pub unsafe fn try_insert_by_id<T: Send + 'static>(
1457        &mut self,
1458        component_id: ComponentId,
1459        value: T,
1460    ) -> &mut Self {
1461        self.queue_handled(
1462            // SAFETY:
1463            // - `ComponentId` safety is ensured by the caller.
1464            // - `T` safety is ensured by the caller.
1465            unsafe { entity_command::insert_by_id(component_id, value, InsertMode::Replace) },
1466            ignore,
1467        )
1468    }
1469
1470    /// Adds a [`Bundle`] of components to the entity.
1471    ///
1472    /// This will overwrite any previous value(s) of the same component type.
1473    ///
1474    /// # Note
1475    ///
1476    /// If the entity does not exist when this command is executed,
1477    /// the resulting error will be ignored.
1478    ///
1479    /// # Example
1480    ///
1481    /// ```
1482    /// # use bevy_ecs::prelude::*;
1483    /// # #[derive(Resource)]
1484    /// # struct PlayerEntity { entity: Entity }
1485    /// #[derive(Component)]
1486    /// struct Health(u32);
1487    /// #[derive(Component)]
1488    /// struct Strength(u32);
1489    /// #[derive(Component)]
1490    /// struct Defense(u32);
1491    ///
1492    /// #[derive(Bundle)]
1493    /// struct CombatBundle {
1494    ///     health: Health,
1495    ///     strength: Strength,
1496    /// }
1497    ///
1498    /// fn add_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
1499    ///     commands.entity(player.entity)
1500    ///         // You can insert individual components:
1501    ///         .try_insert(Defense(10))
1502    ///         // You can also insert tuples of components:
1503    ///         .try_insert(CombatBundle {
1504    ///             health: Health(100),
1505    ///             strength: Strength(40),
1506    ///         });
1507    ///
1508    ///     // Suppose this occurs in a parallel adjacent system or process.
1509    ///     commands.entity(player.entity).despawn();
1510    ///
1511    ///     // This will not panic nor will it add the component.
1512    ///     commands.entity(player.entity).try_insert(Defense(5));
1513    /// }
1514    /// # bevy_ecs::system::assert_is_system(add_combat_stats_system);
1515    /// ```
1516    #[track_caller]
1517    pub fn try_insert(&mut self, bundle: impl Bundle) -> &mut Self {
1518        self.queue_handled(entity_command::insert(bundle, InsertMode::Replace), ignore)
1519    }
1520
1521    /// Adds a [`Bundle`] of components to the entity if the predicate returns true.
1522    ///
1523    /// This is useful for chaining method calls.
1524    ///
1525    /// # Note
1526    ///
1527    /// If the entity does not exist when this command is executed,
1528    /// the resulting error will be ignored.
1529    #[track_caller]
1530    pub fn try_insert_if<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
1531    where
1532        F: FnOnce() -> bool,
1533    {
1534        if condition() {
1535            self.try_insert(bundle)
1536        } else {
1537            self
1538        }
1539    }
1540
1541    /// Adds a [`Bundle`] of components to the entity without overwriting if the
1542    /// predicate returns true.
1543    ///
1544    /// This is the same as [`EntityCommands::try_insert_if`], but in case of duplicate
1545    /// components will leave the old values instead of replacing them with new ones.
1546    ///
1547    /// # Note
1548    ///
1549    /// If the entity does not exist when this command is executed,
1550    /// the resulting error will be ignored.
1551    #[track_caller]
1552    pub fn try_insert_if_new_and<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
1553    where
1554        F: FnOnce() -> bool,
1555    {
1556        if condition() {
1557            self.try_insert_if_new(bundle)
1558        } else {
1559            self
1560        }
1561    }
1562
1563    /// Adds a [`Bundle`] of components to the entity without overwriting.
1564    ///
1565    /// This is the same as [`EntityCommands::try_insert`], but in case of duplicate
1566    /// components will leave the old values instead of replacing them with new ones.
1567    ///
1568    /// # Note
1569    ///
1570    /// If the entity does not exist when this command is executed,
1571    /// the resulting error will be ignored.
1572    #[track_caller]
1573    pub fn try_insert_if_new(&mut self, bundle: impl Bundle) -> &mut Self {
1574        self.queue_handled(entity_command::insert(bundle, InsertMode::Keep), ignore)
1575    }
1576
1577    /// Removes a [`Bundle`] of components from the entity.
1578    ///
1579    /// This will remove all components that intersect with the provided bundle;
1580    /// the entity does not need to have all the components in the bundle.
1581    ///
1582    /// This will emit a warning if the entity does not exist.
1583    ///
1584    /// # Example
1585    ///
1586    /// ```
1587    /// # use bevy_ecs::prelude::*;
1588    /// # #[derive(Resource)]
1589    /// # struct PlayerEntity { entity: Entity }
1590    /// #[derive(Component)]
1591    /// struct Health(u32);
1592    /// #[derive(Component)]
1593    /// struct Strength(u32);
1594    /// #[derive(Component)]
1595    /// struct Defense(u32);
1596    ///
1597    /// #[derive(Bundle)]
1598    /// struct CombatBundle {
1599    ///     health: Health,
1600    ///     strength: Strength,
1601    /// }
1602    ///
1603    /// fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
1604    ///     commands
1605    ///         .entity(player.entity)
1606    ///         // You can remove individual components:
1607    ///         .remove::<Defense>()
1608    ///         // You can also remove pre-defined bundles of components:
1609    ///         .remove::<CombatBundle>()
1610    ///         // You can also remove tuples of components and bundles.
1611    ///         // This is equivalent to the calls above:
1612    ///         .remove::<(Defense, CombatBundle)>();
1613    /// }
1614    /// # bevy_ecs::system::assert_is_system(remove_combat_stats_system);
1615    /// ```
1616    #[track_caller]
1617    pub fn remove<B: Bundle>(&mut self) -> &mut Self {
1618        self.queue_handled(entity_command::remove::<B>(), warn)
1619    }
1620
1621    /// Removes a [`Bundle`] of components from the entity.
1622    ///
1623    /// This will remove all components that intersect with the provided bundle;
1624    /// the entity does not need to have all the components in the bundle.
1625    ///
1626    /// Unlike [`Self::remove`],
1627    /// this will not emit a warning if the entity does not exist.
1628    ///
1629    /// # Example
1630    ///
1631    /// ```
1632    /// # use bevy_ecs::prelude::*;
1633    /// # #[derive(Resource)]
1634    /// # struct PlayerEntity { entity: Entity }
1635    /// #[derive(Component)]
1636    /// struct Health(u32);
1637    /// #[derive(Component)]
1638    /// struct Strength(u32);
1639    /// #[derive(Component)]
1640    /// struct Defense(u32);
1641    ///
1642    /// #[derive(Bundle)]
1643    /// struct CombatBundle {
1644    ///     health: Health,
1645    ///     strength: Strength,
1646    /// }
1647    ///
1648    /// fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
1649    ///     commands
1650    ///         .entity(player.entity)
1651    ///         // You can remove individual components:
1652    ///         .try_remove::<Defense>()
1653    ///         // You can also remove pre-defined bundles of components:
1654    ///         .try_remove::<CombatBundle>()
1655    ///         // You can also remove tuples of components and bundles.
1656    ///         // This is equivalent to the calls above:
1657    ///         .try_remove::<(Defense, CombatBundle)>();
1658    /// }
1659    /// # bevy_ecs::system::assert_is_system(remove_combat_stats_system);
1660    /// ```
1661    pub fn try_remove<B: Bundle>(&mut self) -> &mut Self {
1662        self.queue_handled(entity_command::remove::<B>(), ignore)
1663    }
1664
1665    /// Removes a [`Bundle`] of components from the entity,
1666    /// and also removes any components required by the components in the bundle.
1667    ///
1668    /// This will remove all components that intersect with the provided bundle;
1669    /// the entity does not need to have all the components in the bundle.
1670    ///
1671    /// # Example
1672    ///
1673    /// ```
1674    /// # use bevy_ecs::prelude::*;
1675    /// # #[derive(Resource)]
1676    /// # struct PlayerEntity { entity: Entity }
1677    /// #
1678    /// #[derive(Component)]
1679    /// #[require(B)]
1680    /// struct A;
1681    /// #[derive(Component, Default)]
1682    /// struct B;
1683    ///
1684    /// fn remove_with_requires_system(mut commands: Commands, player: Res<PlayerEntity>) {
1685    ///     commands
1686    ///         .entity(player.entity)
1687    ///         // Removes both A and B from the entity, because B is required by A.
1688    ///         .remove_with_requires::<A>();
1689    /// }
1690    /// # bevy_ecs::system::assert_is_system(remove_with_requires_system);
1691    /// ```
1692    #[track_caller]
1693    pub fn remove_with_requires<B: Bundle>(&mut self) -> &mut Self {
1694        self.queue(entity_command::remove_with_requires::<B>())
1695    }
1696
1697    /// Removes a dynamic [`Component`] from the entity if it exists.
1698    ///
1699    /// # Panics
1700    ///
1701    /// Panics if the provided [`ComponentId`] does not exist in the [`World`].
1702    #[track_caller]
1703    pub fn remove_by_id(&mut self, component_id: ComponentId) -> &mut Self {
1704        self.queue(entity_command::remove_by_id(component_id))
1705    }
1706
1707    /// Removes all components associated with the entity.
1708    #[track_caller]
1709    pub fn clear(&mut self) -> &mut Self {
1710        self.queue(entity_command::clear())
1711    }
1712
1713    /// Despawns the entity.
1714    ///
1715    /// This will emit a warning if the entity does not exist.
1716    ///
1717    /// # Note
1718    ///
1719    /// This will also despawn the entities in any [`RelationshipTarget`](crate::relationship::RelationshipTarget)
1720    /// that is configured to despawn descendants.
1721    ///
1722    /// For example, this will recursively despawn [`Children`](crate::hierarchy::Children).
1723    ///
1724    /// # Example
1725    ///
1726    /// ```
1727    /// # use bevy_ecs::prelude::*;
1728    /// # #[derive(Resource)]
1729    /// # struct CharacterToRemove { entity: Entity }
1730    /// #
1731    /// fn remove_character_system(
1732    ///     mut commands: Commands,
1733    ///     character_to_remove: Res<CharacterToRemove>
1734    /// ) {
1735    ///     commands.entity(character_to_remove.entity).despawn();
1736    /// }
1737    /// # bevy_ecs::system::assert_is_system(remove_character_system);
1738    /// ```
1739    #[track_caller]
1740    pub fn despawn(&mut self) {
1741        self.queue_handled(entity_command::despawn(), warn);
1742    }
1743    /// Despawns the provided entity and its descendants.
1744    #[deprecated(
1745        since = "0.16.0",
1746        note = "Use entity.despawn(), which now automatically despawns recursively."
1747    )]
1748    pub fn despawn_recursive(&mut self) {
1749        self.despawn();
1750    }
1751
1752    /// Despawns the entity.
1753    ///
1754    /// Unlike [`Self::despawn`],
1755    /// this will not emit a warning if the entity does not exist.
1756    ///
1757    /// # Note
1758    ///
1759    /// This will also despawn the entities in any [`RelationshipTarget`](crate::relationship::RelationshipTarget)
1760    /// that is configured to despawn descendants.
1761    ///
1762    /// For example, this will recursively despawn [`Children`](crate::hierarchy::Children).
1763    pub fn try_despawn(&mut self) {
1764        self.queue_handled(entity_command::despawn(), ignore);
1765    }
1766
1767    /// Pushes an [`EntityCommand`] to the queue,
1768    /// which will get executed for the current [`Entity`].
1769    ///
1770    /// The [default error handler](crate::error::default_error_handler)
1771    /// will be used to handle error cases.
1772    /// Every [`EntityCommand`] checks whether the entity exists at the time of execution
1773    /// and returns an error if it does not.
1774    ///
1775    /// To use a custom error handler, see [`EntityCommands::queue_handled`].
1776    ///
1777    /// The command can be:
1778    /// - A custom struct that implements [`EntityCommand`].
1779    /// - A closure or function that matches the following signature:
1780    ///   - [`(EntityWorldMut)`](EntityWorldMut)
1781    ///   - [`(EntityWorldMut)`](EntityWorldMut) `->` [`Result`]
1782    /// - A built-in command from the [`entity_command`] module.
1783    ///
1784    /// # Example
1785    ///
1786    /// ```
1787    /// # use bevy_ecs::prelude::*;
1788    /// # fn my_system(mut commands: Commands) {
1789    /// commands
1790    ///     .spawn_empty()
1791    ///     // Closures with this signature implement `EntityCommand`.
1792    ///     .queue(|entity: EntityWorldMut| {
1793    ///         println!("Executed an EntityCommand for {}", entity.id());
1794    ///     });
1795    /// # }
1796    /// # bevy_ecs::system::assert_is_system(my_system);
1797    /// ```
1798    pub fn queue<C: EntityCommand<T> + CommandWithEntity<M>, T, M>(
1799        &mut self,
1800        command: C,
1801    ) -> &mut Self {
1802        self.commands.queue(command.with_entity(self.entity));
1803        self
1804    }
1805
1806    /// Pushes an [`EntityCommand`] to the queue,
1807    /// which will get executed for the current [`Entity`].
1808    ///
1809    /// The given `error_handler` will be used to handle error cases.
1810    /// Every [`EntityCommand`] checks whether the entity exists at the time of execution
1811    /// and returns an error if it does not.
1812    ///
1813    /// To implicitly use the default error handler, see [`EntityCommands::queue`].
1814    ///
1815    /// The command can be:
1816    /// - A custom struct that implements [`EntityCommand`].
1817    /// - A closure or function that matches the following signature:
1818    ///   - [`(EntityWorldMut)`](EntityWorldMut)
1819    ///   - [`(EntityWorldMut)`](EntityWorldMut) `->` [`Result`]
1820    /// - A built-in command from the [`entity_command`] module.
1821    ///
1822    /// # Example
1823    ///
1824    /// ```
1825    /// # use bevy_ecs::prelude::*;
1826    /// # fn my_system(mut commands: Commands) {
1827    /// use bevy_ecs::error::warn;
1828    ///
1829    /// commands
1830    ///     .spawn_empty()
1831    ///     // Closures with this signature implement `EntityCommand`.
1832    ///     .queue_handled(
1833    ///         |entity: EntityWorldMut| -> Result {
1834    ///             let value: usize = "100".parse()?;
1835    ///             println!("Successfully parsed the value {} for entity {}", value, entity.id());
1836    ///             Ok(())
1837    ///         },
1838    ///         warn
1839    ///     );
1840    /// # }
1841    /// # bevy_ecs::system::assert_is_system(my_system);
1842    /// ```
1843    pub fn queue_handled<C: EntityCommand<T> + CommandWithEntity<M>, T, M>(
1844        &mut self,
1845        command: C,
1846        error_handler: fn(BevyError, ErrorContext),
1847    ) -> &mut Self {
1848        self.commands
1849            .queue_handled(command.with_entity(self.entity), error_handler);
1850        self
1851    }
1852
1853    /// Removes all components except the given [`Bundle`] from the entity.
1854    ///
1855    /// # Example
1856    ///
1857    /// ```
1858    /// # use bevy_ecs::prelude::*;
1859    /// # #[derive(Resource)]
1860    /// # struct PlayerEntity { entity: Entity }
1861    /// #[derive(Component)]
1862    /// struct Health(u32);
1863    /// #[derive(Component)]
1864    /// struct Strength(u32);
1865    /// #[derive(Component)]
1866    /// struct Defense(u32);
1867    ///
1868    /// #[derive(Bundle)]
1869    /// struct CombatBundle {
1870    ///     health: Health,
1871    ///     strength: Strength,
1872    /// }
1873    ///
1874    /// fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
1875    ///     commands
1876    ///         .entity(player.entity)
1877    ///         // You can retain a pre-defined Bundle of components,
1878    ///         // with this removing only the Defense component.
1879    ///         .retain::<CombatBundle>()
1880    ///         // You can also retain only a single component.
1881    ///         .retain::<Health>();
1882    /// }
1883    /// # bevy_ecs::system::assert_is_system(remove_combat_stats_system);
1884    /// ```
1885    #[track_caller]
1886    pub fn retain<B: Bundle>(&mut self) -> &mut Self {
1887        self.queue(entity_command::retain::<B>())
1888    }
1889
1890    /// Logs the components of the entity at the [`info`](log::info) level.
1891    pub fn log_components(&mut self) -> &mut Self {
1892        self.queue(entity_command::log_components())
1893    }
1894
1895    /// Returns the underlying [`Commands`].
1896    pub fn commands(&mut self) -> Commands {
1897        self.commands.reborrow()
1898    }
1899
1900    /// Returns a mutable reference to the underlying [`Commands`].
1901    pub fn commands_mut(&mut self) -> &mut Commands<'a, 'a> {
1902        &mut self.commands
1903    }
1904
1905    /// Sends a [`Trigger`](crate::observer::Trigger) targeting the entity.
1906    ///
1907    /// This will run any [`Observer`] of the given [`Event`] watching this entity.
1908    #[track_caller]
1909    pub fn trigger(&mut self, event: impl Event) -> &mut Self {
1910        self.queue(entity_command::trigger(event))
1911    }
1912
1913    /// Creates an [`Observer`] listening for events of type `E` targeting this entity.
1914    pub fn observe<E: Event, B: Bundle, M>(
1915        &mut self,
1916        observer: impl IntoObserverSystem<E, B, M>,
1917    ) -> &mut Self {
1918        self.queue(entity_command::observe(observer))
1919    }
1920
1921    /// Clones parts of an entity (components, observers, etc.) onto another entity,
1922    /// configured through [`EntityClonerBuilder`].
1923    ///
1924    /// By default, the other entity will receive all the components of the original that implement
1925    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
1926    ///
1927    /// # Panics
1928    ///
1929    /// The command will panic when applied if the target entity does not exist.
1930    ///
1931    /// # Example
1932    ///
1933    /// Configure through [`EntityClonerBuilder`] as follows:
1934    /// ```
1935    /// # use bevy_ecs::prelude::*;
1936    /// #[derive(Component, Clone)]
1937    /// struct ComponentA(u32);
1938    /// #[derive(Component, Clone)]
1939    /// struct ComponentB(u32);
1940    ///
1941    /// fn example_system(mut commands: Commands) {
1942    ///     // Create an empty entity.
1943    ///     let target = commands.spawn_empty().id();
1944    ///
1945    ///     // Create a new entity and keep its EntityCommands.
1946    ///     let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));
1947    ///
1948    ///     // Clone only ComponentA onto the target.
1949    ///     entity.clone_with(target, |builder| {
1950    ///         builder.deny::<ComponentB>();
1951    ///     });
1952    /// }
1953    /// # bevy_ecs::system::assert_is_system(example_system);
1954    /// ```
1955    ///
1956    /// See [`EntityClonerBuilder`] for more options.
1957    pub fn clone_with(
1958        &mut self,
1959        target: Entity,
1960        config: impl FnOnce(&mut EntityClonerBuilder) + Send + Sync + 'static,
1961    ) -> &mut Self {
1962        self.queue(entity_command::clone_with(target, config))
1963    }
1964
1965    /// Spawns a clone of this entity and returns the [`EntityCommands`] of the clone.
1966    ///
1967    /// The clone will receive all the components of the original that implement
1968    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
1969    ///
1970    /// To configure cloning behavior (such as only cloning certain components),
1971    /// use [`EntityCommands::clone_and_spawn_with`].
1972    ///
1973    /// # Note
1974    ///
1975    /// If the original entity does not exist when this command is applied,
1976    /// the returned entity will have no components.
1977    ///
1978    /// # Example
1979    ///
1980    /// ```
1981    /// # use bevy_ecs::prelude::*;
1982    /// #[derive(Component, Clone)]
1983    /// struct ComponentA(u32);
1984    /// #[derive(Component, Clone)]
1985    /// struct ComponentB(u32);
1986    ///
1987    /// fn example_system(mut commands: Commands) {
1988    ///     // Create a new entity and store its EntityCommands.
1989    ///     let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));
1990    ///
1991    ///     // Create a clone of the first entity.
1992    ///     let mut entity_clone = entity.clone_and_spawn();
1993    /// }
1994    /// # bevy_ecs::system::assert_is_system(example_system);
1995    pub fn clone_and_spawn(&mut self) -> EntityCommands<'_> {
1996        self.clone_and_spawn_with(|_| {})
1997    }
1998
1999    /// Spawns a clone of this entity and allows configuring cloning behavior
2000    /// using [`EntityClonerBuilder`], returning the [`EntityCommands`] of the clone.
2001    ///
2002    /// By default, the clone will receive all the components of the original that implement
2003    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
2004    ///
2005    /// To exclude specific components, use [`EntityClonerBuilder::deny`].
2006    /// To only include specific components, use [`EntityClonerBuilder::deny_all`]
2007    /// followed by [`EntityClonerBuilder::allow`].
2008    ///
2009    /// See the methods on [`EntityClonerBuilder`] for more options.
2010    ///
2011    /// # Note
2012    ///
2013    /// If the original entity does not exist when this command is applied,
2014    /// the returned entity will have no components.
2015    ///
2016    /// # Example
2017    ///
2018    /// ```
2019    /// # use bevy_ecs::prelude::*;
2020    /// #[derive(Component, Clone)]
2021    /// struct ComponentA(u32);
2022    /// #[derive(Component, Clone)]
2023    /// struct ComponentB(u32);
2024    ///
2025    /// fn example_system(mut commands: Commands) {
2026    ///     // Create a new entity and store its EntityCommands.
2027    ///     let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));
2028    ///
2029    ///     // Create a clone of the first entity, but without ComponentB.
2030    ///     let mut entity_clone = entity.clone_and_spawn_with(|builder| {
2031    ///         builder.deny::<ComponentB>();
2032    ///     });
2033    /// }
2034    /// # bevy_ecs::system::assert_is_system(example_system);
2035    pub fn clone_and_spawn_with(
2036        &mut self,
2037        config: impl FnOnce(&mut EntityClonerBuilder) + Send + Sync + 'static,
2038    ) -> EntityCommands<'_> {
2039        let entity_clone = self.commands().spawn_empty().id();
2040        self.clone_with(entity_clone, config);
2041        EntityCommands {
2042            commands: self.commands_mut().reborrow(),
2043            entity: entity_clone,
2044        }
2045    }
2046
2047    /// Clones the specified components of this entity and inserts them into another entity.
2048    ///
2049    /// Components can only be cloned if they implement
2050    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
2051    ///
2052    /// # Panics
2053    ///
2054    /// The command will panic when applied if the target entity does not exist.
2055    pub fn clone_components<B: Bundle>(&mut self, target: Entity) -> &mut Self {
2056        self.queue(entity_command::clone_components::<B>(target))
2057    }
2058
2059    /// Clones the specified components of this entity and inserts them into another entity,
2060    /// then removes the components from this entity.
2061    ///
2062    /// Components can only be cloned if they implement
2063    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
2064    ///
2065    /// # Panics
2066    ///
2067    /// The command will panic when applied if the target entity does not exist.
2068    pub fn move_components<B: Bundle>(&mut self, target: Entity) -> &mut Self {
2069        self.queue(entity_command::move_components::<B>(target))
2070    }
2071}
2072
2073/// A wrapper around [`EntityCommands`] with convenience methods for working with a specified component type.
2074pub struct EntityEntryCommands<'a, T> {
2075    entity_commands: EntityCommands<'a>,
2076    marker: PhantomData<T>,
2077}
2078
2079impl<'a, T: Component<Mutability = Mutable>> EntityEntryCommands<'a, T> {
2080    /// Modify the component `T` if it exists, using the function `modify`.
2081    pub fn and_modify(&mut self, modify: impl FnOnce(Mut<T>) + Send + Sync + 'static) -> &mut Self {
2082        self.entity_commands
2083            .queue(move |mut entity: EntityWorldMut| {
2084                if let Some(value) = entity.get_mut() {
2085                    modify(value);
2086                }
2087            });
2088        self
2089    }
2090}
2091
2092impl<'a, T: Component> EntityEntryCommands<'a, T> {
2093    /// [Insert](EntityCommands::insert) `default` into this entity,
2094    /// if `T` is not already present.
2095    #[track_caller]
2096    pub fn or_insert(&mut self, default: T) -> &mut Self {
2097        self.entity_commands.insert_if_new(default);
2098        self
2099    }
2100
2101    /// [Insert](EntityCommands::insert) `default` into this entity,
2102    /// if `T` is not already present.
2103    ///
2104    /// # Note
2105    ///
2106    /// If the entity does not exist when this command is executed,
2107    /// the resulting error will be ignored.
2108    #[track_caller]
2109    pub fn or_try_insert(&mut self, default: T) -> &mut Self {
2110        self.entity_commands.try_insert_if_new(default);
2111        self
2112    }
2113
2114    /// [Insert](EntityCommands::insert) the value returned from `default` into this entity,
2115    /// if `T` is not already present.
2116    #[track_caller]
2117    pub fn or_insert_with(&mut self, default: impl Fn() -> T) -> &mut Self {
2118        self.or_insert(default())
2119    }
2120
2121    /// [Insert](EntityCommands::insert) the value returned from `default` into this entity,
2122    /// if `T` is not already present.
2123    ///
2124    /// # Note
2125    ///
2126    /// If the entity does not exist when this command is executed,
2127    /// the resulting error will be ignored.
2128    #[track_caller]
2129    pub fn or_try_insert_with(&mut self, default: impl Fn() -> T) -> &mut Self {
2130        self.or_try_insert(default())
2131    }
2132
2133    /// [Insert](EntityCommands::insert) `T::default` into this entity,
2134    /// if `T` is not already present.
2135    #[track_caller]
2136    pub fn or_default(&mut self) -> &mut Self
2137    where
2138        T: Default,
2139    {
2140        self.or_insert(T::default())
2141    }
2142
2143    /// [Insert](EntityCommands::insert) `T::from_world` into this entity,
2144    /// if `T` is not already present.
2145    #[track_caller]
2146    pub fn or_from_world(&mut self) -> &mut Self
2147    where
2148        T: FromWorld,
2149    {
2150        self.entity_commands
2151            .queue(entity_command::insert_from_world::<T>(InsertMode::Keep));
2152        self
2153    }
2154
2155    /// Get the [`EntityCommands`] from which the [`EntityEntryCommands`] was initiated.
2156    ///
2157    /// This allows you to continue chaining method calls after calling [`EntityCommands::entry`].
2158    ///
2159    /// # Example
2160    ///
2161    /// ```
2162    /// # use bevy_ecs::prelude::*;
2163    /// # #[derive(Resource)]
2164    /// # struct PlayerEntity { entity: Entity }
2165    /// #[derive(Component)]
2166    /// struct Level(u32);
2167    ///
2168    /// fn level_up_system(mut commands: Commands, player: Res<PlayerEntity>) {
2169    ///     commands
2170    ///         .entity(player.entity)
2171    ///         .entry::<Level>()
2172    ///         // Modify the component if it exists.
2173    ///         .and_modify(|mut lvl| lvl.0 += 1)
2174    ///         // Otherwise, insert a default value.
2175    ///         .or_insert(Level(0))
2176    ///         // Return the EntityCommands for the entity.
2177    ///         .entity()
2178    ///         // Continue chaining method calls.
2179    ///         .insert(Name::new("Player"));
2180    /// }
2181    /// # bevy_ecs::system::assert_is_system(level_up_system);
2182    /// ```
2183    pub fn entity(&mut self) -> EntityCommands {
2184        self.entity_commands.reborrow()
2185    }
2186}
2187
2188#[cfg(test)]
2189mod tests {
2190    use crate::{
2191        component::Component,
2192        resource::Resource,
2193        system::Commands,
2194        world::{CommandQueue, FromWorld, World},
2195    };
2196    use alloc::{string::String, sync::Arc, vec, vec::Vec};
2197    use core::{
2198        any::TypeId,
2199        sync::atomic::{AtomicUsize, Ordering},
2200    };
2201
2202    #[expect(
2203        dead_code,
2204        reason = "This struct is used to test how `Drop` behavior works in regards to SparseSet storage, and as such is solely a wrapper around `DropCk` to make it use the SparseSet storage. Because of this, the inner field is intentionally never read."
2205    )]
2206    #[derive(Component)]
2207    #[component(storage = "SparseSet")]
2208    struct SparseDropCk(DropCk);
2209
2210    #[derive(Component)]
2211    struct DropCk(Arc<AtomicUsize>);
2212    impl DropCk {
2213        fn new_pair() -> (Self, Arc<AtomicUsize>) {
2214            let atomic = Arc::new(AtomicUsize::new(0));
2215            (DropCk(atomic.clone()), atomic)
2216        }
2217    }
2218
2219    impl Drop for DropCk {
2220        fn drop(&mut self) {
2221            self.0.as_ref().fetch_add(1, Ordering::Relaxed);
2222        }
2223    }
2224
2225    #[derive(Component, Resource)]
2226    struct W<T>(T);
2227
2228    fn simple_command(world: &mut World) {
2229        world.spawn((W(0u32), W(42u64)));
2230    }
2231
2232    impl FromWorld for W<String> {
2233        fn from_world(world: &mut World) -> Self {
2234            let v = world.resource::<W<usize>>();
2235            Self("*".repeat(v.0))
2236        }
2237    }
2238
2239    #[test]
2240    fn entity_commands_entry() {
2241        let mut world = World::default();
2242        let mut queue = CommandQueue::default();
2243        let mut commands = Commands::new(&mut queue, &world);
2244        let entity = commands.spawn_empty().id();
2245        commands
2246            .entity(entity)
2247            .entry::<W<u32>>()
2248            .and_modify(|_| unreachable!());
2249        queue.apply(&mut world);
2250        assert!(!world.entity(entity).contains::<W<u32>>());
2251        let mut commands = Commands::new(&mut queue, &world);
2252        commands
2253            .entity(entity)
2254            .entry::<W<u32>>()
2255            .or_insert(W(0))
2256            .and_modify(|mut val| {
2257                val.0 = 21;
2258            });
2259        queue.apply(&mut world);
2260        assert_eq!(21, world.get::<W<u32>>(entity).unwrap().0);
2261        let mut commands = Commands::new(&mut queue, &world);
2262        commands
2263            .entity(entity)
2264            .entry::<W<u64>>()
2265            .and_modify(|_| unreachable!())
2266            .or_insert(W(42));
2267        queue.apply(&mut world);
2268        assert_eq!(42, world.get::<W<u64>>(entity).unwrap().0);
2269        world.insert_resource(W(5_usize));
2270        let mut commands = Commands::new(&mut queue, &world);
2271        commands.entity(entity).entry::<W<String>>().or_from_world();
2272        queue.apply(&mut world);
2273        assert_eq!("*****", &world.get::<W<String>>(entity).unwrap().0);
2274        let mut commands = Commands::new(&mut queue, &world);
2275        let id = commands.entity(entity).entry::<W<u64>>().entity().id();
2276        queue.apply(&mut world);
2277        assert_eq!(id, entity);
2278    }
2279
2280    #[test]
2281    fn commands() {
2282        let mut world = World::default();
2283        let mut command_queue = CommandQueue::default();
2284        let entity = Commands::new(&mut command_queue, &world)
2285            .spawn((W(1u32), W(2u64)))
2286            .id();
2287        command_queue.apply(&mut world);
2288        assert_eq!(world.entities().len(), 1);
2289        let results = world
2290            .query::<(&W<u32>, &W<u64>)>()
2291            .iter(&world)
2292            .map(|(a, b)| (a.0, b.0))
2293            .collect::<Vec<_>>();
2294        assert_eq!(results, vec![(1u32, 2u64)]);
2295        // test entity despawn
2296        {
2297            let mut commands = Commands::new(&mut command_queue, &world);
2298            commands.entity(entity).despawn();
2299            commands.entity(entity).despawn(); // double despawn shouldn't panic
2300        }
2301        command_queue.apply(&mut world);
2302        let results2 = world
2303            .query::<(&W<u32>, &W<u64>)>()
2304            .iter(&world)
2305            .map(|(a, b)| (a.0, b.0))
2306            .collect::<Vec<_>>();
2307        assert_eq!(results2, vec![]);
2308
2309        // test adding simple (FnOnce) commands
2310        {
2311            let mut commands = Commands::new(&mut command_queue, &world);
2312
2313            // set up a simple command using a closure that adds one additional entity
2314            commands.queue(|world: &mut World| {
2315                world.spawn((W(42u32), W(0u64)));
2316            });
2317
2318            // set up a simple command using a function that adds one additional entity
2319            commands.queue(simple_command);
2320        }
2321        command_queue.apply(&mut world);
2322        let results3 = world
2323            .query::<(&W<u32>, &W<u64>)>()
2324            .iter(&world)
2325            .map(|(a, b)| (a.0, b.0))
2326            .collect::<Vec<_>>();
2327
2328        assert_eq!(results3, vec![(42u32, 0u64), (0u32, 42u64)]);
2329    }
2330
2331    #[test]
2332    fn insert_components() {
2333        let mut world = World::default();
2334        let mut command_queue1 = CommandQueue::default();
2335
2336        // insert components
2337        let entity = Commands::new(&mut command_queue1, &world)
2338            .spawn(())
2339            .insert_if(W(1u8), || true)
2340            .insert_if(W(2u8), || false)
2341            .insert_if_new(W(1u16))
2342            .insert_if_new(W(2u16))
2343            .insert_if_new_and(W(1u32), || false)
2344            .insert_if_new_and(W(2u32), || true)
2345            .insert_if_new_and(W(3u32), || true)
2346            .id();
2347        command_queue1.apply(&mut world);
2348
2349        let results = world
2350            .query::<(&W<u8>, &W<u16>, &W<u32>)>()
2351            .iter(&world)
2352            .map(|(a, b, c)| (a.0, b.0, c.0))
2353            .collect::<Vec<_>>();
2354        assert_eq!(results, vec![(1u8, 1u16, 2u32)]);
2355
2356        // try to insert components after despawning entity
2357        // in another command queue
2358        Commands::new(&mut command_queue1, &world)
2359            .entity(entity)
2360            .try_insert_if_new_and(W(1u64), || true);
2361
2362        let mut command_queue2 = CommandQueue::default();
2363        Commands::new(&mut command_queue2, &world)
2364            .entity(entity)
2365            .despawn();
2366        command_queue2.apply(&mut world);
2367        command_queue1.apply(&mut world);
2368    }
2369
2370    #[test]
2371    fn remove_components() {
2372        let mut world = World::default();
2373
2374        let mut command_queue = CommandQueue::default();
2375        let (dense_dropck, dense_is_dropped) = DropCk::new_pair();
2376        let (sparse_dropck, sparse_is_dropped) = DropCk::new_pair();
2377        let sparse_dropck = SparseDropCk(sparse_dropck);
2378
2379        let entity = Commands::new(&mut command_queue, &world)
2380            .spawn((W(1u32), W(2u64), dense_dropck, sparse_dropck))
2381            .id();
2382        command_queue.apply(&mut world);
2383        let results_before = world
2384            .query::<(&W<u32>, &W<u64>)>()
2385            .iter(&world)
2386            .map(|(a, b)| (a.0, b.0))
2387            .collect::<Vec<_>>();
2388        assert_eq!(results_before, vec![(1u32, 2u64)]);
2389
2390        // test component removal
2391        Commands::new(&mut command_queue, &world)
2392            .entity(entity)
2393            .remove::<W<u32>>()
2394            .remove::<(W<u32>, W<u64>, SparseDropCk, DropCk)>();
2395
2396        assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 0);
2397        assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 0);
2398        command_queue.apply(&mut world);
2399        assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 1);
2400        assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 1);
2401
2402        let results_after = world
2403            .query::<(&W<u32>, &W<u64>)>()
2404            .iter(&world)
2405            .map(|(a, b)| (a.0, b.0))
2406            .collect::<Vec<_>>();
2407        assert_eq!(results_after, vec![]);
2408        let results_after_u64 = world
2409            .query::<&W<u64>>()
2410            .iter(&world)
2411            .map(|v| v.0)
2412            .collect::<Vec<_>>();
2413        assert_eq!(results_after_u64, vec![]);
2414    }
2415
2416    #[test]
2417    fn remove_components_by_id() {
2418        let mut world = World::default();
2419
2420        let mut command_queue = CommandQueue::default();
2421        let (dense_dropck, dense_is_dropped) = DropCk::new_pair();
2422        let (sparse_dropck, sparse_is_dropped) = DropCk::new_pair();
2423        let sparse_dropck = SparseDropCk(sparse_dropck);
2424
2425        let entity = Commands::new(&mut command_queue, &world)
2426            .spawn((W(1u32), W(2u64), dense_dropck, sparse_dropck))
2427            .id();
2428        command_queue.apply(&mut world);
2429        let results_before = world
2430            .query::<(&W<u32>, &W<u64>)>()
2431            .iter(&world)
2432            .map(|(a, b)| (a.0, b.0))
2433            .collect::<Vec<_>>();
2434        assert_eq!(results_before, vec![(1u32, 2u64)]);
2435
2436        // test component removal
2437        Commands::new(&mut command_queue, &world)
2438            .entity(entity)
2439            .remove_by_id(world.components().get_id(TypeId::of::<W<u32>>()).unwrap())
2440            .remove_by_id(world.components().get_id(TypeId::of::<W<u64>>()).unwrap())
2441            .remove_by_id(world.components().get_id(TypeId::of::<DropCk>()).unwrap())
2442            .remove_by_id(
2443                world
2444                    .components()
2445                    .get_id(TypeId::of::<SparseDropCk>())
2446                    .unwrap(),
2447            );
2448
2449        assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 0);
2450        assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 0);
2451        command_queue.apply(&mut world);
2452        assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 1);
2453        assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 1);
2454
2455        let results_after = world
2456            .query::<(&W<u32>, &W<u64>)>()
2457            .iter(&world)
2458            .map(|(a, b)| (a.0, b.0))
2459            .collect::<Vec<_>>();
2460        assert_eq!(results_after, vec![]);
2461        let results_after_u64 = world
2462            .query::<&W<u64>>()
2463            .iter(&world)
2464            .map(|v| v.0)
2465            .collect::<Vec<_>>();
2466        assert_eq!(results_after_u64, vec![]);
2467    }
2468
2469    #[test]
2470    fn remove_resources() {
2471        let mut world = World::default();
2472        let mut queue = CommandQueue::default();
2473        {
2474            let mut commands = Commands::new(&mut queue, &world);
2475            commands.insert_resource(W(123i32));
2476            commands.insert_resource(W(456.0f64));
2477        }
2478
2479        queue.apply(&mut world);
2480        assert!(world.contains_resource::<W<i32>>());
2481        assert!(world.contains_resource::<W<f64>>());
2482
2483        {
2484            let mut commands = Commands::new(&mut queue, &world);
2485            // test resource removal
2486            commands.remove_resource::<W<i32>>();
2487        }
2488        queue.apply(&mut world);
2489        assert!(!world.contains_resource::<W<i32>>());
2490        assert!(world.contains_resource::<W<f64>>());
2491    }
2492
2493    #[test]
2494    fn remove_component_with_required_components() {
2495        #[derive(Component)]
2496        #[require(Y)]
2497        struct X;
2498
2499        #[derive(Component, Default)]
2500        struct Y;
2501
2502        #[derive(Component)]
2503        struct Z;
2504
2505        let mut world = World::default();
2506        let mut queue = CommandQueue::default();
2507        let e = {
2508            let mut commands = Commands::new(&mut queue, &world);
2509            commands.spawn((X, Z)).id()
2510        };
2511        queue.apply(&mut world);
2512
2513        assert!(world.get::<Y>(e).is_some());
2514        assert!(world.get::<X>(e).is_some());
2515        assert!(world.get::<Z>(e).is_some());
2516
2517        {
2518            let mut commands = Commands::new(&mut queue, &world);
2519            commands.entity(e).remove_with_requires::<X>();
2520        }
2521        queue.apply(&mut world);
2522
2523        assert!(world.get::<Y>(e).is_none());
2524        assert!(world.get::<X>(e).is_none());
2525
2526        assert!(world.get::<Z>(e).is_some());
2527    }
2528
2529    #[test]
2530    fn unregister_system_cached_commands() {
2531        let mut world = World::default();
2532        let mut queue = CommandQueue::default();
2533
2534        fn nothing() {}
2535
2536        let resources = world.iter_resources().count();
2537        let id = world.register_system_cached(nothing);
2538        assert_eq!(world.iter_resources().count(), resources + 1);
2539        assert!(world.get_entity(id.entity).is_ok());
2540
2541        let mut commands = Commands::new(&mut queue, &world);
2542        commands.unregister_system_cached(nothing);
2543        queue.apply(&mut world);
2544        assert_eq!(world.iter_resources().count(), resources);
2545        assert!(world.get_entity(id.entity).is_err());
2546    }
2547
2548    fn is_send<T: Send>() {}
2549    fn is_sync<T: Sync>() {}
2550
2551    #[test]
2552    fn test_commands_are_send_and_sync() {
2553        is_send::<Commands>();
2554        is_sync::<Commands>();
2555    }
2556
2557    #[test]
2558    fn append() {
2559        let mut world = World::default();
2560        let mut queue_1 = CommandQueue::default();
2561        {
2562            let mut commands = Commands::new(&mut queue_1, &world);
2563            commands.insert_resource(W(123i32));
2564        }
2565        let mut queue_2 = CommandQueue::default();
2566        {
2567            let mut commands = Commands::new(&mut queue_2, &world);
2568            commands.insert_resource(W(456.0f64));
2569        }
2570        queue_1.append(&mut queue_2);
2571        queue_1.apply(&mut world);
2572        assert!(world.contains_resource::<W<i32>>());
2573        assert!(world.contains_resource::<W<f64>>());
2574    }
2575}