bevy_ecs/system/
system.rs

1use bevy_utils::tracing::warn;
2use core::fmt::Debug;
3use derive_more::derive::{Display, Error};
4
5use crate::{
6    archetype::ArchetypeComponentId,
7    component::{ComponentId, Tick},
8    query::Access,
9    schedule::InternedSystemSet,
10    system::{input::SystemInput, SystemIn},
11    world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, World},
12};
13
14use alloc::borrow::Cow;
15use core::any::TypeId;
16
17use super::IntoSystem;
18
19/// An ECS system that can be added to a [`Schedule`](crate::schedule::Schedule)
20///
21/// Systems are functions with all arguments implementing
22/// [`SystemParam`](crate::system::SystemParam).
23///
24/// Systems are added to an application using `App::add_systems(Update, my_system)`
25/// or similar methods, and will generally run once per pass of the main loop.
26///
27/// Systems are executed in parallel, in opportunistic order; data access is managed automatically.
28/// It's possible to specify explicit execution order between specific systems,
29/// see [`IntoSystemConfigs`](crate::schedule::IntoSystemConfigs).
30#[diagnostic::on_unimplemented(message = "`{Self}` is not a system", label = "invalid system")]
31pub trait System: Send + Sync + 'static {
32    /// The system's input.
33    type In: SystemInput;
34    /// The system's output.
35    type Out;
36    /// Returns the system's name.
37    fn name(&self) -> Cow<'static, str>;
38    /// Returns the [`TypeId`] of the underlying system type.
39    #[inline]
40    fn type_id(&self) -> TypeId {
41        TypeId::of::<Self>()
42    }
43    /// Returns the system's component [`Access`].
44    fn component_access(&self) -> &Access<ComponentId>;
45    /// Returns the system's archetype component [`Access`].
46    fn archetype_component_access(&self) -> &Access<ArchetypeComponentId>;
47    /// Returns true if the system is [`Send`].
48    fn is_send(&self) -> bool;
49
50    /// Returns true if the system must be run exclusively.
51    fn is_exclusive(&self) -> bool;
52
53    /// Returns true if system has deferred buffers.
54    fn has_deferred(&self) -> bool;
55
56    /// Runs the system with the given input in the world. Unlike [`System::run`], this function
57    /// can be called in parallel with other systems and may break Rust's aliasing rules
58    /// if used incorrectly, making it unsafe to call.
59    ///
60    /// Unlike [`System::run`], this will not apply deferred parameters, which must be independently
61    /// applied by calling [`System::apply_deferred`] at later point in time.
62    ///
63    /// # Safety
64    ///
65    /// - The caller must ensure that [`world`](UnsafeWorldCell) has permission to access any world data
66    ///   registered in `archetype_component_access`. There must be no conflicting
67    ///   simultaneous accesses while the system is running.
68    /// - The method [`System::update_archetype_component_access`] must be called at some
69    ///   point before this one, with the same exact [`World`]. If [`System::update_archetype_component_access`]
70    ///   panics (or otherwise does not return for any reason), this method must not be called.
71    unsafe fn run_unsafe(&mut self, input: SystemIn<'_, Self>, world: UnsafeWorldCell)
72        -> Self::Out;
73
74    /// Runs the system with the given input in the world.
75    ///
76    /// For [read-only](ReadOnlySystem) systems, see [`run_readonly`], which can be called using `&World`.
77    ///
78    /// Unlike [`System::run_unsafe`], this will apply deferred parameters *immediately*.
79    ///
80    /// [`run_readonly`]: ReadOnlySystem::run_readonly
81    fn run(&mut self, input: SystemIn<'_, Self>, world: &mut World) -> Self::Out {
82        let world_cell = world.as_unsafe_world_cell();
83        self.update_archetype_component_access(world_cell);
84        // SAFETY:
85        // - We have exclusive access to the entire world.
86        // - `update_archetype_component_access` has been called.
87        let ret = unsafe { self.run_unsafe(input, world_cell) };
88        self.apply_deferred(world);
89        ret
90    }
91
92    /// Applies any [`Deferred`](crate::system::Deferred) system parameters (or other system buffers) of this system to the world.
93    ///
94    /// This is where [`Commands`](crate::system::Commands) get applied.
95    fn apply_deferred(&mut self, world: &mut World);
96
97    /// Enqueues any [`Deferred`](crate::system::Deferred) system parameters (or other system buffers)
98    /// of this system into the world's command buffer.
99    fn queue_deferred(&mut self, world: DeferredWorld);
100
101    /// Validates that all parameters can be acquired and that system can run without panic.
102    /// Built-in executors use this to prevent invalid systems from running.
103    ///
104    /// However calling and respecting [`System::validate_param_unsafe`] or it's safe variant
105    /// is not a strict requirement, both [`System::run`] and [`System::run_unsafe`]
106    /// should provide their own safety mechanism to prevent undefined behavior.
107    ///
108    /// This method has to be called directly before [`System::run_unsafe`] with no other (relevant)
109    /// world mutations in between. Otherwise, while it won't lead to any undefined behavior,
110    /// the validity of the param may change.
111    ///
112    /// # Safety
113    ///
114    /// - The caller must ensure that [`world`](UnsafeWorldCell) has permission to access any world data
115    ///   registered in `archetype_component_access`. There must be no conflicting
116    ///   simultaneous accesses while the system is running.
117    /// - The method [`System::update_archetype_component_access`] must be called at some
118    ///   point before this one, with the same exact [`World`]. If [`System::update_archetype_component_access`]
119    ///   panics (or otherwise does not return for any reason), this method must not be called.
120    unsafe fn validate_param_unsafe(&mut self, world: UnsafeWorldCell) -> bool;
121
122    /// Safe version of [`System::validate_param_unsafe`].
123    /// that runs on exclusive, single-threaded `world` pointer.
124    fn validate_param(&mut self, world: &World) -> bool {
125        let world_cell = world.as_unsafe_world_cell_readonly();
126        self.update_archetype_component_access(world_cell);
127        // SAFETY:
128        // - We have exclusive access to the entire world.
129        // - `update_archetype_component_access` has been called.
130        unsafe { self.validate_param_unsafe(world_cell) }
131    }
132
133    /// Initialize the system.
134    fn initialize(&mut self, _world: &mut World);
135
136    /// Update the system's archetype component [`Access`].
137    ///
138    /// ## Note for implementors
139    /// `world` may only be used to access metadata. This can be done in safe code
140    /// via functions such as [`UnsafeWorldCell::archetypes`].
141    fn update_archetype_component_access(&mut self, world: UnsafeWorldCell);
142
143    /// Checks any [`Tick`]s stored on this system and wraps their value if they get too old.
144    ///
145    /// This method must be called periodically to ensure that change detection behaves correctly.
146    /// When using bevy's default configuration, this will be called for you as needed.
147    fn check_change_tick(&mut self, change_tick: Tick);
148
149    /// Returns the system's default [system sets](crate::schedule::SystemSet).
150    ///
151    /// Each system will create a default system set that contains the system.
152    fn default_system_sets(&self) -> Vec<InternedSystemSet> {
153        Vec::new()
154    }
155
156    /// Gets the tick indicating the last time this system ran.
157    fn get_last_run(&self) -> Tick;
158
159    /// Overwrites the tick indicating the last time this system ran.
160    ///
161    /// # Warning
162    /// This is a complex and error-prone operation, that can have unexpected consequences on any system relying on this code.
163    /// However, it can be an essential escape hatch when, for example,
164    /// you are trying to synchronize representations using change detection and need to avoid infinite recursion.
165    fn set_last_run(&mut self, last_run: Tick);
166}
167
168/// [`System`] types that do not modify the [`World`] when run.
169/// This is implemented for any systems whose parameters all implement [`ReadOnlySystemParam`].
170///
171/// Note that systems which perform [deferred](System::apply_deferred) mutations (such as with [`Commands`])
172/// may implement this trait.
173///
174/// [`ReadOnlySystemParam`]: crate::system::ReadOnlySystemParam
175/// [`Commands`]: crate::system::Commands
176///
177/// # Safety
178///
179/// This must only be implemented for system types which do not mutate the `World`
180/// when [`System::run_unsafe`] is called.
181pub unsafe trait ReadOnlySystem: System {
182    /// Runs this system with the given input in the world.
183    ///
184    /// Unlike [`System::run`], this can be called with a shared reference to the world,
185    /// since this system is known not to modify the world.
186    fn run_readonly(&mut self, input: SystemIn<'_, Self>, world: &World) -> Self::Out {
187        let world = world.as_unsafe_world_cell_readonly();
188        self.update_archetype_component_access(world);
189        // SAFETY:
190        // - We have read-only access to the entire world.
191        // - `update_archetype_component_access` has been called.
192        unsafe { self.run_unsafe(input, world) }
193    }
194}
195
196/// A convenience type alias for a boxed [`System`] trait object.
197pub type BoxedSystem<In = (), Out = ()> = Box<dyn System<In = In, Out = Out>>;
198
199pub(crate) fn check_system_change_tick(last_run: &mut Tick, this_run: Tick, system_name: &str) {
200    if last_run.check_tick(this_run) {
201        let age = this_run.relative_to(*last_run).get();
202        warn!(
203            "System '{system_name}' has not run for {age} ticks. \
204            Changes older than {} ticks will not be detected.",
205            Tick::MAX.get() - 1,
206        );
207    }
208}
209
210impl<In, Out> Debug for dyn System<In = In, Out = Out>
211where
212    In: SystemInput + 'static,
213    Out: 'static,
214{
215    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
216        f.debug_struct("System")
217            .field("name", &self.name())
218            .field("is_exclusive", &self.is_exclusive())
219            .field("is_send", &self.is_send())
220            .finish_non_exhaustive()
221    }
222}
223
224/// Trait used to run a system immediately on a [`World`].
225///
226/// # Warning
227/// This function is not an efficient method of running systems and it's meant to be used as a utility
228/// for testing and/or diagnostics.
229///
230/// Systems called through [`run_system_once`](RunSystemOnce::run_system_once) do not hold onto any state,
231/// as they are created and destroyed every time [`run_system_once`](RunSystemOnce::run_system_once) is called.
232/// Practically, this means that [`Local`](crate::system::Local) variables are
233/// reset on every run and change detection does not work.
234///
235/// ```
236/// # use bevy_ecs::prelude::*;
237/// # use bevy_ecs::system::RunSystemOnce;
238/// #[derive(Resource, Default)]
239/// struct Counter(u8);
240///
241/// fn increment(mut counter: Local<Counter>) {
242///    counter.0 += 1;
243///    println!("{}", counter.0);
244/// }
245///
246/// let mut world = World::default();
247/// world.run_system_once(increment); // prints 1
248/// world.run_system_once(increment); // still prints 1
249/// ```
250///
251/// If you do need systems to hold onto state between runs, use [`World::run_system_cached`](World::run_system_cached)
252/// or [`World::run_system`](World::run_system).
253///
254/// # Usage
255/// Typically, to test a system, or to extract specific diagnostics information from a world,
256/// you'd need a [`Schedule`](crate::schedule::Schedule) to run the system. This can create redundant boilerplate code
257/// when writing tests or trying to quickly iterate on debug specific systems.
258///
259/// For these situations, this function can be useful because it allows you to execute a system
260/// immediately with some custom input and retrieve its output without requiring the necessary boilerplate.
261///
262/// # Examples
263///
264/// ## Immediate Command Execution
265///
266/// This usage is helpful when trying to test systems or functions that operate on [`Commands`](crate::system::Commands):
267/// ```
268/// # use bevy_ecs::prelude::*;
269/// # use bevy_ecs::system::RunSystemOnce;
270/// let mut world = World::default();
271/// let entity = world.run_system_once(|mut commands: Commands| {
272///     commands.spawn_empty().id()
273/// }).unwrap();
274/// # assert!(world.get_entity(entity).is_ok());
275/// ```
276///
277/// ## Immediate Queries
278///
279/// This usage is helpful when trying to run an arbitrary query on a world for testing or debugging purposes:
280/// ```
281/// # use bevy_ecs::prelude::*;
282/// # use bevy_ecs::system::RunSystemOnce;
283///
284/// #[derive(Component)]
285/// struct T(usize);
286///
287/// let mut world = World::default();
288/// world.spawn(T(0));
289/// world.spawn(T(1));
290/// world.spawn(T(1));
291/// let count = world.run_system_once(|query: Query<&T>| {
292///     query.iter().filter(|t| t.0 == 1).count()
293/// }).unwrap();
294///
295/// # assert_eq!(count, 2);
296/// ```
297///
298/// Note that instead of closures you can also pass in regular functions as systems:
299///
300/// ```
301/// # use bevy_ecs::prelude::*;
302/// # use bevy_ecs::system::RunSystemOnce;
303///
304/// #[derive(Component)]
305/// struct T(usize);
306///
307/// fn count(query: Query<&T>) -> usize {
308///     query.iter().filter(|t| t.0 == 1).count()
309/// }
310///
311/// let mut world = World::default();
312/// world.spawn(T(0));
313/// world.spawn(T(1));
314/// world.spawn(T(1));
315/// let count = world.run_system_once(count).unwrap();
316///
317/// # assert_eq!(count, 2);
318/// ```
319pub trait RunSystemOnce: Sized {
320    /// Tries to run a system and apply its deferred parameters.
321    fn run_system_once<T, Out, Marker>(self, system: T) -> Result<Out, RunSystemError>
322    where
323        T: IntoSystem<(), Out, Marker>,
324    {
325        self.run_system_once_with((), system)
326    }
327
328    /// Tries to run a system with given input and apply deferred parameters.
329    fn run_system_once_with<T, In, Out, Marker>(
330        self,
331        input: SystemIn<'_, T::System>,
332        system: T,
333    ) -> Result<Out, RunSystemError>
334    where
335        T: IntoSystem<In, Out, Marker>,
336        In: SystemInput;
337}
338
339impl RunSystemOnce for &mut World {
340    fn run_system_once_with<T, In, Out, Marker>(
341        self,
342        input: SystemIn<'_, T::System>,
343        system: T,
344    ) -> Result<Out, RunSystemError>
345    where
346        T: IntoSystem<In, Out, Marker>,
347        In: SystemInput,
348    {
349        let mut system: T::System = IntoSystem::into_system(system);
350        system.initialize(self);
351        if system.validate_param(self) {
352            Ok(system.run(input, self))
353        } else {
354            Err(RunSystemError::InvalidParams(system.name()))
355        }
356    }
357}
358
359/// Running system failed.
360#[derive(Error, Display)]
361pub enum RunSystemError {
362    /// System could not be run due to parameters that failed validation.
363    ///
364    /// This can occur because the data required by the system was not present in the world.
365    #[display("The data required by the system {_0:?} was not found in the world and the system did not run due to failed parameter validation.")]
366    #[error(ignore)]
367    InvalidParams(Cow<'static, str>),
368}
369
370impl Debug for RunSystemError {
371    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
372        match self {
373            Self::InvalidParams(arg0) => f.debug_tuple("InvalidParams").field(arg0).finish(),
374        }
375    }
376}
377
378#[cfg(test)]
379mod tests {
380    use super::*;
381    use crate as bevy_ecs;
382    use crate::prelude::*;
383
384    #[test]
385    fn run_system_once() {
386        struct T(usize);
387
388        impl Resource for T {}
389
390        fn system(In(n): In<usize>, mut commands: Commands) -> usize {
391            commands.insert_resource(T(n));
392            n + 1
393        }
394
395        let mut world = World::default();
396        let n = world.run_system_once_with(1, system).unwrap();
397        assert_eq!(n, 2);
398        assert_eq!(world.resource::<T>().0, 1);
399    }
400
401    #[derive(Resource, Default, PartialEq, Debug)]
402    struct Counter(u8);
403
404    #[allow(dead_code)]
405    fn count_up(mut counter: ResMut<Counter>) {
406        counter.0 += 1;
407    }
408
409    #[test]
410    fn run_two_systems() {
411        let mut world = World::new();
412        world.init_resource::<Counter>();
413        assert_eq!(*world.resource::<Counter>(), Counter(0));
414        world.run_system_once(count_up).unwrap();
415        assert_eq!(*world.resource::<Counter>(), Counter(1));
416        world.run_system_once(count_up).unwrap();
417        assert_eq!(*world.resource::<Counter>(), Counter(2));
418    }
419
420    #[allow(dead_code)]
421    fn spawn_entity(mut commands: Commands) {
422        commands.spawn_empty();
423    }
424
425    #[test]
426    fn command_processing() {
427        let mut world = World::new();
428        assert_eq!(world.entities.len(), 0);
429        world.run_system_once(spawn_entity).unwrap();
430        assert_eq!(world.entities.len(), 1);
431    }
432
433    #[test]
434    fn non_send_resources() {
435        fn non_send_count_down(mut ns: NonSendMut<Counter>) {
436            ns.0 -= 1;
437        }
438
439        let mut world = World::new();
440        world.insert_non_send_resource(Counter(10));
441        assert_eq!(*world.non_send_resource::<Counter>(), Counter(10));
442        world.run_system_once(non_send_count_down).unwrap();
443        assert_eq!(*world.non_send_resource::<Counter>(), Counter(9));
444    }
445
446    #[test]
447    fn run_system_once_invalid_params() {
448        struct T;
449        impl Resource for T {}
450        fn system(_: Res<T>) {}
451
452        let mut world = World::default();
453        // This fails because `T` has not been added to the world yet.
454        let result = world.run_system_once(system.param_warn_once());
455
456        assert!(matches!(result, Err(RunSystemError::InvalidParams(_))));
457    }
458}