#![expect(1clippy::module_inception,2reason = "This instance of module inception is being discussed; see #17353."3)]4use bevy_utils::prelude::DebugName;5use bitflags::bitflags;6use core::fmt::{Debug, Display};7use log::warn;89use crate::{10component::{CheckChangeTicks, Tick},11error::BevyError,12query::FilteredAccessSet,13schedule::InternedSystemSet,14system::{input::SystemInput, SystemIn},15world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, World},16};1718use alloc::{boxed::Box, vec::Vec};19use core::any::{Any, TypeId};2021use super::{IntoSystem, SystemParamValidationError};2223bitflags! {24/// Bitflags representing system states and requirements.25#[derive(Clone, Copy, PartialEq, Eq, Hash)]26pub struct SystemStateFlags: u8 {27/// Set if system cannot be sent across threads28const NON_SEND = 1 << 0;29/// Set if system requires exclusive World access30const EXCLUSIVE = 1 << 1;31/// Set if system has deferred buffers.32const DEFERRED = 1 << 2;33}34}35/// An ECS system that can be added to a [`Schedule`](crate::schedule::Schedule)36///37/// Systems are functions with all arguments implementing38/// [`SystemParam`](crate::system::SystemParam).39///40/// Systems are added to an application using `App::add_systems(Update, my_system)`41/// or similar methods, and will generally run once per pass of the main loop.42///43/// Systems are executed in parallel, in opportunistic order; data access is managed automatically.44/// It's possible to specify explicit execution order between specific systems,45/// see [`IntoScheduleConfigs`](crate::schedule::IntoScheduleConfigs).46#[diagnostic::on_unimplemented(message = "`{Self}` is not a system", label = "invalid system")]47pub trait System: Send + Sync + 'static {48/// The system's input.49type In: SystemInput;50/// The system's output.51type Out;5253/// Returns the system's name.54fn name(&self) -> DebugName;55/// Returns the [`TypeId`] of the underlying system type.56#[inline]57fn type_id(&self) -> TypeId {58TypeId::of::<Self>()59}6061/// Returns the [`SystemStateFlags`] of the system.62fn flags(&self) -> SystemStateFlags;6364/// Returns true if the system is [`Send`].65#[inline]66fn is_send(&self) -> bool {67!self.flags().intersects(SystemStateFlags::NON_SEND)68}6970/// Returns true if the system must be run exclusively.71#[inline]72fn is_exclusive(&self) -> bool {73self.flags().intersects(SystemStateFlags::EXCLUSIVE)74}7576/// Returns true if system has deferred buffers.77#[inline]78fn has_deferred(&self) -> bool {79self.flags().intersects(SystemStateFlags::DEFERRED)80}8182/// Runs the system with the given input in the world. Unlike [`System::run`], this function83/// can be called in parallel with other systems and may break Rust's aliasing rules84/// if used incorrectly, making it unsafe to call.85///86/// Unlike [`System::run`], this will not apply deferred parameters, which must be independently87/// applied by calling [`System::apply_deferred`] at later point in time.88///89/// # Safety90///91/// - The caller must ensure that [`world`](UnsafeWorldCell) has permission to access any world data92/// registered in the access returned from [`System::initialize`]. There must be no conflicting93/// simultaneous accesses while the system is running.94/// - If [`System::is_exclusive`] returns `true`, then it must be valid to call95/// [`UnsafeWorldCell::world_mut`] on `world`.96unsafe fn run_unsafe(97&mut self,98input: SystemIn<'_, Self>,99world: UnsafeWorldCell,100) -> Result<Self::Out, RunSystemError>;101102/// Refresh the inner pointer based on the latest hot patch jump table103#[cfg(feature = "hotpatching")]104fn refresh_hotpatch(&mut self);105106/// Runs the system with the given input in the world.107///108/// For [read-only](ReadOnlySystem) systems, see [`run_readonly`], which can be called using `&World`.109///110/// Unlike [`System::run_unsafe`], this will apply deferred parameters *immediately*.111///112/// [`run_readonly`]: ReadOnlySystem::run_readonly113fn run(114&mut self,115input: SystemIn<'_, Self>,116world: &mut World,117) -> Result<Self::Out, RunSystemError> {118let ret = self.run_without_applying_deferred(input, world)?;119self.apply_deferred(world);120Ok(ret)121}122123/// Runs the system with the given input in the world.124///125/// [`run_readonly`]: ReadOnlySystem::run_readonly126fn run_without_applying_deferred(127&mut self,128input: SystemIn<'_, Self>,129world: &mut World,130) -> Result<Self::Out, RunSystemError> {131let world_cell = world.as_unsafe_world_cell();132// SAFETY:133// - We have exclusive access to the entire world.134unsafe { self.validate_param_unsafe(world_cell) }?;135// SAFETY:136// - We have exclusive access to the entire world.137unsafe { self.run_unsafe(input, world_cell) }138}139140/// Applies any [`Deferred`](crate::system::Deferred) system parameters (or other system buffers) of this system to the world.141///142/// This is where [`Commands`](crate::system::Commands) get applied.143fn apply_deferred(&mut self, world: &mut World);144145/// Enqueues any [`Deferred`](crate::system::Deferred) system parameters (or other system buffers)146/// of this system into the world's command buffer.147fn queue_deferred(&mut self, world: DeferredWorld);148149/// Validates that all parameters can be acquired and that system can run without panic.150/// Built-in executors use this to prevent invalid systems from running.151///152/// However calling and respecting [`System::validate_param_unsafe`] or its safe variant153/// is not a strict requirement, both [`System::run`] and [`System::run_unsafe`]154/// should provide their own safety mechanism to prevent undefined behavior.155///156/// This method has to be called directly before [`System::run_unsafe`] with no other (relevant)157/// world mutations in between. Otherwise, while it won't lead to any undefined behavior,158/// the validity of the param may change.159///160/// # Safety161///162/// - The caller must ensure that [`world`](UnsafeWorldCell) has permission to access any world data163/// registered in the access returned from [`System::initialize`]. There must be no conflicting164/// simultaneous accesses while the system is running.165unsafe fn validate_param_unsafe(166&mut self,167world: UnsafeWorldCell,168) -> Result<(), SystemParamValidationError>;169170/// Safe version of [`System::validate_param_unsafe`].171/// that runs on exclusive, single-threaded `world` pointer.172fn validate_param(&mut self, world: &World) -> Result<(), SystemParamValidationError> {173let world_cell = world.as_unsafe_world_cell_readonly();174// SAFETY:175// - We have exclusive access to the entire world.176unsafe { self.validate_param_unsafe(world_cell) }177}178179/// Initialize the system.180///181/// Returns a [`FilteredAccessSet`] with the access required to run the system.182fn initialize(&mut self, _world: &mut World) -> FilteredAccessSet;183184/// Checks any [`Tick`]s stored on this system and wraps their value if they get too old.185///186/// This method must be called periodically to ensure that change detection behaves correctly.187/// When using bevy's default configuration, this will be called for you as needed.188fn check_change_tick(&mut self, check: CheckChangeTicks);189190/// Returns the system's default [system sets](crate::schedule::SystemSet).191///192/// Each system will create a default system set that contains the system.193fn default_system_sets(&self) -> Vec<InternedSystemSet> {194Vec::new()195}196197/// Gets the tick indicating the last time this system ran.198fn get_last_run(&self) -> Tick;199200/// Overwrites the tick indicating the last time this system ran.201///202/// # Warning203/// This is a complex and error-prone operation, that can have unexpected consequences on any system relying on this code.204/// However, it can be an essential escape hatch when, for example,205/// you are trying to synchronize representations using change detection and need to avoid infinite recursion.206fn set_last_run(&mut self, last_run: Tick);207}208209/// [`System`] types that do not modify the [`World`] when run.210/// This is implemented for any systems whose parameters all implement [`ReadOnlySystemParam`].211///212/// Note that systems which perform [deferred](System::apply_deferred) mutations (such as with [`Commands`])213/// may implement this trait.214///215/// [`ReadOnlySystemParam`]: crate::system::ReadOnlySystemParam216/// [`Commands`]: crate::system::Commands217///218/// # Safety219///220/// This must only be implemented for system types which do not mutate the `World`221/// when [`System::run_unsafe`] is called.222#[diagnostic::on_unimplemented(223message = "`{Self}` is not a read-only system",224label = "invalid read-only system"225)]226pub unsafe trait ReadOnlySystem: System {227/// Runs this system with the given input in the world.228///229/// Unlike [`System::run`], this can be called with a shared reference to the world,230/// since this system is known not to modify the world.231fn run_readonly(232&mut self,233input: SystemIn<'_, Self>,234world: &World,235) -> Result<Self::Out, RunSystemError> {236let world = world.as_unsafe_world_cell_readonly();237// SAFETY:238// - We have read-only access to the entire world.239unsafe { self.validate_param_unsafe(world) }?;240// SAFETY:241// - We have read-only access to the entire world.242unsafe { self.run_unsafe(input, world) }243}244}245246/// A convenience type alias for a boxed [`System`] trait object.247pub type BoxedSystem<In = (), Out = ()> = Box<dyn System<In = In, Out = Out>>;248249/// A convenience type alias for a boxed [`ReadOnlySystem`] trait object.250pub type BoxedReadOnlySystem<In = (), Out = ()> = Box<dyn ReadOnlySystem<In = In, Out = Out>>;251252pub(crate) fn check_system_change_tick(253last_run: &mut Tick,254check: CheckChangeTicks,255system_name: DebugName,256) {257if last_run.check_tick(check) {258let age = check.present_tick().relative_to(*last_run).get();259warn!(260"System '{system_name}' has not run for {age} ticks. \261Changes older than {} ticks will not be detected.",262Tick::MAX.get() - 1,263);264}265}266267impl<In, Out> Debug for dyn System<In = In, Out = Out>268where269In: SystemInput + 'static,270Out: 'static,271{272fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {273f.debug_struct("System")274.field("name", &self.name())275.field("is_exclusive", &self.is_exclusive())276.field("is_send", &self.is_send())277.finish_non_exhaustive()278}279}280281/// Trait used to run a system immediately on a [`World`].282///283/// # Warning284/// This function is not an efficient method of running systems and it's meant to be used as a utility285/// for testing and/or diagnostics.286///287/// Systems called through [`run_system_once`](RunSystemOnce::run_system_once) do not hold onto any state,288/// as they are created and destroyed every time [`run_system_once`](RunSystemOnce::run_system_once) is called.289/// Practically, this means that [`Local`](crate::system::Local) variables are290/// reset on every run and change detection does not work.291///292/// ```293/// # use bevy_ecs::prelude::*;294/// # use bevy_ecs::system::RunSystemOnce;295/// #[derive(Resource, Default)]296/// struct Counter(u8);297///298/// fn increment(mut counter: Local<Counter>) {299/// counter.0 += 1;300/// println!("{}", counter.0);301/// }302///303/// let mut world = World::default();304/// world.run_system_once(increment); // prints 1305/// world.run_system_once(increment); // still prints 1306/// ```307///308/// If you do need systems to hold onto state between runs, use [`World::run_system_cached`](World::run_system_cached)309/// or [`World::run_system`](World::run_system).310///311/// # Usage312/// Typically, to test a system, or to extract specific diagnostics information from a world,313/// you'd need a [`Schedule`](crate::schedule::Schedule) to run the system. This can create redundant boilerplate code314/// when writing tests or trying to quickly iterate on debug specific systems.315///316/// For these situations, this function can be useful because it allows you to execute a system317/// immediately with some custom input and retrieve its output without requiring the necessary boilerplate.318///319/// # Examples320///321/// ## Immediate Command Execution322///323/// This usage is helpful when trying to test systems or functions that operate on [`Commands`](crate::system::Commands):324/// ```325/// # use bevy_ecs::prelude::*;326/// # use bevy_ecs::system::RunSystemOnce;327/// let mut world = World::default();328/// let entity = world.run_system_once(|mut commands: Commands| {329/// commands.spawn_empty().id()330/// }).unwrap();331/// # assert!(world.get_entity(entity).is_ok());332/// ```333///334/// ## Immediate Queries335///336/// This usage is helpful when trying to run an arbitrary query on a world for testing or debugging purposes:337/// ```338/// # use bevy_ecs::prelude::*;339/// # use bevy_ecs::system::RunSystemOnce;340///341/// #[derive(Component)]342/// struct T(usize);343///344/// let mut world = World::default();345/// world.spawn(T(0));346/// world.spawn(T(1));347/// world.spawn(T(1));348/// let count = world.run_system_once(|query: Query<&T>| {349/// query.iter().filter(|t| t.0 == 1).count()350/// }).unwrap();351///352/// # assert_eq!(count, 2);353/// ```354///355/// Note that instead of closures you can also pass in regular functions as systems:356///357/// ```358/// # use bevy_ecs::prelude::*;359/// # use bevy_ecs::system::RunSystemOnce;360///361/// #[derive(Component)]362/// struct T(usize);363///364/// fn count(query: Query<&T>) -> usize {365/// query.iter().filter(|t| t.0 == 1).count()366/// }367///368/// let mut world = World::default();369/// world.spawn(T(0));370/// world.spawn(T(1));371/// world.spawn(T(1));372/// let count = world.run_system_once(count).unwrap();373///374/// # assert_eq!(count, 2);375/// ```376pub trait RunSystemOnce: Sized {377/// Tries to run a system and apply its deferred parameters.378fn run_system_once<T, Out, Marker>(self, system: T) -> Result<Out, RunSystemError>379where380T: IntoSystem<(), Out, Marker>,381{382self.run_system_once_with(system, ())383}384385/// Tries to run a system with given input and apply deferred parameters.386fn run_system_once_with<T, In, Out, Marker>(387self,388system: T,389input: SystemIn<'_, T::System>,390) -> Result<Out, RunSystemError>391where392T: IntoSystem<In, Out, Marker>,393In: SystemInput;394}395396impl RunSystemOnce for &mut World {397fn run_system_once_with<T, In, Out, Marker>(398self,399system: T,400input: SystemIn<'_, T::System>,401) -> Result<Out, RunSystemError>402where403T: IntoSystem<In, Out, Marker>,404In: SystemInput,405{406let mut system: T::System = IntoSystem::into_system(system);407system.initialize(self);408system.run(input, self)409}410}411412/// Running system failed.413#[derive(Debug)]414pub enum RunSystemError {415/// System could not be run due to parameters that failed validation.416/// This is not considered an error.417Skipped(SystemParamValidationError),418/// System returned an error or failed required parameter validation.419Failed(BevyError),420}421422impl Display for RunSystemError {423fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {424match self {425Self::Skipped(err) => write!(426f,427"System did not run due to failed parameter validation: {err}"428),429Self::Failed(err) => write!(f, "{err}"),430}431}432}433434impl<E: Any> From<E> for RunSystemError435where436BevyError: From<E>,437{438fn from(mut value: E) -> Self {439// Specialize the impl so that a skipped `SystemParamValidationError`440// is converted to `Skipped` instead of `Failed`.441// Note that the `downcast_mut` check is based on the static type,442// and can be optimized out after monomorphization.443let any: &mut dyn Any = &mut value;444if let Some(err) = any.downcast_mut::<SystemParamValidationError>() {445if err.skipped {446return Self::Skipped(core::mem::replace(err, SystemParamValidationError::EMPTY));447}448}449Self::Failed(From::from(value))450}451}452453#[cfg(test)]454mod tests {455use super::*;456use crate::prelude::*;457use alloc::string::ToString;458459#[test]460fn run_system_once() {461struct T(usize);462463impl Resource for T {}464465fn system(In(n): In<usize>, mut commands: Commands) -> usize {466commands.insert_resource(T(n));467n + 1468}469470let mut world = World::default();471let n = world.run_system_once_with(system, 1).unwrap();472assert_eq!(n, 2);473assert_eq!(world.resource::<T>().0, 1);474}475476#[derive(Resource, Default, PartialEq, Debug)]477struct Counter(u8);478479fn count_up(mut counter: ResMut<Counter>) {480counter.0 += 1;481}482483#[test]484fn run_two_systems() {485let mut world = World::new();486world.init_resource::<Counter>();487assert_eq!(*world.resource::<Counter>(), Counter(0));488world.run_system_once(count_up).unwrap();489assert_eq!(*world.resource::<Counter>(), Counter(1));490world.run_system_once(count_up).unwrap();491assert_eq!(*world.resource::<Counter>(), Counter(2));492}493494#[derive(Component)]495struct A;496497fn spawn_entity(mut commands: Commands) {498commands.spawn(A);499}500501#[test]502fn command_processing() {503let mut world = World::new();504assert_eq!(world.query::<&A>().query(&world).count(), 0);505world.run_system_once(spawn_entity).unwrap();506assert_eq!(world.query::<&A>().query(&world).count(), 1);507}508509#[test]510fn non_send_resources() {511fn non_send_count_down(mut ns: NonSendMut<Counter>) {512ns.0 -= 1;513}514515let mut world = World::new();516world.insert_non_send_resource(Counter(10));517assert_eq!(*world.non_send_resource::<Counter>(), Counter(10));518world.run_system_once(non_send_count_down).unwrap();519assert_eq!(*world.non_send_resource::<Counter>(), Counter(9));520}521522#[test]523fn run_system_once_invalid_params() {524struct T;525impl Resource for T {}526fn system(_: Res<T>) {}527528let mut world = World::default();529// This fails because `T` has not been added to the world yet.530let result = world.run_system_once(system);531532assert!(matches!(result, Err(RunSystemError::Failed { .. })));533534let expected = "Resource does not exist";535let actual = result.unwrap_err().to_string();536537assert!(538actual.contains(expected),539"Expected error message to contain `{}` but got `{}`",540expected,541actual542);543}544}545546547