repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_utils/src/parallel_queue.rs
crates/bevy_utils/src/parallel_queue.rs
use alloc::vec::Vec; use core::{cell::RefCell, ops::DerefMut}; use thread_local::ThreadLocal; /// A cohesive set of thread-local values of a given type. /// /// Mutable references can be fetched if `T: Default` via [`Parallel::scope`]. pub struct Parallel<T: Send> { locals: ThreadLocal<RefCell<T>>, } impl<T: Send> Parallel<T> { /// Gets a mutable iterator over all of the per-thread queues. pub fn iter_mut(&mut self) -> impl Iterator<Item = &'_ mut T> { self.locals.iter_mut().map(RefCell::get_mut) } /// Clears all of the stored thread local values. pub fn clear(&mut self) { self.locals.clear(); } /// Retrieves the thread-local value for the current thread and runs `f` on it. /// /// If there is no thread-local value, it will be initialized to the result /// of `create`. pub fn scope_or<R>(&self, create: impl FnOnce() -> T, f: impl FnOnce(&mut T) -> R) -> R { f(&mut self.borrow_local_mut_or(create)) } /// Mutably borrows the thread-local value. /// /// If there is no thread-local value, it will be initialized to the result /// of `create`. pub fn borrow_local_mut_or( &self, create: impl FnOnce() -> T, ) -> impl DerefMut<Target = T> + '_ { self.locals.get_or(|| RefCell::new(create())).borrow_mut() } } impl<T: Default + Send> Parallel<T> { /// Retrieves the thread-local value for the current thread and runs `f` on it. /// /// If there is no thread-local value, it will be initialized to its default. pub fn scope<R>(&self, f: impl FnOnce(&mut T) -> R) -> R { self.scope_or(Default::default, f) } /// Mutably borrows the thread-local value. /// /// If there is no thread-local value, it will be initialized to its default. pub fn borrow_local_mut(&self) -> impl DerefMut<Target = T> + '_ { self.borrow_local_mut_or(Default::default) } } impl<T, I> Parallel<I> where I: IntoIterator<Item = T> + Default + Send + 'static, { /// Drains all enqueued items from all threads and returns an iterator over them. /// /// Unlike [`Vec::drain`], this will piecemeal remove chunks of the data stored. /// If iteration is terminated part way, the rest of the enqueued items in the same /// chunk will be dropped, and the rest of the undrained elements will remain. /// /// The ordering is not guaranteed. pub fn drain(&mut self) -> impl Iterator<Item = T> + '_ { self.locals.iter_mut().flat_map(|item| item.take()) } } impl<T: Send> Parallel<Vec<T>> { /// Collect all enqueued items from all threads and appends them to the end of a /// single Vec. /// /// The ordering is not guaranteed. pub fn drain_into(&mut self, out: &mut Vec<T>) { let size = self .locals .iter_mut() .map(|queue| queue.get_mut().len()) .sum(); out.reserve(size); for queue in self.locals.iter_mut() { out.append(queue.get_mut()); } } } // `Default` is manually implemented to avoid the `T: Default` bound. impl<T: Send> Default for Parallel<T> { fn default() -> Self { Self { locals: ThreadLocal::default(), } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_utils/src/default.rs
crates/bevy_utils/src/default.rs
/// An ergonomic abbreviation for [`Default::default()`] to make initializing structs easier. /// /// This is especially helpful when combined with ["struct update syntax"](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax). /// ``` /// use bevy_utils::default; /// /// #[derive(Default)] /// struct Foo { /// a: usize, /// b: usize, /// c: usize, /// } /// /// // Normally you would initialize a struct with defaults using "struct update syntax" /// // combined with `Default::default()`. This example sets `Foo::a` to 10 and the remaining /// // values to their defaults. /// let foo = Foo { /// a: 10, /// ..Default::default() /// }; /// /// // But now you can do this, which is equivalent: /// let foo = Foo { /// a: 10, /// ..default() /// }; /// ``` #[inline] pub fn default<T: Default>() -> T { Default::default() }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_utils/src/map.rs
crates/bevy_utils/src/map.rs
use core::{any::TypeId, hash::Hash}; use bevy_platform::{ collections::{hash_map::Entry, HashMap}, hash::{Hashed, NoOpHash, PassHash}, }; /// A [`HashMap`] pre-configured to use [`Hashed`] keys and [`PassHash`] passthrough hashing. /// Iteration order only depends on the order of insertions and deletions. pub type PreHashMap<K, V> = HashMap<Hashed<K>, V, PassHash>; /// Extension methods intended to add functionality to [`PreHashMap`]. pub trait PreHashMapExt<K, V> { /// Tries to get or insert the value for the given `key` using the pre-computed hash first. /// If the [`PreHashMap`] does not already contain the `key`, it will clone it and insert /// the value returned by `func`. fn get_or_insert_with<F: FnOnce() -> V>(&mut self, key: &Hashed<K>, func: F) -> &mut V; } impl<K: Hash + Eq + PartialEq + Clone, V> PreHashMapExt<K, V> for PreHashMap<K, V> { #[inline] fn get_or_insert_with<F: FnOnce() -> V>(&mut self, key: &Hashed<K>, func: F) -> &mut V { use bevy_platform::collections::hash_map::RawEntryMut; let entry = self .raw_entry_mut() .from_key_hashed_nocheck(key.hash(), key); match entry { RawEntryMut::Occupied(entry) => entry.into_mut(), RawEntryMut::Vacant(entry) => { let (_, value) = entry.insert_hashed_nocheck(key.hash(), key.clone(), func()); value } } } } /// A specialized hashmap type with Key of [`TypeId`] /// Iteration order only depends on the order of insertions and deletions. pub type TypeIdMap<V> = HashMap<TypeId, V, NoOpHash>; /// Extension trait to make use of [`TypeIdMap`] more ergonomic. /// /// Each function on this trait is a trivial wrapper for a function /// on [`HashMap`], replacing a `TypeId` key with a /// generic parameter `T`. /// /// # Examples /// /// ```rust /// # use std::any::TypeId; /// # use bevy_utils::TypeIdMap; /// use bevy_utils::TypeIdMapExt; /// /// struct MyType; /// /// // Using the built-in `HashMap` functions requires manually looking up `TypeId`s. /// let mut map = TypeIdMap::default(); /// map.insert(TypeId::of::<MyType>(), 7); /// assert_eq!(map.get(&TypeId::of::<MyType>()), Some(&7)); /// /// // Using `TypeIdMapExt` functions does the lookup for you. /// map.insert_type::<MyType>(7); /// assert_eq!(map.get_type::<MyType>(), Some(&7)); /// ``` pub trait TypeIdMapExt<V> { /// Inserts a value for the type `T`. /// /// If the map did not previously contain this key then [`None`] is returned, /// otherwise the value for this key is updated and the old value returned. fn insert_type<T: ?Sized + 'static>(&mut self, v: V) -> Option<V>; /// Returns a reference to the value for type `T`, if one exists. fn get_type<T: ?Sized + 'static>(&self) -> Option<&V>; /// Returns a mutable reference to the value for type `T`, if one exists. fn get_type_mut<T: ?Sized + 'static>(&mut self) -> Option<&mut V>; /// Removes type `T` from the map, returning the value for this /// key if it was previously present. fn remove_type<T: ?Sized + 'static>(&mut self) -> Option<V>; /// Gets the type `T`'s entry in the map for in-place manipulation. fn entry_type<T: ?Sized + 'static>(&mut self) -> Entry<'_, TypeId, V, NoOpHash>; } impl<V> TypeIdMapExt<V> for TypeIdMap<V> { #[inline] fn insert_type<T: ?Sized + 'static>(&mut self, v: V) -> Option<V> { self.insert(TypeId::of::<T>(), v) } #[inline] fn get_type<T: ?Sized + 'static>(&self) -> Option<&V> { self.get(&TypeId::of::<T>()) } #[inline] fn get_type_mut<T: ?Sized + 'static>(&mut self) -> Option<&mut V> { self.get_mut(&TypeId::of::<T>()) } #[inline] fn remove_type<T: ?Sized + 'static>(&mut self) -> Option<V> { self.remove(&TypeId::of::<T>()) } #[inline] fn entry_type<T: ?Sized + 'static>(&mut self) -> Entry<'_, TypeId, V, NoOpHash> { self.entry(TypeId::of::<T>()) } } #[cfg(test)] mod tests { use super::*; use static_assertions::assert_impl_all; // Check that the HashMaps are Clone if the key/values are Clone assert_impl_all!(PreHashMap::<u64, usize>: Clone); #[test] fn fast_typeid_hash() { struct Hasher; impl core::hash::Hasher for Hasher { fn finish(&self) -> u64 { 0 } fn write(&mut self, _: &[u8]) { panic!("Hashing of core::any::TypeId changed"); } fn write_u64(&mut self, _: u64) {} } Hash::hash(&TypeId::of::<()>(), &mut Hasher); } crate::cfg::alloc! { #[test] fn stable_hash_within_same_program_execution() { use alloc::vec::Vec; let mut map_1 = <HashMap<_, _>>::default(); let mut map_2 = <HashMap<_, _>>::default(); for i in 1..10 { map_1.insert(i, i); map_2.insert(i, i); } assert_eq!( map_1.iter().collect::<Vec<_>>(), map_2.iter().collect::<Vec<_>>() ); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_utils/src/once.rs
crates/bevy_utils/src/once.rs
use bevy_platform::sync::atomic::{AtomicBool, Ordering}; /// Wrapper around an [`AtomicBool`], abstracting the backing implementation and /// ordering considerations. #[doc(hidden)] pub struct OnceFlag(AtomicBool); impl OnceFlag { /// Create a new flag in the unset state. pub const fn new() -> Self { Self(AtomicBool::new(true)) } /// Sets this flag. Will return `true` if this flag hasn't been set before. pub fn set(&self) -> bool { self.0.swap(false, Ordering::Relaxed) } } impl Default for OnceFlag { fn default() -> Self { Self::new() } } /// Call some expression only once per call site. #[macro_export] macro_rules! once { ($expression:expr) => {{ static SHOULD_FIRE: $crate::OnceFlag = $crate::OnceFlag::new(); if SHOULD_FIRE.set() { $expression; } }}; }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_macro_utils/src/fq_std.rs
crates/bevy_macro_utils/src/fq_std.rs
//! This module contains unit structs that should be used inside `quote!` and `spanned_quote!` //! using the variable interpolation syntax in place of their equivalent structs and traits //! present in `std`. //! //! To create hygienic proc macros, all the names must be its fully qualified form. These //! unit structs help us to not specify the fully qualified name every single time. //! //! # Example //! Instead of writing this: //! ``` //! # use quote::quote; //! quote!( //! fn get_id() -> Option<i32> { //! Some(0) //! } //! ); //! ``` //! Or this: //! ``` //! # use quote::quote; //! quote!( //! fn get_id() -> ::core::option::Option<i32> { //! ::core::option::Option::Some(0) //! } //! ); //! ``` //! We should write this: //! ``` //! use bevy_macro_utils::fq_std::FQOption; //! # use quote::quote; //! //! quote!( //! fn get_id() -> #FQOption<i32> { //! #FQOption::Some(0) //! } //! ); //! ``` use proc_macro2::TokenStream; use quote::{quote, ToTokens}; /// Fully Qualified (FQ) short name for [`std::any::Any`] pub struct FQAny; /// Fully Qualified (FQ) short name for [`Box`] pub struct FQBox; /// Fully Qualified (FQ) short name for [`Clone`] pub struct FQClone; /// Fully Qualified (FQ) short name for [`Default`] pub struct FQDefault; /// Fully Qualified (FQ) short name for [`Option`] pub struct FQOption; /// Fully Qualified (FQ) short name for [`Result`] pub struct FQResult; /// Fully Qualified (FQ) short name for [`Send`] pub struct FQSend; /// Fully Qualified (FQ) short name for [`Sync`] pub struct FQSync; impl ToTokens for FQAny { fn to_tokens(&self, tokens: &mut TokenStream) { quote!(::core::any::Any).to_tokens(tokens); } } impl ToTokens for FQBox { fn to_tokens(&self, tokens: &mut TokenStream) { quote!(::std::boxed::Box).to_tokens(tokens); } } impl ToTokens for FQClone { fn to_tokens(&self, tokens: &mut TokenStream) { quote!(::core::clone::Clone).to_tokens(tokens); } } impl ToTokens for FQDefault { fn to_tokens(&self, tokens: &mut TokenStream) { quote!(::core::default::Default).to_tokens(tokens); } } impl ToTokens for FQOption { fn to_tokens(&self, tokens: &mut TokenStream) { quote!(::core::option::Option).to_tokens(tokens); } } impl ToTokens for FQResult { fn to_tokens(&self, tokens: &mut TokenStream) { quote!(::core::result::Result).to_tokens(tokens); } } impl ToTokens for FQSend { fn to_tokens(&self, tokens: &mut TokenStream) { quote!(::core::marker::Send).to_tokens(tokens); } } impl ToTokens for FQSync { fn to_tokens(&self, tokens: &mut TokenStream) { quote!(::core::marker::Sync).to_tokens(tokens); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_macro_utils/src/result_sifter.rs
crates/bevy_macro_utils/src/result_sifter.rs
/// Helper struct used to process an iterator of `Result<Vec<T>, syn::Error>`, /// combining errors into one along the way. pub struct ResultSifter<T> { items: Vec<T>, errors: Option<syn::Error>, } impl<T> Default for ResultSifter<T> { fn default() -> Self { Self { items: Vec::new(), errors: None, } } } impl<T> ResultSifter<T> { /// Sift the given result, combining errors if necessary. pub fn sift(&mut self, result: Result<T, syn::Error>) { match result { Ok(data) => self.items.push(data), Err(err) => { if let Some(ref mut errors) = self.errors { errors.combine(err); } else { self.errors = Some(err); } } } } /// Associated method that provides a convenient implementation for [`Iterator::fold`]. pub fn fold(mut sifter: Self, result: Result<T, syn::Error>) -> Self { sifter.sift(result); sifter } /// Complete the sifting process and return the final result. pub fn finish(self) -> Result<Vec<T>, syn::Error> { if let Some(errors) = self.errors { Err(errors) } else { Ok(self.items) } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_macro_utils/src/attrs.rs
crates/bevy_macro_utils/src/attrs.rs
use syn::{Expr, ExprLit, Lit}; use crate::symbol::Symbol; /// Get a [literal string](struct@syn::LitStr) from the provided [expression](Expr). pub fn get_lit_str(attr_name: Symbol, value: &Expr) -> syn::Result<&syn::LitStr> { if let Expr::Lit(ExprLit { lit: Lit::Str(lit), .. }) = &value { Ok(lit) } else { Err(syn::Error::new_spanned( value, format!("expected {attr_name} attribute to be a string: `{attr_name} = \"...\"`"), )) } } /// Get a [literal boolean](struct@syn::LitBool) from the provided [expression](Expr) as a [`bool`]. pub fn get_lit_bool(attr_name: Symbol, value: &Expr) -> syn::Result<bool> { if let Expr::Lit(ExprLit { lit: Lit::Bool(lit), .. }) = &value { Ok(lit.value()) } else { Err(syn::Error::new_spanned( value, format!("expected {attr_name} attribute to be a bool value, `true` or `false`: `{attr_name} = ...`"), ))? } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_macro_utils/src/shape.rs
crates/bevy_macro_utils/src/shape.rs
use syn::{ punctuated::Punctuated, spanned::Spanned, token::Comma, Data, DataEnum, DataUnion, Error, Field, Fields, }; /// Get the fields of a data structure if that structure is a struct; /// otherwise, return a compile error that points to the site of the macro invocation. /// /// `meta` should be the name of the macro calling this function. pub fn get_struct_fields<'a>(data: &'a Data, meta: &str) -> Result<&'a Fields, Error> { match data { Data::Struct(data_struct) => Ok(&data_struct.fields), Data::Enum(DataEnum { enum_token, .. }) => Err(Error::new( enum_token.span(), format!("#[{meta}] only supports structs, not enums"), )), Data::Union(DataUnion { union_token, .. }) => Err(Error::new( union_token.span(), format!("#[{meta}] only supports structs, not unions"), )), } } /// Return an error if `Fields` is not `Fields::Named` pub fn require_named<'a>(fields: &'a Fields) -> Result<&'a Punctuated<Field, Comma>, Error> { if let Fields::Named(fields) = fields { Ok(&fields.named) } else { Err(Error::new( fields.span(), "Unnamed fields are not supported here", )) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_macro_utils/src/lib.rs
crates/bevy_macro_utils/src/lib.rs
#![forbid(unsafe_code)] #![cfg_attr(docsrs, feature(doc_cfg))] #![doc( html_logo_url = "https://bevy.org/assets/icon.png", html_favicon_url = "https://bevy.org/assets/icon.png" )] //! A collection of helper types and functions for working on macros within the Bevy ecosystem. extern crate alloc; extern crate proc_macro; mod attrs; mod bevy_manifest; pub mod fq_std; mod label; mod member; mod parser; mod result_sifter; mod shape; mod symbol; pub use attrs::*; pub use bevy_manifest::*; pub use label::*; pub use member::*; pub use parser::*; pub use result_sifter::*; pub use shape::*; pub use symbol::*;
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_macro_utils/src/parser.rs
crates/bevy_macro_utils/src/parser.rs
use syn::{ parse::{Parse, ParseStream, Peek}, punctuated::Punctuated, }; /// Returns a [`syn::parse::Parser`] which parses a stream of zero or more occurrences of `T` /// separated by punctuation of type `P`, with optional trailing punctuation. /// /// This is functionally the same as [`Punctuated::parse_terminated`], /// but accepts a closure rather than a function pointer. pub fn terminated_parser<T, P, F: FnMut(ParseStream) -> syn::Result<T>>( terminator: P, mut parser: F, ) -> impl FnOnce(ParseStream) -> syn::Result<Punctuated<T, P::Token>> where P: Peek, P::Token: Parse, { let _ = terminator; move |stream: ParseStream| { let mut punctuated = Punctuated::new(); loop { if stream.is_empty() { break; } let value = parser(stream)?; punctuated.push_value(value); if stream.is_empty() { break; } let punct = stream.parse()?; punctuated.push_punct(punct); } Ok(punctuated) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_macro_utils/src/bevy_manifest.rs
crates/bevy_macro_utils/src/bevy_manifest.rs
extern crate proc_macro; use alloc::collections::BTreeMap; use proc_macro::TokenStream; use std::sync::{PoisonError, RwLock}; use std::{ env, path::{Path, PathBuf}, time::SystemTime, }; use toml_edit::{Document, Item}; /// The path to the `Cargo.toml` file for the Bevy project. #[derive(Debug)] pub struct BevyManifest { manifest: Document<Box<str>>, modified_time: SystemTime, } const BEVY: &str = "bevy"; impl BevyManifest { /// Calls `f` with a global shared instance of the [`BevyManifest`] struct. pub fn shared<R>(f: impl FnOnce(&BevyManifest) -> R) -> R { static MANIFESTS: RwLock<BTreeMap<PathBuf, BevyManifest>> = RwLock::new(BTreeMap::new()); let manifest_path = Self::get_manifest_path(); let modified_time = Self::get_manifest_modified_time(&manifest_path) .expect("The Cargo.toml should have a modified time"); let manifests = MANIFESTS.read().unwrap_or_else(PoisonError::into_inner); if let Some(manifest) = manifests.get(&manifest_path) && manifest.modified_time == modified_time { return f(manifest); } drop(manifests); let manifest = BevyManifest { manifest: Self::read_manifest(&manifest_path), modified_time, }; let key = manifest_path.clone(); // TODO: Switch to using RwLockWriteGuard::downgrade when it stabilizes. MANIFESTS .write() .unwrap_or_else(PoisonError::into_inner) .insert(key, manifest); f(MANIFESTS .read() .unwrap_or_else(PoisonError::into_inner) .get(&manifest_path) .unwrap()) } fn get_manifest_path() -> PathBuf { env::var_os("CARGO_MANIFEST_DIR") .map(|path| { let mut path = PathBuf::from(path); path.push("Cargo.toml"); assert!( path.exists(), "Cargo manifest does not exist at path {}", path.display() ); path }) .expect("CARGO_MANIFEST_DIR is not defined.") } fn get_manifest_modified_time( cargo_manifest_path: &Path, ) -> Result<SystemTime, std::io::Error> { std::fs::metadata(cargo_manifest_path).and_then(|metadata| metadata.modified()) } fn read_manifest(path: &Path) -> Document<Box<str>> { let manifest = std::fs::read_to_string(path) .unwrap_or_else(|_| panic!("Unable to read cargo manifest: {}", path.display())) .into_boxed_str(); Document::parse(manifest) .unwrap_or_else(|_| panic!("Failed to parse cargo manifest: {}", path.display())) } /// Attempt to retrieve the [path](syn::Path) of a particular package in /// the [manifest](BevyManifest) by [name](str). pub fn maybe_get_path(&self, name: &str) -> Option<syn::Path> { let find_in_deps = |deps: &Item| -> Option<syn::Path> { let package = if deps.get(name).is_some() { return Some(Self::parse_str(name)); } else if deps.get(BEVY).is_some() { BEVY } else { // Note: to support bevy crate aliases, we could do scanning here to find a crate with a "package" name that // matches our request, but that would then mean we are scanning every dependency (and dev dependency) for every // macro execution that hits this branch (which includes all built-in bevy crates). Our current stance is that supporting // remapped crate names in derive macros is not worth that "compile time" price of admission. As a workaround, people aliasing // bevy crate names can use "use REMAPPED as bevy_X" or "use REMAPPED::x as bevy_x". return None; }; let mut path = Self::parse_str::<syn::Path>(&format!("::{package}")); if let Some(module) = name.strip_prefix("bevy_") { path.segments.push(Self::parse_str(module)); } Some(path) }; let deps = self.manifest.get("dependencies"); let deps_dev = self.manifest.get("dev-dependencies"); deps.and_then(find_in_deps) .or_else(|| deps_dev.and_then(find_in_deps)) } /// Attempt to parse the provided [path](str) as a [syntax tree node](syn::parse::Parse) pub fn try_parse_str<T: syn::parse::Parse>(path: &str) -> Option<T> { syn::parse(path.parse::<TokenStream>().ok()?).ok() } /// Returns the path for the crate with the given name. pub fn get_path(&self, name: &str) -> syn::Path { self.maybe_get_path(name) .unwrap_or_else(|| Self::parse_str(name)) } /// Attempt to parse provided [path](str) as a [syntax tree node](syn::parse::Parse). /// /// # Panics /// /// Will panic if the path is not able to be parsed. For a non-panicking option, see [`try_parse_str`] /// /// [`try_parse_str`]: Self::try_parse_str pub fn parse_str<T: syn::parse::Parse>(path: &str) -> T { Self::try_parse_str(path).unwrap() } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_macro_utils/src/label.rs
crates/bevy_macro_utils/src/label.rs
use proc_macro::{TokenStream, TokenTree}; use quote::{quote, quote_spanned}; use std::collections::HashSet; use syn::{spanned::Spanned, Ident}; /// Finds an identifier that will not conflict with the specified set of tokens. /// /// If the identifier is present in `haystack`, extra characters will be added /// to it until it no longer conflicts with anything. /// /// Note that the returned identifier can still conflict in niche cases, /// such as if an identifier in `haystack` is hidden behind an un-expanded macro. pub fn ensure_no_collision(value: Ident, haystack: TokenStream) -> Ident { // Collect all the identifiers in `haystack` into a set. let idents = { // List of token streams that will be visited in future loop iterations. let mut unvisited = vec![haystack]; // Identifiers we have found while searching tokens. let mut found = HashSet::new(); while let Some(tokens) = unvisited.pop() { for t in tokens { match t { // Collect any identifiers we encounter. TokenTree::Ident(ident) => { found.insert(ident.to_string()); } // Queue up nested token streams to be visited in a future loop iteration. TokenTree::Group(g) => unvisited.push(g.stream()), TokenTree::Punct(_) | TokenTree::Literal(_) => {} } } } found }; let span = value.span(); // If there's a collision, add more characters to the identifier // until it doesn't collide with anything anymore. let mut value = value.to_string(); while idents.contains(&value) { value.push('X'); } Ident::new(&value, span) } /// Derive a label trait /// /// # Args /// /// - `input`: The [`syn::DeriveInput`] for struct that is deriving the label trait /// - `trait_name`: Name of the label trait /// - `trait_path`: The [path](`syn::Path`) to the label trait /// - `dyn_eq_path`: The [path](`syn::Path`) to the `DynEq` trait pub fn derive_label( input: syn::DeriveInput, trait_name: &str, trait_path: &syn::Path, ) -> TokenStream { if let syn::Data::Union(_) = &input.data { let message = format!("Cannot derive {trait_name} for unions."); return quote_spanned! { input.span() => compile_error!(#message); } .into(); } let ident = input.ident.clone(); let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let mut where_clause = where_clause.cloned().unwrap_or_else(|| syn::WhereClause { where_token: Default::default(), predicates: Default::default(), }); where_clause.predicates.push( syn::parse2(quote! { Self: 'static + Send + Sync + Clone + Eq + ::core::fmt::Debug + ::core::hash::Hash }) .unwrap(), ); quote! { // To ensure alloc is available, but also prevent its name from clashing, we place the implementation inside an anonymous constant const _: () = { extern crate alloc; impl #impl_generics #trait_path for #ident #ty_generics #where_clause { fn dyn_clone(&self) -> alloc::boxed::Box<dyn #trait_path> { alloc::boxed::Box::new(::core::clone::Clone::clone(self)) } } }; } .into() }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_macro_utils/src/member.rs
crates/bevy_macro_utils/src/member.rs
use syn::{Ident, Member}; /// Converts an optional identifier or index into a [`syn::Member`] variant. /// /// This is useful for when you want to access a field inside a `quote!` block regardless of whether it is an identifier or an index. /// There is also [`syn::Fields::members`], but this method doesn't work when you're dealing with single / filtered fields. /// /// Rust struct syntax allows for `Struct { foo: "string" }` with explicitly /// named fields. It allows the `Struct { 0: "string" }` syntax when the struct /// is declared as a tuple struct. /// /// # Example /// ```rust /// use syn::{Ident, parse_str, DeriveInput, Data, DataStruct}; /// use quote::quote; /// use bevy_macro_utils::as_member; /// /// let ast: DeriveInput = syn::parse_str( /// r#" /// struct Mystruct { /// field: usize, /// #[my_derive] /// other_field: usize /// } /// "#, /// ) /// .unwrap(); /// /// let Data::Struct(DataStruct { fields, .. }) = &ast.data else { return }; /// /// let field_members = fields /// .iter() /// .enumerate() /// .filter(|(_, field)| field.attrs.iter().any(|attr| attr.path().is_ident("my_derive"))) /// .map(|(i, field)| { as_member(field.ident.as_ref(), i) }); /// /// // it won't matter now if it's a named field or a unnamed field. e.g self.field or self.0 /// quote!( /// #(self.#field_members.do_something();)* /// ); /// /// ``` /// pub fn as_member(ident: Option<&Ident>, index: usize) -> Member { ident.map_or_else(|| Member::from(index), |ident| Member::Named(ident.clone())) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_macro_utils/src/symbol.rs
crates/bevy_macro_utils/src/symbol.rs
use core::fmt::{self, Display}; use syn::{Ident, Path}; /// A single named value, representable as a [string](str). #[derive(Copy, Clone)] pub struct Symbol(pub &'static str); impl PartialEq<Symbol> for Ident { fn eq(&self, word: &Symbol) -> bool { self == word.0 } } impl<'a> PartialEq<Symbol> for &'a Ident { fn eq(&self, word: &Symbol) -> bool { *self == word.0 } } impl PartialEq<Symbol> for Path { fn eq(&self, word: &Symbol) -> bool { self.is_ident(word.0) } } impl<'a> PartialEq<Symbol> for &'a Path { fn eq(&self, word: &Symbol) -> bool { self.is_ident(word.0) } } impl Display for Symbol { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(self.0) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/src/lib.rs
crates/bevy_ecs/compile_fail/src/lib.rs
// Nothing here, check out the integration tests
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui.rs
crates/bevy_ecs/compile_fail/tests/ui.rs
fn main() -> compile_fail_utils::ui_test::Result<()> { compile_fail_utils::test("ecs_ui", "tests/ui") }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/query_exact_sized_iterator_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/query_exact_sized_iterator_safety.rs
use bevy_ecs::prelude::*; #[derive(Component)] struct Foo; fn on_changed(query: Query<&Foo, Changed<Foo>>) { is_exact_size_iterator(query.iter()); //~^ E0277 } fn on_added(query: Query<&Foo, Added<Foo>>) { is_exact_size_iterator(query.iter()); //~^ E0277 } fn is_exact_size_iterator<T: ExactSizeIterator>(_iter: T) {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/system_query_iter_many_mut_lifetime_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/system_query_iter_many_mut_lifetime_safety.rs
use bevy_ecs::prelude::*; #[derive(Component)] struct A(usize); fn system(mut query: Query<&mut A>, e: Entity) { let mut results = Vec::new(); let mut iter = query.iter_many_mut([e, e]); //~v E0499 while let Some(a) = iter.fetch_next() { results.push(a); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/query_iter_many_mut_iterator_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/query_iter_many_mut_iterator_safety.rs
use bevy_ecs::prelude::*; #[derive(Component)] struct A(usize); fn system(mut query: Query<&mut A>, e: Entity) { let iter = query.iter_many_mut([e]); is_iterator(iter) //~^ E0277 } fn is_iterator<T: Iterator>(_iter: T) {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/deconstruct_moving_ptr.rs
crates/bevy_ecs/compile_fail/tests/ui/deconstruct_moving_ptr.rs
//@no-rustfix use bevy_ecs::ptr::{deconstruct_moving_ptr, MovingPtr}; pub struct A { x: usize, } #[repr(packed)] pub struct B { x: usize, } fn test1( a: MovingPtr<A>, box_a: MovingPtr<Box<A>>, mut_a: MovingPtr<&mut A>, box_t1: MovingPtr<Box<(usize,)>>, mut_t1: MovingPtr<&mut (usize,)>, box_t2: MovingPtr<Box<(usize, usize)>>, mut_t2: MovingPtr<&mut (usize, usize)>, ) { // Moving the same field twice would cause mutable aliased pointers //~v E0025 deconstruct_moving_ptr!({ let A { x, x } = a; }); // Field offsets would not be valid through autoderef //~vv E0308 //~v E0308 deconstruct_moving_ptr!({ let A { x } = box_a; }); //~v E0308 deconstruct_moving_ptr!({ let A { x } = mut_a; }); //~v E0308 deconstruct_moving_ptr!({ let tuple { 0: _ } = box_t1; }); //~v E0308 deconstruct_moving_ptr!({ let tuple { 0: _ } = mut_t1; }); //~v E0308 deconstruct_moving_ptr!({ let tuple { 0: _, 1: _ } = box_t2; }); //~v E0308 deconstruct_moving_ptr!({ let tuple { 0: _, 1: _ } = mut_t2; }); } fn test2(t: MovingPtr<(usize, usize)>) { // Moving the same field twice would cause mutable aliased pointers //~v E0499 deconstruct_moving_ptr!({ let tuple { 0: _, 0: _ } = t; }); } fn test3(b: MovingPtr<B>) { // A pointer to a member of a `repr(packed)` struct may not be aligned //~v E0793 deconstruct_moving_ptr!({ let B { x } = b; }); } fn test4(a: &mut MovingPtr<A>, t1: &mut MovingPtr<(usize,)>, t2: &mut MovingPtr<(usize, usize)>) { // Make sure it only takes `MovingPtr` by value and not by reference, // since the child `MovingPtr`s will drop part of the parent deconstruct_moving_ptr!({ //~v E0308 let A { x } = a; }); deconstruct_moving_ptr!({ //~v E0308 let tuple { 0: _ } = t1; }); deconstruct_moving_ptr!({ //~v E0308 let tuple { 0: _, 1: _ } = t2; }); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/entity_ref_mut_lifetime_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/entity_ref_mut_lifetime_safety.rs
use bevy_ecs::prelude::*; #[derive(Component, Eq, PartialEq, Debug)] struct A(Box<usize>); #[derive(Component)] struct B; fn main() { let mut world = World::default(); let e = world.spawn(A(Box::new(10_usize))).id(); let mut e_mut = world.entity_mut(e); { let gotten: &A = e_mut.get::<A>().unwrap(); let gotten2: A = e_mut.take::<A>().unwrap(); //~^ E0502 assert_eq!(gotten, &gotten2); // oops UB } e_mut.insert(A(Box::new(12_usize))); { let mut gotten: Mut<A> = e_mut.get_mut::<A>().unwrap(); let mut gotten2: A = e_mut.take::<A>().unwrap(); //~^ E0499 assert_eq!(&mut *gotten, &mut gotten2); // oops UB } e_mut.insert(A(Box::new(14_usize))); { let gotten: &A = e_mut.get::<A>().unwrap(); e_mut.despawn(); //~^ E0505 assert_eq!(gotten, &A(Box::new(14_usize))); // oops UB } let e = world.spawn(A(Box::new(16_usize))).id(); let mut e_mut = world.entity_mut(e); { let gotten: &A = e_mut.get::<A>().unwrap(); let gotten_mut: Mut<A> = e_mut.get_mut::<A>().unwrap(); //~^ E0502 assert_eq!(gotten, &*gotten_mut); // oops UB } { let gotten_mut: Mut<A> = e_mut.get_mut::<A>().unwrap(); let gotten: &A = e_mut.get::<A>().unwrap(); //~^ E0502 assert_eq!(gotten, &*gotten_mut); // oops UB } { let gotten: &A = e_mut.get::<A>().unwrap(); e_mut.insert::<B>(B); //~^ E0502 assert_eq!(gotten, &A(Box::new(16_usize))); // oops UB e_mut.remove::<B>(); } { let mut gotten_mut: Mut<A> = e_mut.get_mut::<A>().unwrap(); e_mut.insert::<B>(B); //~^ E0499 assert_eq!(&mut *gotten_mut, &mut A(Box::new(16_usize))); // oops UB } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/component_hook_struct_path.rs
crates/bevy_ecs/compile_fail/tests/ui/component_hook_struct_path.rs
use bevy_ecs::prelude::*; // the proc macro allows general paths, which means normal structs are also passing the basic // parsing. This test makes sure that we don't accidentally allow structs as hooks through future // changes. // // Currently the error is thrown in the generated code and not while executing the proc macro // logic. #[derive(Component)] #[component( on_add = Bar, //~^ E0425 )] pub struct FooWrongPath;
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/query_lens_lifetime_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/query_lens_lifetime_safety.rs
use bevy_ecs::prelude::*; use bevy_ecs::system::{QueryLens, SystemState}; #[derive(Component, Eq, PartialEq, Debug)] struct Foo(u32); #[derive(Component, Eq, PartialEq, Debug)] struct Bar(u32); fn main() { let mut world = World::default(); let e = world.spawn((Foo(10_u32), Bar(10_u32))).id(); let mut system_state = SystemState::<(Query<&mut Foo>, Query<&mut Bar>)>::new(&mut world); { let (mut foo_query, mut bar_query) = system_state.get_mut(&mut world); dbg!("hi"); { let mut lens = foo_query.as_query_lens(); let mut data: Mut<Foo> = lens.query().get_inner(e).unwrap(); let mut data2: Mut<Foo> = lens.query().get_inner(e).unwrap(); //~^ E0499 assert_eq!(&mut *data, &mut *data2); // oops UB } { let mut join: QueryLens<(&mut Foo, &mut Bar)> = foo_query.join(&mut bar_query); let mut query = join.query(); let (_, mut data) = query.single_mut().unwrap(); let mut data2 = bar_query.single_mut().unwrap(); //~^ E0499 assert_eq!(&mut *data, &mut *data2); // oops UB } { let mut join: QueryLens<(&mut Foo, &mut Bar)> = foo_query.join_inner(bar_query.reborrow()); let mut query = join.query(); let (_, mut data) = query.single_mut().unwrap(); let mut data2 = bar_query.single_mut().unwrap(); //~^ E0499 assert_eq!(&mut *data, &mut *data2); // oops UB } dbg!("bye"); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/component_hook_call_signature_mismatch.rs
crates/bevy_ecs/compile_fail/tests/ui/component_hook_call_signature_mismatch.rs
use bevy_ecs::prelude::*; // this should fail since the function is required to have the signature // (DeferredWorld, HookContext) -> () #[derive(Component)] //~^ E0057 #[component( on_add = wrong_bazzing("foo"), )] pub struct FooWrongCall; fn wrong_bazzing(_path: &str) -> impl Fn(bevy_ecs::world::DeferredWorld) { |_world| {} }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/query_iter_combinations_mut_iterator_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/query_iter_combinations_mut_iterator_safety.rs
use bevy_ecs::prelude::*; #[derive(Component)] struct A(usize); fn system(mut query: Query<&mut A>) { let iter = query.iter_combinations_mut(); is_iterator(iter) //~^ E0277 } fn is_iterator<T: Iterator>(_iter: T) {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/system_state_iter_mut_overlap_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/system_state_iter_mut_overlap_safety.rs
use bevy_ecs::prelude::*; use bevy_ecs::system::SystemState; #[derive(Component, Eq, PartialEq, Debug, Clone, Copy)] struct A(usize); fn main() { let mut world = World::default(); world.spawn(A(1)); world.spawn(A(2)); let mut system_state = SystemState::<Query<&mut A>>::new(&mut world); { let mut query = system_state.get_mut(&mut world); let mut_vec = query.iter_mut().collect::<Vec<bevy_ecs::prelude::Mut<A>>>(); assert_eq!( // this should fail to compile due to the later use of mut_vec query.iter().collect::<Vec<&A>>(), //~^ E0502 vec![&A(1), &A(2)], "both components returned by iter of &mut" ); assert_eq!( mut_vec.iter().map(|m| **m).collect::<Vec<A>>(), vec![A(1), A(2)], "both components returned by iter_mut of &mut" ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/system_query_set_get_lifetime_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/system_query_set_get_lifetime_safety.rs
use bevy_ecs::prelude::*; #[derive(Component)] struct A(usize); fn query_set(mut queries: ParamSet<(Query<&mut A>, Query<&A>)>, e: Entity) { let mut q2 = queries.p0(); let mut b = q2.get_mut(e).unwrap(); let q1 = queries.p1(); //~^ E0499 let a = q1.get(e).unwrap(); // this should fail to compile b.0 = a.0 } fn query_set_flip(mut queries: ParamSet<(Query<&mut A>, Query<&A>)>, e: Entity) { let q1 = queries.p1(); let a = q1.get(e).unwrap(); let mut q2 = queries.p0(); //~^ E0499 let mut b = q2.get_mut(e).unwrap(); // this should fail to compile b.0 = a.0 }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/system_state_iter_lifetime_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/system_state_iter_lifetime_safety.rs
use bevy_ecs::prelude::*; use bevy_ecs::system::SystemState; #[derive(Component)] struct A(usize); #[derive(Component)] struct B(usize); struct State { state_r: SystemState<Query<'static, 'static, &'static A>>, state_w: SystemState<Query<'static, 'static, &'static mut A>>, } impl State { fn get_components(&mut self, world: &mut World) { let q1 = self.state_r.get(&world); let a1 = q1.iter().next().unwrap(); let mut q2 = self.state_w.get_mut(world); //~^ E0502 let _ = q2.iter_mut().next().unwrap(); println!("{}", a1.0); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/resource_derive.rs
crates/bevy_ecs/compile_fail/tests/ui/resource_derive.rs
use bevy_ecs::prelude::*; #[derive(Resource)] //~v ERROR: Lifetimes must be 'static struct A<'a> { foo: &'a str, } #[derive(Resource)] struct B<'a: 'static> { foo: &'a str, }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/system_query_iter_lifetime_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/system_query_iter_lifetime_safety.rs
use bevy_ecs::prelude::*; #[derive(Component)] struct A(usize); fn system(mut query: Query<&mut A>) { let mut iter = query.iter_mut(); let a = &mut *iter.next().unwrap(); let mut iter2 = query.iter_mut(); //~^ E0499 let _ = &mut *iter2.next().unwrap(); println!("{}", a.0); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/system_param_derive_readonly.rs
crates/bevy_ecs/compile_fail/tests/ui/system_param_derive_readonly.rs
use bevy_ecs::prelude::*; use bevy_ecs::system::{ReadOnlySystemParam, SystemParam, SystemState}; #[derive(Component)] struct Foo; #[derive(SystemParam)] struct Mutable<'w, 's> { a: Query<'w, 's, &'static mut Foo>, } fn main() { let mut world = World::default(); let state = SystemState::<Mutable>::new(&mut world); state.get(&world); //~^ E0277 } fn assert_readonly<P>() where P: ReadOnlySystemParam, { }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/system_query_get_lifetime_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/system_query_get_lifetime_safety.rs
use bevy_ecs::prelude::*; #[derive(Component)] struct A(usize); fn system(mut query: Query<&mut A>, e: Entity) { let a1 = query.get_mut(e).unwrap(); let a2 = query.get_mut(e).unwrap(); //~^ E0499 println!("{} {}", a1.0, a2.0); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/world_query_derive.rs
crates/bevy_ecs/compile_fail/tests/ui/world_query_derive.rs
use bevy_ecs::prelude::*; use bevy_ecs::query::QueryData; #[derive(Component)] struct Foo; #[derive(QueryData)] struct MutableUnmarked { //~v E0277 a: &'static mut Foo, } #[derive(QueryData)] #[query_data(mut)] //~^ ERROR: invalid attribute, expected `mutable` or `derive` struct MutableInvalidAttribute { a: &'static mut Foo, } #[derive(QueryData)] #[query_data(mutable)] struct MutableMarked { a: &'static mut Foo, } #[derive(QueryData)] struct NestedMutableUnmarked { //~v E0277 a: MutableMarked, }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/system_query_set_iter_lifetime_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/system_query_set_iter_lifetime_safety.rs
use bevy_ecs::prelude::*; #[derive(Component)] struct A(usize); fn query_set(mut queries: ParamSet<(Query<&mut A>, Query<&A>)>) { let mut q2 = queries.p0(); let mut iter2 = q2.iter_mut(); let mut b = iter2.next().unwrap(); let q1 = queries.p1(); //~^ E0499 let mut iter = q1.iter(); let a = &*iter.next().unwrap(); b.0 = a.0 } fn query_set_flip(mut queries: ParamSet<(Query<&mut A>, Query<&A>)>) { let q1 = queries.p1(); let mut iter = q1.iter(); let a = &*iter.next().unwrap(); let mut q2 = queries.p0(); //~^ E0499 let mut iter2 = q2.iter_mut(); let mut b = iter2.next().unwrap(); b.0 = a.0; }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/component_hook_relationship.rs
crates/bevy_ecs/compile_fail/tests/ui/component_hook_relationship.rs
use bevy_ecs::prelude::*; mod case1 { use super::*; #[derive(Component, Debug)] #[component(on_insert = foo_hook)] //~^ ERROR: Custom on_insert hooks are not supported as relationships already define an on_insert hook #[relationship(relationship_target = FooTargets)] pub struct FooTargetOfFail(Entity); #[derive(Component, Debug)] #[relationship_target(relationship = FooTargetOfFail)] //~^ E0277 pub struct FooTargets(Vec<Entity>); } mod case2 { use super::*; #[derive(Component, Debug)] #[component(on_replace = foo_hook)] //~^ ERROR: Custom on_replace hooks are not supported as RelationshipTarget already defines an on_replace hook #[relationship_target(relationship = FooTargetOf)] pub struct FooTargetsFail(Vec<Entity>); #[derive(Component, Debug)] #[relationship(relationship_target = FooTargetsFail)] //~^ E0277 pub struct FooTargetOf(Entity); } mod case3 { use super::*; #[derive(Component, Debug)] #[component(on_replace = foo_hook)] //~^ ERROR: Custom on_replace hooks are not supported as Relationships already define an on_replace hook #[relationship(relationship_target = BarTargets)] pub struct BarTargetOfFail(Entity); #[derive(Component, Debug)] #[relationship_target(relationship = BarTargetOfFail)] //~^ E0277 pub struct BarTargets(Vec<Entity>); } mod case4 { use super::*; #[derive(Component, Debug)] #[component(on_despawn = foo_hook)] //~^ ERROR: Custom on_despawn hooks are not supported as this RelationshipTarget already defines an on_despawn hook, via the 'linked_spawn' attribute #[relationship_target(relationship = BarTargetOf, linked_spawn)] pub struct BarTargetsFail(Vec<Entity>); #[derive(Component, Debug)] #[relationship(relationship_target = BarTargetsFail)] //~^ E0277 pub struct BarTargetOf(Entity); } fn foo_hook(_world: bevy_ecs::world::DeferredWorld, _ctx: bevy_ecs::lifecycle::HookContext) {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/system_query_get_many_lifetime_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/system_query_get_many_lifetime_safety.rs
use bevy_ecs::prelude::*; #[derive(Component)] struct A(usize); fn system(mut query: Query<&mut A>, e: Entity) { let a1 = query.get_many([e, e]).unwrap(); let a2 = query.get_mut(e).unwrap(); //~^ E0502 println!("{} {}", a1[0].0, a2.0); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/system_query_iter_sort_lifetime_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/system_query_iter_sort_lifetime_safety.rs
use bevy_ecs::prelude::*; use std::cmp::Ordering; #[derive(Component)] struct A(usize); fn system(mut query: Query<&mut A>) { let iter = query.iter_mut(); let mut stored: Option<&A> = None; let mut sorted = iter.sort_by::<&A>(|left, _right| { // Try to smuggle the lens item out of the closure. stored = Some(left); //~^ E0521 Ordering::Equal }); let r: &A = stored.unwrap(); let m: &mut A = &mut sorted.next().unwrap(); assert!(std::ptr::eq(r, m)); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/query_transmute_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/query_transmute_safety.rs
use bevy_ecs::prelude::*; use bevy_ecs::system::SystemState; #[derive(Component, Eq, PartialEq, Debug)] struct Foo(u32); #[derive(Component)] struct Bar; fn main() { let mut world = World::default(); world.spawn(Foo(10)); let mut system_state = SystemState::<Query<(&mut Foo, &Bar)>>::new(&mut world); let mut query = system_state.get_mut(&mut world); { let mut lens_a = query.transmute_lens::<&mut Foo>(); let mut lens_b = query.transmute_lens::<&mut Foo>(); //~^ E0499 let mut query_a = lens_a.query(); let mut query_b = lens_b.query(); let a = query_a.single_mut().unwrap(); let b = query_b.single_mut().unwrap(); // oops 2 mutable references to same Foo assert_eq!(*a, *b); } { let mut lens = query.transmute_lens::<&mut Foo>(); let mut query_a = lens.query(); let mut query_b = lens.query(); //~^ E0499 let a = query_a.single_mut().unwrap(); let b = query_b.single_mut().unwrap(); // oops 2 mutable references to same Foo assert_eq!(*a, *b); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/query_to_readonly.rs
crates/bevy_ecs/compile_fail/tests/ui/query_to_readonly.rs
use bevy_ecs::prelude::*; #[derive(Component, Debug)] struct Foo; fn for_loops(mut query: Query<&mut Foo>) { // this should fail to compile for _ in query.iter_mut() { for _ in query.as_readonly().iter() {} //~^ E0502 } // this should fail to compile for _ in query.as_readonly().iter() { for _ in query.iter_mut() {} //~^ E0502 } // this should *not* fail to compile for _ in query.as_readonly().iter() { for _ in query.as_readonly().iter() {} } // this should *not* fail to compile for _ in query.as_readonly().iter() { for _ in query.iter() {} } // this should *not* fail to compile for _ in query.iter() { for _ in query.as_readonly().iter() {} } } fn single_mut_query(mut query: Query<&mut Foo>) { // this should fail to compile { let mut mut_foo = query.single_mut().unwrap(); // This solves "temporary value dropped while borrowed" let readonly_query = query.as_readonly(); //~^ E0502 let ref_foo = readonly_query.single().unwrap(); *mut_foo = Foo; println!("{ref_foo:?}"); } // this should fail to compile { // This solves "temporary value dropped while borrowed" let readonly_query = query.as_readonly(); let ref_foo = readonly_query.single(); let mut mut_foo = query.single_mut().unwrap(); //~^ E0502 println!("{ref_foo:?}"); *mut_foo = Foo; } // this should *not* fail to compile { // This solves "temporary value dropped while borrowed" let readonly_query = query.as_readonly(); let readonly_foo = readonly_query.single(); let query_foo = query.single(); println!("{readonly_foo:?}, {query_foo:?}"); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/system_state_get_lifetime_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/system_state_get_lifetime_safety.rs
use bevy_ecs::prelude::*; use bevy_ecs::system::SystemState; #[derive(Component)] struct A(usize); #[derive(Component)] struct B(usize); struct State { state_r: SystemState<Query<'static, 'static, &'static A>>, state_w: SystemState<Query<'static, 'static, &'static mut A>>, } impl State { fn get_component(&mut self, world: &mut World, entity: Entity) { let q1 = self.state_r.get(&world); let a1 = q1.get(entity).unwrap(); let mut q2 = self.state_w.get_mut(world); //~^ E0502 let _ = q2.get_mut(entity).unwrap(); println!("{}", a1.0); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/query_lifetime_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/query_lifetime_safety.rs
use bevy_ecs::prelude::*; use bevy_ecs::system::SystemState; #[derive(Component, Eq, PartialEq, Debug)] struct Foo(u32); fn main() { let mut world = World::default(); let e = world.spawn(Foo(10_u32)).id(); let mut system_state = SystemState::<Query<&mut Foo>>::new(&mut world); { let mut query = system_state.get_mut(&mut world); dbg!("hi"); { let data: &Foo = query.get(e).unwrap(); let mut data2: Mut<Foo> = query.get_mut(e).unwrap(); //~^ E0502 assert_eq!(data, &mut *data2); // oops UB } { let mut data2: Mut<Foo> = query.get_mut(e).unwrap(); let data: &Foo = query.get(e).unwrap(); //~^ E0502 assert_eq!(data, &mut *data2); // oops UB } { let data: &Foo = query.single().unwrap(); let mut data2: Mut<Foo> = query.single_mut().unwrap(); //~^ E0502 assert_eq!(data, &mut *data2); // oops UB } { let mut data2: Mut<Foo> = query.single_mut().unwrap(); let data: &Foo = query.single().unwrap(); //~^ E0502 assert_eq!(data, &mut *data2); // oops UB } { let data: &Foo = query.single().unwrap(); let mut data2: Mut<Foo> = query.single_mut().unwrap(); //~^ E0502 assert_eq!(data, &mut *data2); // oops UB } { let mut data2: Mut<Foo> = query.single_mut().unwrap(); let data: &Foo = query.single().unwrap(); //~^ E0502 assert_eq!(data, &mut *data2); // oops UB } { let data: &Foo = query.iter().next().unwrap(); let mut data2: Mut<Foo> = query.iter_mut().next().unwrap(); //~^ E0502 assert_eq!(data, &mut *data2); // oops UB } { let mut data2: Mut<Foo> = query.iter_mut().next().unwrap(); let data: &Foo = query.iter().next().unwrap(); //~^ E0502 assert_eq!(data, &mut *data2); // oops UB } { let mut opt_data: Option<&Foo> = None; let mut opt_data_2: Option<Mut<Foo>> = None; query.iter().for_each(|data| opt_data = Some(data)); query.iter_mut().for_each(|data| opt_data_2 = Some(data)); //~^ E0502 assert_eq!(opt_data.unwrap(), &mut *opt_data_2.unwrap()); // oops UB } { let mut opt_data_2: Option<Mut<Foo>> = None; let mut opt_data: Option<&Foo> = None; query.iter_mut().for_each(|data| opt_data_2 = Some(data)); query.iter().for_each(|data| opt_data = Some(data)); //~^ E0502 assert_eq!(opt_data.unwrap(), &mut *opt_data_2.unwrap()); // oops UB } dbg!("bye"); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/bundle_on_drop_impl.rs
crates/bevy_ecs/compile_fail/tests/ui/bundle_on_drop_impl.rs
use bevy_ecs::prelude::*; #[derive(Component, Debug)] pub struct A(usize); // this should fail since destructuring T: Drop cannot be split. #[derive(Bundle, Debug)] //~^ E0509 pub struct DropBundle { component_a: A, } impl Drop for DropBundle { fn drop(&mut self) { // Just need the impl } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/compile_fail/tests/ui/system_query_get_many_mut_lifetime_safety.rs
crates/bevy_ecs/compile_fail/tests/ui/system_query_get_many_mut_lifetime_safety.rs
use bevy_ecs::prelude::*; #[derive(Component)] struct A(usize); fn system(mut query: Query<&mut A>, e: Entity) { let a1 = query.get_many_mut([e, e]).unwrap(); let a2 = query.get_mut(e).unwrap(); //~^ E0499 println!("{} {}", a1[0].0, a2.0); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/macros/src/event.rs
crates/bevy_ecs/macros/src/event.rs
use proc_macro::TokenStream; use quote::quote; use syn::{ parse_macro_input, parse_quote, spanned::Spanned, Data, DataStruct, DeriveInput, Fields, Index, Member, Path, Result, Token, Type, }; pub const EVENT: &str = "event"; pub const ENTITY_EVENT: &str = "entity_event"; pub const PROPAGATE: &str = "propagate"; pub const AUTO_PROPAGATE: &str = "auto_propagate"; pub const TRIGGER: &str = "trigger"; pub const EVENT_TARGET: &str = "event_target"; pub fn derive_event(input: TokenStream) -> TokenStream { let mut ast = parse_macro_input!(input as DeriveInput); let bevy_ecs_path: Path = crate::bevy_ecs_path(); ast.generics .make_where_clause() .predicates .push(parse_quote! { Self: Send + Sync + 'static }); let mut processed_attrs = Vec::new(); let mut trigger: Option<Type> = None; for attr in ast.attrs.iter().filter(|attr| attr.path().is_ident(EVENT)) { if let Err(e) = attr.parse_nested_meta(|meta| match meta.path.get_ident() { Some(ident) if processed_attrs.iter().any(|i| ident == i) => { Err(meta.error(format!("duplicate attribute: {ident}"))) } Some(ident) if ident == TRIGGER => { trigger = Some(meta.value()?.parse()?); processed_attrs.push(TRIGGER); Ok(()) } Some(ident) => Err(meta.error(format!("unsupported attribute: {ident}"))), None => Err(meta.error("expected identifier")), }) { return e.to_compile_error().into(); } } let trigger = if let Some(trigger) = trigger { quote! {#trigger} } else { quote! {#bevy_ecs_path::event::GlobalTrigger} }; let struct_name = &ast.ident; let (impl_generics, type_generics, where_clause) = &ast.generics.split_for_impl(); TokenStream::from(quote! { impl #impl_generics #bevy_ecs_path::event::Event for #struct_name #type_generics #where_clause { type Trigger<'a> = #trigger; } }) } pub fn derive_entity_event(input: TokenStream) -> TokenStream { let mut ast = parse_macro_input!(input as DeriveInput); ast.generics .make_where_clause() .predicates .push(parse_quote! { Self: Send + Sync + 'static }); let mut auto_propagate = false; let mut propagate = false; let mut traversal: Option<Type> = None; let mut trigger: Option<Type> = None; let bevy_ecs_path: Path = crate::bevy_ecs_path(); let mut processed_attrs = Vec::new(); for attr in ast .attrs .iter() .filter(|attr| attr.path().is_ident(ENTITY_EVENT)) { if let Err(e) = attr.parse_nested_meta(|meta| match meta.path.get_ident() { Some(ident) if processed_attrs.iter().any(|i| ident == i) => { Err(meta.error(format!("duplicate attribute: {ident}"))) } Some(ident) if ident == AUTO_PROPAGATE => { propagate = true; auto_propagate = true; processed_attrs.push(AUTO_PROPAGATE); Ok(()) } Some(ident) if ident == PROPAGATE => { propagate = true; if meta.input.peek(Token![=]) { traversal = Some(meta.value()?.parse()?); } processed_attrs.push(PROPAGATE); Ok(()) } Some(ident) if ident == TRIGGER => { trigger = Some(meta.value()?.parse()?); processed_attrs.push(TRIGGER); Ok(()) } Some(ident) => Err(meta.error(format!("unsupported attribute: {ident}"))), None => Err(meta.error("expected identifier")), }) { return e.to_compile_error().into(); } } if trigger.is_some() && propagate { return syn::Error::new( ast.span(), "Cannot define both #[entity_event(trigger)] and #[entity_event(propagate)]", ) .into_compile_error() .into(); } let entity_field = match get_event_target_field(&ast) { Ok(value) => value, Err(err) => return err.into_compile_error().into(), }; let struct_name = &ast.ident; let (impl_generics, type_generics, where_clause) = &ast.generics.split_for_impl(); let trigger = if let Some(trigger) = trigger { quote! {#trigger} } else if propagate { let traversal = traversal .unwrap_or_else(|| parse_quote! { &'static #bevy_ecs_path::hierarchy::ChildOf}); quote! {#bevy_ecs_path::event::PropagateEntityTrigger<#auto_propagate, Self, #traversal>} } else { quote! {#bevy_ecs_path::event::EntityTrigger} }; let set_entity_event_target_impl = if propagate { quote! { impl #impl_generics #bevy_ecs_path::event::SetEntityEventTarget for #struct_name #type_generics #where_clause { fn set_event_target(&mut self, entity: #bevy_ecs_path::entity::Entity) { self.#entity_field = Into::into(entity); } } } } else { quote! {} }; TokenStream::from(quote! { impl #impl_generics #bevy_ecs_path::event::Event for #struct_name #type_generics #where_clause { type Trigger<'a> = #trigger; } impl #impl_generics #bevy_ecs_path::event::EntityEvent for #struct_name #type_generics #where_clause { fn event_target(&self) -> #bevy_ecs_path::entity::Entity { #bevy_ecs_path::entity::ContainsEntity::entity(&self.#entity_field) } } #set_entity_event_target_impl }) } /// Returns the field with the `#[event_target]` attribute, the only field if unnamed, /// or the field with the name "entity". fn get_event_target_field(ast: &DeriveInput) -> Result<Member> { let Data::Struct(DataStruct { fields, .. }) = &ast.data else { return Err(syn::Error::new( ast.span(), "EntityEvent can only be derived for structs.", )); }; match fields { Fields::Named(fields) => fields.named.iter().find_map(|field| { if field.ident.as_ref().is_some_and(|i| i == "entity") || field .attrs .iter() .any(|attr| attr.path().is_ident(EVENT_TARGET)) { Some(Member::Named(field.ident.clone()?)) } else { None } }).ok_or(syn::Error::new( fields.span(), "EntityEvent derive expected a field name 'entity' or a field annotated with #[event_target]." )), Fields::Unnamed(fields) if fields.unnamed.len() == 1 => Ok(Member::Unnamed(Index::from(0))), Fields::Unnamed(fields) => fields.unnamed.iter().enumerate().find_map(|(index, field)| { if field .attrs .iter() .any(|attr| attr.path().is_ident(EVENT_TARGET)) { Some(Member::Unnamed(Index::from(index))) } else { None } }) .ok_or(syn::Error::new( fields.span(), "EntityEvent derive expected unnamed structs with one field or with a field annotated with #[event_target].", )), Fields::Unit => Err(syn::Error::new( fields.span(), "EntityEvent derive does not work on unit structs. Your type must have a field to store the `Entity` target, such as `Attack(Entity)` or `Attack { entity: Entity }`.", )), } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/macros/src/lib.rs
crates/bevy_ecs/macros/src/lib.rs
//! Macros for deriving ECS traits. #![cfg_attr(docsrs, feature(doc_cfg))] extern crate proc_macro; mod component; mod event; mod message; mod query_data; mod query_filter; mod world_query; use crate::{ component::map_entities, query_data::derive_query_data_impl, query_filter::derive_query_filter_impl, }; use bevy_macro_utils::{derive_label, ensure_no_collision, get_struct_fields, BevyManifest}; use proc_macro::TokenStream; use proc_macro2::{Ident, Span}; use quote::{format_ident, quote, ToTokens}; use syn::{ parse_macro_input, parse_quote, punctuated::Punctuated, token::Comma, ConstParam, Data, DeriveInput, GenericParam, TypeParam, }; enum BundleFieldKind { Component, Ignore, } const BUNDLE_ATTRIBUTE_NAME: &str = "bundle"; const BUNDLE_ATTRIBUTE_IGNORE_NAME: &str = "ignore"; const BUNDLE_ATTRIBUTE_NO_FROM_COMPONENTS: &str = "ignore_from_components"; #[derive(Debug)] struct BundleAttributes { impl_from_components: bool, } impl Default for BundleAttributes { fn default() -> Self { Self { impl_from_components: true, } } } /// Implement the `Bundle` trait. #[proc_macro_derive(Bundle, attributes(bundle))] pub fn derive_bundle(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let ecs_path = bevy_ecs_path(); let mut attributes = BundleAttributes::default(); for attr in &ast.attrs { if attr.path().is_ident(BUNDLE_ATTRIBUTE_NAME) { let parsing = attr.parse_nested_meta(|meta| { if meta.path.is_ident(BUNDLE_ATTRIBUTE_NO_FROM_COMPONENTS) { attributes.impl_from_components = false; return Ok(()); } Err(meta.error(format!("Invalid bundle container attribute. Allowed attributes: `{BUNDLE_ATTRIBUTE_NO_FROM_COMPONENTS}`"))) }); if let Err(e) = parsing { return e.into_compile_error().into(); } } } let fields = match get_struct_fields(&ast.data, "derive(Bundle)") { Ok(fields) => fields, Err(e) => return e.into_compile_error().into(), }; let mut field_kinds = Vec::with_capacity(fields.len()); for field in fields { let mut kind = BundleFieldKind::Component; for attr in field .attrs .iter() .filter(|a| a.path().is_ident(BUNDLE_ATTRIBUTE_NAME)) { if let Err(error) = attr.parse_nested_meta(|meta| { if meta.path.is_ident(BUNDLE_ATTRIBUTE_IGNORE_NAME) { kind = BundleFieldKind::Ignore; Ok(()) } else { Err(meta.error(format!( "Invalid bundle attribute. Use `{BUNDLE_ATTRIBUTE_IGNORE_NAME}`" ))) } }) { return error.into_compile_error().into(); } } field_kinds.push(kind); } let field_types = fields.iter().map(|field| &field.ty).collect::<Vec<_>>(); let mut active_field_types = Vec::new(); let mut active_field_members = Vec::new(); let mut active_field_locals = Vec::new(); let mut inactive_field_members = Vec::new(); for ((field_member, field_type), field_kind) in fields.members().zip(field_types).zip(field_kinds) { let field_local = format_ident!("field_{}", field_member); match field_kind { BundleFieldKind::Component => { active_field_types.push(field_type); active_field_locals.push(field_local); active_field_members.push(field_member); } BundleFieldKind::Ignore => inactive_field_members.push(field_member), } } let generics = ast.generics; let generics_ty_list = generics.type_params().map(|p| p.ident.clone()); let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let struct_name = &ast.ident; let bundle_impl = quote! { // SAFETY: // - ComponentId is returned in field-definition-order. [get_components] uses field-definition-order // - `Bundle::get_components` is exactly once for each member. Rely's on the Component -> Bundle implementation to properly pass // the correct `StorageType` into the callback. unsafe impl #impl_generics #ecs_path::bundle::Bundle for #struct_name #ty_generics #where_clause { fn component_ids( components: &mut #ecs_path::component::ComponentsRegistrator, ) -> impl Iterator<Item = #ecs_path::component::ComponentId> + use<#(#generics_ty_list,)*> { core::iter::empty()#(.chain(<#active_field_types as #ecs_path::bundle::Bundle>::component_ids(components)))* } fn get_component_ids( components: &#ecs_path::component::Components, ) -> impl Iterator<Item = Option<#ecs_path::component::ComponentId>> { core::iter::empty()#(.chain(<#active_field_types as #ecs_path::bundle::Bundle>::get_component_ids(components)))* } } }; let dynamic_bundle_impl = quote! { impl #impl_generics #ecs_path::bundle::DynamicBundle for #struct_name #ty_generics #where_clause { type Effect = (); #[allow(unused_variables)] #[inline] unsafe fn get_components( ptr: #ecs_path::ptr::MovingPtr<'_, Self>, func: &mut impl FnMut(#ecs_path::component::StorageType, #ecs_path::ptr::OwningPtr<'_>) ) { use #ecs_path::__macro_exports::DebugCheckedUnwrap; #ecs_path::ptr::deconstruct_moving_ptr!({ let #struct_name { #(#active_field_members: #active_field_locals,)* #(#inactive_field_members: _,)* } = ptr; }); #( <#active_field_types as #ecs_path::bundle::DynamicBundle>::get_components( #active_field_locals, func ); )* } #[allow(unused_variables)] #[inline] unsafe fn apply_effect( ptr: #ecs_path::ptr::MovingPtr<'_, core::mem::MaybeUninit<Self>>, func: &mut #ecs_path::world::EntityWorldMut<'_>, ) { } } }; let from_components_impl = attributes.impl_from_components.then(|| quote! { // SAFETY: // - ComponentId is returned in field-definition-order. [from_components] uses field-definition-order unsafe impl #impl_generics #ecs_path::bundle::BundleFromComponents for #struct_name #ty_generics #where_clause { #[allow(unused_variables, non_snake_case)] unsafe fn from_components<__T, __F>(ctx: &mut __T, func: &mut __F) -> Self where __F: FnMut(&mut __T) -> #ecs_path::ptr::OwningPtr<'_> { Self { #(#active_field_members: <#active_field_types as #ecs_path::bundle::BundleFromComponents>::from_components(ctx, &mut *func),)* #(#inactive_field_members: ::core::default::Default::default(),)* } } } }); TokenStream::from(quote! { #bundle_impl #from_components_impl #dynamic_bundle_impl }) } /// Implement the `MapEntities` trait. #[proc_macro_derive(MapEntities, attributes(entities))] pub fn derive_map_entities(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let ecs_path = bevy_ecs_path(); let map_entities_impl = map_entities( &ast.data, &ecs_path, Ident::new("self", Span::call_site()), false, false, None, ); let struct_name = &ast.ident; let (impl_generics, type_generics, where_clause) = &ast.generics.split_for_impl(); TokenStream::from(quote! { impl #impl_generics #ecs_path::entity::MapEntities for #struct_name #type_generics #where_clause { fn map_entities<M: #ecs_path::entity::EntityMapper>(&mut self, mapper: &mut M) { #map_entities_impl } } }) } /// Implement `SystemParam` to use a struct as a parameter in a system #[proc_macro_derive(SystemParam, attributes(system_param))] pub fn derive_system_param(input: TokenStream) -> TokenStream { let token_stream = input.clone(); let ast = parse_macro_input!(input as DeriveInput); match derive_system_param_impl(token_stream, ast) { Ok(t) => t, Err(e) => e.into_compile_error().into(), } } fn derive_system_param_impl( token_stream: TokenStream, ast: DeriveInput, ) -> syn::Result<TokenStream> { let fields = get_struct_fields(&ast.data, "derive(SystemParam)")?; let path = bevy_ecs_path(); let field_locals = fields .members() .map(|m| format_ident!("field{}", m)) .collect::<Vec<_>>(); let field_members = fields.members().collect::<Vec<_>>(); let field_types = fields.iter().map(|f| &f.ty).collect::<Vec<_>>(); let field_validation_names = fields.members().map(|m| format!("::{}", quote! { #m })); let mut field_validation_messages = Vec::with_capacity(fields.len()); for attr in fields .iter() .map(|f| f.attrs.iter().find(|a| a.path().is_ident("system_param"))) { let mut field_validation_message = None; if let Some(attr) = attr { attr.parse_nested_meta(|nested| { if nested.path.is_ident("validation_message") { field_validation_message = Some(nested.value()?.parse()?); Ok(()) } else { Err(nested.error("Unsupported attribute")) } })?; } field_validation_messages .push(field_validation_message.unwrap_or_else(|| quote! { err.message })); } let generics = ast.generics; // Emit an error if there's any unrecognized lifetime names. let w = format_ident!("w"); let s = format_ident!("s"); for lt in generics.lifetimes() { let ident = &lt.lifetime.ident; if ident != &w && ident != &s { return Err(syn::Error::new_spanned( lt, r#"invalid lifetime name: expected `'w` or `'s` 'w -- refers to data stored in the World. 's -- refers to data stored in the SystemParam's state.'"#, )); } } let (_impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let lifetimeless_generics: Vec<_> = generics .params .iter() .filter(|g| !matches!(g, GenericParam::Lifetime(_))) .collect(); let shadowed_lifetimes: Vec<_> = generics.lifetimes().map(|_| quote!('_)).collect(); let mut punctuated_generics = Punctuated::<_, Comma>::new(); punctuated_generics.extend(lifetimeless_generics.iter().map(|g| match g { GenericParam::Type(g) => GenericParam::Type(TypeParam { default: None, ..g.clone() }), GenericParam::Const(g) => GenericParam::Const(ConstParam { default: None, ..g.clone() }), _ => unreachable!(), })); let mut punctuated_generic_idents = Punctuated::<_, Comma>::new(); punctuated_generic_idents.extend(lifetimeless_generics.iter().map(|g| match g { GenericParam::Type(g) => &g.ident, GenericParam::Const(g) => &g.ident, _ => unreachable!(), })); let punctuated_generics_no_bounds: Punctuated<_, Comma> = lifetimeless_generics .iter() .map(|&g| match g.clone() { GenericParam::Type(mut g) => { g.bounds.clear(); GenericParam::Type(g) } g => g, }) .collect(); let mut tuple_types: Vec<_> = field_types.iter().map(ToTokens::to_token_stream).collect(); let mut tuple_patterns: Vec<_> = field_locals.iter().map(ToTokens::to_token_stream).collect(); // If the number of fields exceeds the 16-parameter limit, // fold the fields into tuples of tuples until we are below the limit. const LIMIT: usize = 16; while tuple_types.len() > LIMIT { let end = Vec::from_iter(tuple_types.drain(..LIMIT)); tuple_types.push(parse_quote!( (#(#end,)*) )); let end = Vec::from_iter(tuple_patterns.drain(..LIMIT)); tuple_patterns.push(parse_quote!( (#(#end,)*) )); } // Create a where clause for the `ReadOnlySystemParam` impl. // Ensure that each field implements `ReadOnlySystemParam`. let mut read_only_generics = generics.clone(); let read_only_where_clause = read_only_generics.make_where_clause(); for field_type in &field_types { read_only_where_clause .predicates .push(syn::parse_quote!(#field_type: #path::system::ReadOnlySystemParam)); } let fields_alias = ensure_no_collision(format_ident!("__StructFieldsAlias"), token_stream.clone()); let struct_name = &ast.ident; let state_struct_visibility = &ast.vis; let state_struct_name = ensure_no_collision(format_ident!("FetchState"), token_stream); let mut builder_name = None; for meta in ast .attrs .iter() .filter(|a| a.path().is_ident("system_param")) { meta.parse_nested_meta(|nested| { if nested.path.is_ident("builder") { builder_name = Some(format_ident!("{struct_name}Builder")); Ok(()) } else { Err(nested.error("Unsupported attribute")) } })?; } let builder = builder_name.map(|builder_name| { let builder_type_parameters: Vec<Ident> = field_members.iter().map(|m| format_ident!("B{}", m)).collect(); let builder_doc_comment = format!("A [`SystemParamBuilder`] for a [`{struct_name}`]."); let builder_struct = quote! { #[doc = #builder_doc_comment] struct #builder_name<#(#builder_type_parameters,)*> { #(#field_members: #builder_type_parameters,)* } }; let lifetimes: Vec<_> = generics.lifetimes().collect(); let generic_struct = quote!{ #struct_name <#(#lifetimes,)* #punctuated_generic_idents> }; let builder_impl = quote!{ // SAFETY: This delegates to the `SystemParamBuilder` for tuples. unsafe impl< #(#lifetimes,)* #(#builder_type_parameters: #path::system::SystemParamBuilder<#field_types>,)* #punctuated_generics > #path::system::SystemParamBuilder<#generic_struct> for #builder_name<#(#builder_type_parameters,)*> #where_clause { fn build(self, world: &mut #path::world::World) -> <#generic_struct as #path::system::SystemParam>::State { let #builder_name { #(#field_members: #field_locals,)* } = self; #state_struct_name { state: #path::system::SystemParamBuilder::build((#(#tuple_patterns,)*), world) } } } }; (builder_struct, builder_impl) }); let (builder_struct, builder_impl) = builder.unzip(); Ok(TokenStream::from(quote! { // We define the FetchState struct in an anonymous scope to avoid polluting the user namespace. // The struct can still be accessed via SystemParam::State, e.g. MessageReaderState can be accessed via // <MessageReader<'static, 'static, T> as SystemParam>::State const _: () = { // Allows rebinding the lifetimes of each field type. type #fields_alias <'w, 's, #punctuated_generics_no_bounds> = (#(#tuple_types,)*); #[doc(hidden)] #state_struct_visibility struct #state_struct_name <#(#lifetimeless_generics,)*> #where_clause { state: <#fields_alias::<'static, 'static, #punctuated_generic_idents> as #path::system::SystemParam>::State, } unsafe impl<#punctuated_generics> #path::system::SystemParam for #struct_name <#(#shadowed_lifetimes,)* #punctuated_generic_idents> #where_clause { type State = #state_struct_name<#punctuated_generic_idents>; type Item<'w, 's> = #struct_name #ty_generics; fn init_state(world: &mut #path::world::World) -> Self::State { #state_struct_name { state: <#fields_alias::<'_, '_, #punctuated_generic_idents> as #path::system::SystemParam>::init_state(world), } } fn init_access(state: &Self::State, system_meta: &mut #path::system::SystemMeta, component_access_set: &mut #path::query::FilteredAccessSet, world: &mut #path::world::World) { <#fields_alias::<'_, '_, #punctuated_generic_idents> as #path::system::SystemParam>::init_access(&state.state, system_meta, component_access_set, world); } fn apply(state: &mut Self::State, system_meta: &#path::system::SystemMeta, world: &mut #path::world::World) { <#fields_alias::<'_, '_, #punctuated_generic_idents> as #path::system::SystemParam>::apply(&mut state.state, system_meta, world); } fn queue(state: &mut Self::State, system_meta: &#path::system::SystemMeta, world: #path::world::DeferredWorld) { <#fields_alias::<'_, '_, #punctuated_generic_idents> as #path::system::SystemParam>::queue(&mut state.state, system_meta, world); } #[inline] unsafe fn validate_param<'w, 's>( state: &'s mut Self::State, _system_meta: &#path::system::SystemMeta, _world: #path::world::unsafe_world_cell::UnsafeWorldCell<'w>, ) -> Result<(), #path::system::SystemParamValidationError> { let #state_struct_name { state: (#(#tuple_patterns,)*) } = state; #( <#field_types as #path::system::SystemParam>::validate_param(#field_locals, _system_meta, _world) .map_err(|err| #path::system::SystemParamValidationError::new::<Self>(err.skipped, #field_validation_messages, #field_validation_names))?; )* Result::Ok(()) } #[inline] unsafe fn get_param<'w, 's>( state: &'s mut Self::State, system_meta: &#path::system::SystemMeta, world: #path::world::unsafe_world_cell::UnsafeWorldCell<'w>, change_tick: #path::change_detection::Tick, ) -> Self::Item<'w, 's> { let (#(#tuple_patterns,)*) = < (#(#tuple_types,)*) as #path::system::SystemParam >::get_param(&mut state.state, system_meta, world, change_tick); #struct_name { #(#field_members: #field_locals,)* } } } // Safety: Each field is `ReadOnlySystemParam`, so this can only read from the `World` unsafe impl<'w, 's, #punctuated_generics> #path::system::ReadOnlySystemParam for #struct_name #ty_generics #read_only_where_clause {} #builder_impl }; #builder_struct })) } /// Implement `QueryData` to use a struct as a data parameter in a query #[proc_macro_derive(QueryData, attributes(query_data))] pub fn derive_query_data(input: TokenStream) -> TokenStream { derive_query_data_impl(input) } /// Implement `QueryFilter` to use a struct as a filter parameter in a query #[proc_macro_derive(QueryFilter, attributes(query_filter))] pub fn derive_query_filter(input: TokenStream) -> TokenStream { derive_query_filter_impl(input) } /// Derive macro generating an impl of the trait `ScheduleLabel`. /// /// This does not work for unions. #[proc_macro_derive(ScheduleLabel)] pub fn derive_schedule_label(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let mut trait_path = bevy_ecs_path(); trait_path.segments.push(format_ident!("schedule").into()); trait_path .segments .push(format_ident!("ScheduleLabel").into()); derive_label(input, "ScheduleLabel", &trait_path) } /// Derive macro generating an impl of the trait `SystemSet`. /// /// This does not work for unions. #[proc_macro_derive(SystemSet)] pub fn derive_system_set(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let mut trait_path = bevy_ecs_path(); trait_path.segments.push(format_ident!("schedule").into()); trait_path.segments.push(format_ident!("SystemSet").into()); derive_label(input, "SystemSet", &trait_path) } pub(crate) fn bevy_ecs_path() -> syn::Path { BevyManifest::shared(|manifest| manifest.get_path("bevy_ecs")) } /// Implement the `Event` trait. #[proc_macro_derive(Event, attributes(event))] pub fn derive_event(input: TokenStream) -> TokenStream { event::derive_event(input) } /// Cheat sheet for derive syntax, /// see full explanation on `EntityEvent` trait docs. /// /// ```ignore /// #[derive(EntityEvent)] /// /// Enable propagation, which defaults to using the ChildOf component /// #[entity_event(propagate)] /// /// Enable propagation using the given Traversal implementation /// #[entity_event(propagate = &'static ChildOf)] /// /// Always propagate /// #[entity_event(auto_propagate)] /// struct MyEvent; /// ``` #[proc_macro_derive(EntityEvent, attributes(entity_event, event_target))] pub fn derive_entity_event(input: TokenStream) -> TokenStream { event::derive_entity_event(input) } /// Implement the `Message` trait. #[proc_macro_derive(Message)] pub fn derive_message(input: TokenStream) -> TokenStream { message::derive_message(input) } /// Implement the `Resource` trait. #[proc_macro_derive(Resource)] pub fn derive_resource(input: TokenStream) -> TokenStream { component::derive_resource(input) } /// Cheat sheet for derive syntax, /// see full explanation and examples on the `Component` trait doc. /// /// ## Immutability /// ```ignore /// #[derive(Component)] /// #[component(immutable)] /// struct MyComponent; /// ``` /// /// ## Sparse instead of table-based storage /// ```ignore /// #[derive(Component)] /// #[component(storage = "SparseSet")] /// struct MyComponent; /// ``` /// /// ## Required Components /// /// ```ignore /// #[derive(Component)] /// #[require( /// // `Default::default()` /// A, /// // tuple structs /// B(1), /// // named-field structs /// C { /// x: 1, /// ..default() /// }, /// // unit structs/variants /// D::One, /// // associated consts /// E::ONE, /// // constructors /// F::new(1), /// // arbitrary expressions /// G = make(1, 2, 3) /// )] /// struct MyComponent; /// ``` /// /// ## Relationships /// ```ignore /// #[derive(Component)] /// #[relationship(relationship_target = Children)] /// pub struct ChildOf { /// // Marking the field is not necessary if there is only one. /// #[relationship] /// pub parent: Entity, /// internal: u8, /// }; /// /// #[derive(Component)] /// #[relationship_target(relationship = ChildOf)] /// pub struct Children(Vec<Entity>); /// ``` /// /// On despawn, also despawn all related entities: /// ```ignore /// #[derive(Component)] /// #[relationship_target(relationship_target = Children, linked_spawn)] /// pub struct Children(Vec<Entity>); /// ``` /// /// ## Hooks /// ```ignore /// #[derive(Component)] /// #[component(hook_name = function)] /// struct MyComponent; /// ``` /// where `hook_name` is `on_add`, `on_insert`, `on_replace` or `on_remove`; /// `function` can be either a path, e.g. `some_function::<Self>`, /// or a function call that returns a function that can be turned into /// a `ComponentHook`, e.g. `get_closure("Hi!")`. /// `function` can be elided if the path is `Self::on_add`, `Self::on_insert` etc. /// /// ## Ignore this component when cloning an entity /// ```ignore /// #[derive(Component)] /// #[component(clone_behavior = Ignore)] /// struct MyComponent; /// ``` #[proc_macro_derive( Component, attributes(component, require, relationship, relationship_target, entities) )] pub fn derive_component(input: TokenStream) -> TokenStream { component::derive_component(input) } /// Implement the `FromWorld` trait. #[proc_macro_derive(FromWorld, attributes(from_world))] pub fn derive_from_world(input: TokenStream) -> TokenStream { let bevy_ecs_path = bevy_ecs_path(); let ast = parse_macro_input!(input as DeriveInput); let name = ast.ident; let (impl_generics, ty_generics, where_clauses) = ast.generics.split_for_impl(); let (fields, variant_ident) = match &ast.data { Data::Struct(data) => (&data.fields, None), Data::Enum(data) => { match data.variants.iter().find(|variant| { variant .attrs .iter() .any(|attr| attr.path().is_ident("from_world")) }) { Some(variant) => (&variant.fields, Some(&variant.ident)), None => { return syn::Error::new( Span::call_site(), "No variant found with the `#[from_world]` attribute", ) .into_compile_error() .into(); } } } Data::Union(_) => { return syn::Error::new( Span::call_site(), "#[derive(FromWorld)]` does not support unions", ) .into_compile_error() .into(); } }; let field_init_expr = quote!(#bevy_ecs_path::world::FromWorld::from_world(world)); let members = fields.members(); let field_initializers = match variant_ident { Some(variant_ident) => quote!( Self::#variant_ident { #(#members: #field_init_expr),* }), None => quote!( Self { #(#members: #field_init_expr),* }), }; TokenStream::from(quote! { impl #impl_generics #bevy_ecs_path::world::FromWorld for #name #ty_generics #where_clauses { fn from_world(world: &mut #bevy_ecs_path::world::World) -> Self { #field_initializers } } }) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/macros/src/query_filter.rs
crates/bevy_ecs/macros/src/query_filter.rs
use bevy_macro_utils::{ensure_no_collision, get_struct_fields}; use proc_macro::TokenStream; use proc_macro2::{Ident, Span}; use quote::{format_ident, quote}; use syn::{parse_macro_input, parse_quote, DeriveInput}; use crate::{bevy_ecs_path, world_query::world_query_impl}; mod field_attr_keywords { syn::custom_keyword!(ignore); } pub fn derive_query_filter_impl(input: TokenStream) -> TokenStream { let tokens = input.clone(); let ast = parse_macro_input!(input as DeriveInput); let visibility = ast.vis; let path = bevy_ecs_path(); let user_generics = ast.generics.clone(); let (user_impl_generics, user_ty_generics, user_where_clauses) = user_generics.split_for_impl(); let user_generics_with_world = { let mut generics = ast.generics; generics.params.insert(0, parse_quote!('__w)); generics }; let (user_impl_generics_with_world, user_ty_generics_with_world, user_where_clauses_with_world) = user_generics_with_world.split_for_impl(); let struct_name = ast.ident; let fetch_struct_name = Ident::new(&format!("{struct_name}Fetch"), Span::call_site()); let fetch_struct_name = ensure_no_collision(fetch_struct_name, tokens.clone()); let marker_name = ensure_no_collision(format_ident!("_world_query_derive_marker"), tokens.clone()); // Generate a name for the state struct that doesn't conflict // with the struct definition. let state_struct_name = Ident::new(&format!("{struct_name}State"), Span::call_site()); let state_struct_name = ensure_no_collision(state_struct_name, tokens); let fields = match get_struct_fields(&ast.data, "derive(WorldQuery)") { Ok(fields) => fields, Err(e) => return e.into_compile_error().into(), }; let field_members: Vec<_> = fields.members().collect(); let field_aliases = fields .members() .map(|m| format_ident!("field{}", m)) .collect(); let field_types = fields.iter().map(|f| f.ty.clone()).collect(); let world_query_impl = world_query_impl( &path, &struct_name, &visibility, &fetch_struct_name, &field_types, &user_impl_generics, &user_impl_generics_with_world, &user_ty_generics, &user_ty_generics_with_world, &field_aliases, &marker_name, &state_struct_name, user_where_clauses, user_where_clauses_with_world, ); let filter_impl = quote! { // SAFETY: This only performs access that subqueries perform, and they impl `QueryFilter` and so perform no mutable access. unsafe impl #user_impl_generics #path::query::QueryFilter for #struct_name #user_ty_generics #user_where_clauses { const IS_ARCHETYPAL: bool = true #(&& <#field_types as #path::query::QueryFilter>::IS_ARCHETYPAL)*; #[allow(unused_variables)] #[inline(always)] unsafe fn filter_fetch<'__w>( _state: &Self::State, _fetch: &mut <Self as #path::query::WorldQuery>::Fetch<'__w>, _entity: #path::entity::Entity, _table_row: #path::storage::TableRow, ) -> bool { true #(&& <#field_types>::filter_fetch(&_state.#field_aliases, &mut _fetch.#field_aliases, _entity, _table_row))* } } }; let filter_asserts = quote! { #( assert_filter::<#field_types>(); )* }; TokenStream::from(quote! { const _: () = { #[doc(hidden)] #[doc = concat!( "Automatically generated internal [`WorldQuery`](", stringify!(#path), "::query::WorldQuery) state type for [`", stringify!(#struct_name), "`], used for caching." )] #[automatically_derived] #visibility struct #state_struct_name #user_impl_generics #user_where_clauses { #(#field_aliases: <#field_types as #path::query::WorldQuery>::State,)* } #world_query_impl #filter_impl }; #[allow(dead_code)] const _: () = { fn assert_filter<T>() where T: #path::query::QueryFilter, { } // We generate a filter assertion for every struct member. fn assert_all #user_impl_generics_with_world () #user_where_clauses_with_world { #filter_asserts } }; // The original struct will most likely be left unused. As we don't want our users having // to specify `#[allow(dead_code)]` for their custom queries, we are using this cursed // workaround. #[allow(dead_code)] const _: () = { fn dead_code_workaround #user_impl_generics ( q: #struct_name #user_ty_generics, q2: #struct_name #user_ty_generics ) #user_where_clauses { #(q.#field_members;)* #(q2.#field_members;)* } }; }) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/macros/src/message.rs
crates/bevy_ecs/macros/src/message.rs
use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, parse_quote, DeriveInput, Path}; pub fn derive_message(input: TokenStream) -> TokenStream { let mut ast = parse_macro_input!(input as DeriveInput); let bevy_ecs_path: Path = crate::bevy_ecs_path(); ast.generics .make_where_clause() .predicates .push(parse_quote! { Self: Send + Sync + 'static }); let struct_name = &ast.ident; let (impl_generics, type_generics, where_clause) = &ast.generics.split_for_impl(); TokenStream::from(quote! { impl #impl_generics #bevy_ecs_path::message::Message for #struct_name #type_generics #where_clause {} }) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/macros/src/world_query.rs
crates/bevy_ecs/macros/src/world_query.rs
use proc_macro2::Ident; use quote::quote; use syn::{Attribute, Fields, ImplGenerics, Member, Type, TypeGenerics, Visibility, WhereClause}; pub(crate) fn item_struct( path: &syn::Path, fields: &Fields, derive_macro_call: &proc_macro2::TokenStream, struct_name: &Ident, visibility: &Visibility, item_struct_name: &Ident, field_types: &Vec<Type>, user_impl_generics_with_world_and_state: &ImplGenerics, field_attrs: &Vec<Vec<Attribute>>, field_visibilities: &Vec<Visibility>, field_members: &Vec<Member>, user_ty_generics: &TypeGenerics, user_ty_generics_with_world_and_state: &TypeGenerics, user_where_clauses_with_world_and_state: Option<&WhereClause>, ) -> proc_macro2::TokenStream { let item_attrs = quote! { #[doc = concat!( "Automatically generated [`WorldQuery`](", stringify!(#path), "::query::WorldQuery) item type for [`", stringify!(#struct_name), "`], returned when iterating over query results." )] #[automatically_derived] }; match fields { Fields::Named(_) => quote! { #derive_macro_call #item_attrs #visibility struct #item_struct_name #user_impl_generics_with_world_and_state #user_where_clauses_with_world_and_state { #(#(#field_attrs)* #field_visibilities #field_members: <#field_types as #path::query::QueryData>::Item<'__w, '__s>,)* } }, Fields::Unnamed(_) => quote! { #derive_macro_call #item_attrs #visibility struct #item_struct_name #user_impl_generics_with_world_and_state #user_where_clauses_with_world_and_state( #( #field_visibilities <#field_types as #path::query::QueryData>::Item<'__w, '__s>, )* ); }, Fields::Unit => quote! { #item_attrs #visibility type #item_struct_name #user_ty_generics_with_world_and_state = #struct_name #user_ty_generics; }, } } pub(crate) fn world_query_impl( path: &syn::Path, struct_name: &Ident, visibility: &Visibility, fetch_struct_name: &Ident, field_types: &Vec<Type>, user_impl_generics: &ImplGenerics, user_impl_generics_with_world: &ImplGenerics, user_ty_generics: &TypeGenerics, user_ty_generics_with_world: &TypeGenerics, field_aliases: &Vec<Ident>, marker_name: &Ident, state_struct_name: &Ident, user_where_clauses: Option<&WhereClause>, user_where_clauses_with_world: Option<&WhereClause>, ) -> proc_macro2::TokenStream { quote! { #[doc(hidden)] #[doc = concat!( "Automatically generated internal [`WorldQuery`](", stringify!(#path), "::query::WorldQuery) fetch type for [`", stringify!(#struct_name), "`], used to define the world data accessed by this query." )] #[automatically_derived] #visibility struct #fetch_struct_name #user_impl_generics_with_world #user_where_clauses_with_world { #(#field_aliases: <#field_types as #path::query::WorldQuery>::Fetch<'__w>,)* #marker_name: &'__w(), } impl #user_impl_generics_with_world Clone for #fetch_struct_name #user_ty_generics_with_world #user_where_clauses_with_world { fn clone(&self) -> Self { Self { #(#field_aliases: self.#field_aliases.clone(),)* #marker_name: &(), } } } // SAFETY: `update_component_access` is called on every field unsafe impl #user_impl_generics #path::query::WorldQuery for #struct_name #user_ty_generics #user_where_clauses { type Fetch<'__w> = #fetch_struct_name #user_ty_generics_with_world; type State = #state_struct_name #user_ty_generics; fn shrink_fetch<'__wlong: '__wshort, '__wshort>( fetch: <#struct_name #user_ty_generics as #path::query::WorldQuery>::Fetch<'__wlong> ) -> <#struct_name #user_ty_generics as #path::query::WorldQuery>::Fetch<'__wshort> { #fetch_struct_name { #( #field_aliases: <#field_types>::shrink_fetch(fetch.#field_aliases), )* #marker_name: &(), } } unsafe fn init_fetch<'__w, '__s>( _world: #path::world::unsafe_world_cell::UnsafeWorldCell<'__w>, state: &'__s Self::State, _last_run: #path::change_detection::Tick, _this_run: #path::change_detection::Tick, ) -> <Self as #path::query::WorldQuery>::Fetch<'__w> { #fetch_struct_name { #(#field_aliases: <#field_types>::init_fetch( _world, &state.#field_aliases, _last_run, _this_run, ), )* #marker_name: &(), } } const IS_DENSE: bool = true #(&& <#field_types>::IS_DENSE)*; /// SAFETY: we call `set_archetype` for each member that implements `Fetch` #[inline] unsafe fn set_archetype<'__w, '__s>( _fetch: &mut <Self as #path::query::WorldQuery>::Fetch<'__w>, _state: &'__s Self::State, _archetype: &'__w #path::archetype::Archetype, _table: &'__w #path::storage::Table ) { #(<#field_types>::set_archetype(&mut _fetch.#field_aliases, &_state.#field_aliases, _archetype, _table);)* } /// SAFETY: we call `set_table` for each member that implements `Fetch` #[inline] unsafe fn set_table<'__w, '__s>( _fetch: &mut <Self as #path::query::WorldQuery>::Fetch<'__w>, _state: &'__s Self::State, _table: &'__w #path::storage::Table ) { #(<#field_types>::set_table(&mut _fetch.#field_aliases, &_state.#field_aliases, _table);)* } fn update_component_access(state: &Self::State, _access: &mut #path::query::FilteredAccess) { #( <#field_types>::update_component_access(&state.#field_aliases, _access); )* } fn init_state(world: &mut #path::world::World) -> #state_struct_name #user_ty_generics { #state_struct_name { #(#field_aliases: <#field_types>::init_state(world),)* } } fn get_state(components: &#path::component::Components) -> Option<#state_struct_name #user_ty_generics> { Some(#state_struct_name { #(#field_aliases: <#field_types>::get_state(components)?,)* }) } fn matches_component_set(state: &Self::State, _set_contains_id: &impl Fn(#path::component::ComponentId) -> bool) -> bool { true #(&& <#field_types>::matches_component_set(&state.#field_aliases, _set_contains_id))* } } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/macros/src/query_data.rs
crates/bevy_ecs/macros/src/query_data.rs
use bevy_macro_utils::{ensure_no_collision, get_struct_fields}; use proc_macro::TokenStream; use proc_macro2::{Ident, Span}; use quote::{format_ident, quote}; use syn::{ parse_macro_input, parse_quote, punctuated::Punctuated, token::Comma, DeriveInput, Meta, }; use crate::{ bevy_ecs_path, world_query::{item_struct, world_query_impl}, }; #[derive(Default)] struct QueryDataAttributes { pub is_mutable: bool, pub derive_args: Punctuated<Meta, Comma>, } static MUTABLE_ATTRIBUTE_NAME: &str = "mutable"; static DERIVE_ATTRIBUTE_NAME: &str = "derive"; mod field_attr_keywords { syn::custom_keyword!(ignore); } pub static QUERY_DATA_ATTRIBUTE_NAME: &str = "query_data"; pub fn derive_query_data_impl(input: TokenStream) -> TokenStream { let tokens = input.clone(); let ast = parse_macro_input!(input as DeriveInput); let visibility = ast.vis; let mut attributes = QueryDataAttributes::default(); for attr in &ast.attrs { if !attr.path().is_ident(QUERY_DATA_ATTRIBUTE_NAME) { continue; } let result = attr.parse_nested_meta(|meta| { if meta.path.is_ident(MUTABLE_ATTRIBUTE_NAME) { attributes.is_mutable = true; Ok(()) } else if meta.path.is_ident(DERIVE_ATTRIBUTE_NAME) { meta.parse_nested_meta(|meta| { attributes.derive_args.push(Meta::Path(meta.path)); Ok(()) }) } else { Err(meta.error(format_args!("invalid attribute, expected `{MUTABLE_ATTRIBUTE_NAME}` or `{DERIVE_ATTRIBUTE_NAME}`"))) } }); if let Err(err) = result { return err.to_compile_error().into(); } } let path = bevy_ecs_path(); let user_generics = ast.generics.clone(); let (user_impl_generics, user_ty_generics, user_where_clauses) = user_generics.split_for_impl(); let user_generics_with_world = { let mut generics = ast.generics.clone(); generics.params.insert(0, parse_quote!('__w)); generics }; let (user_impl_generics_with_world, user_ty_generics_with_world, user_where_clauses_with_world) = user_generics_with_world.split_for_impl(); let user_generics_with_world_and_state = { let mut generics = ast.generics; generics.params.insert(0, parse_quote!('__w)); generics.params.insert(1, parse_quote!('__s)); generics }; let ( user_impl_generics_with_world_and_state, user_ty_generics_with_world_and_state, user_where_clauses_with_world_and_state, ) = user_generics_with_world_and_state.split_for_impl(); let struct_name = ast.ident; let read_only_struct_name = if attributes.is_mutable { Ident::new(&format!("{struct_name}ReadOnly"), Span::call_site()) } else { struct_name.clone() }; let item_struct_name = Ident::new(&format!("{struct_name}Item"), Span::call_site()); let read_only_item_struct_name = if attributes.is_mutable { Ident::new(&format!("{struct_name}ReadOnlyItem"), Span::call_site()) } else { item_struct_name.clone() }; let fetch_struct_name = Ident::new(&format!("{struct_name}Fetch"), Span::call_site()); let fetch_struct_name = ensure_no_collision(fetch_struct_name, tokens.clone()); let read_only_fetch_struct_name = if attributes.is_mutable { let new_ident = Ident::new(&format!("{struct_name}ReadOnlyFetch"), Span::call_site()); ensure_no_collision(new_ident, tokens.clone()) } else { fetch_struct_name.clone() }; let marker_name = ensure_no_collision(format_ident!("_world_query_derive_marker"), tokens.clone()); // Generate a name for the state struct that doesn't conflict // with the struct definition. let state_struct_name = Ident::new(&format!("{struct_name}State"), Span::call_site()); let state_struct_name = ensure_no_collision(state_struct_name, tokens); let fields = match get_struct_fields(&ast.data, "derive(QueryData)") { Ok(fields) => fields, Err(e) => return e.into_compile_error().into(), }; let field_attrs = fields.iter().map(|f| f.attrs.clone()).collect(); let field_visibilities = fields.iter().map(|f| f.vis.clone()).collect(); let field_members = fields.members().collect(); let field_aliases = fields .members() .map(|m| format_ident!("field{}", m)) .collect(); let field_types: Vec<syn::Type> = fields.iter().map(|f| f.ty.clone()).collect(); let read_only_field_types = field_types .iter() .map(|ty| parse_quote!(<#ty as #path::query::QueryData>::ReadOnly)) .collect(); let derive_args = &attributes.derive_args; // `#[derive()]` is valid syntax let derive_macro_call = quote! { #[derive(#derive_args)] }; let mutable_item_struct = item_struct( &path, fields, &derive_macro_call, &struct_name, &visibility, &item_struct_name, &field_types, &user_impl_generics_with_world_and_state, &field_attrs, &field_visibilities, &field_members, &user_ty_generics, &user_ty_generics_with_world_and_state, user_where_clauses_with_world_and_state, ); let mutable_world_query_impl = world_query_impl( &path, &struct_name, &visibility, &fetch_struct_name, &field_types, &user_impl_generics, &user_impl_generics_with_world, &user_ty_generics, &user_ty_generics_with_world, &field_aliases, &marker_name, &state_struct_name, user_where_clauses, user_where_clauses_with_world, ); let (read_only_struct, read_only_impl) = if attributes.is_mutable { // If the query is mutable, we need to generate a separate readonly version of some things let readonly_item_struct = item_struct( &path, fields, &derive_macro_call, &read_only_struct_name, &visibility, &read_only_item_struct_name, &read_only_field_types, &user_impl_generics_with_world_and_state, &field_attrs, &field_visibilities, &field_members, &user_ty_generics, &user_ty_generics_with_world_and_state, user_where_clauses_with_world_and_state, ); let readonly_world_query_impl = world_query_impl( &path, &read_only_struct_name, &visibility, &read_only_fetch_struct_name, &read_only_field_types, &user_impl_generics, &user_impl_generics_with_world, &user_ty_generics, &user_ty_generics_with_world, &field_aliases, &marker_name, &state_struct_name, user_where_clauses, user_where_clauses_with_world, ); let read_only_structs = quote! { #[doc = concat!( "Automatically generated [`WorldQuery`](", stringify!(#path), "::query::WorldQuery) type for a read-only variant of [`", stringify!(#struct_name), "`]." )] #[automatically_derived] #visibility struct #read_only_struct_name #user_impl_generics #user_where_clauses { #( #[doc = "Automatically generated read-only field for accessing `"] #[doc = stringify!(#field_types)] #[doc = "`."] #field_visibilities #field_members: #read_only_field_types, )* } #readonly_item_struct }; (read_only_structs, readonly_world_query_impl) } else { (quote! {}, quote! {}) }; let data_impl = { let read_only_data_impl = if attributes.is_mutable { quote! { /// SAFETY: we assert fields are readonly below unsafe impl #user_impl_generics #path::query::QueryData for #read_only_struct_name #user_ty_generics #user_where_clauses { const IS_READ_ONLY: bool = true; const IS_ARCHETYPAL: bool = true #(&& <#read_only_field_types as #path::query::QueryData>::IS_ARCHETYPAL)*; type ReadOnly = #read_only_struct_name #user_ty_generics; type Item<'__w, '__s> = #read_only_item_struct_name #user_ty_generics_with_world_and_state; fn shrink<'__wlong: '__wshort, '__wshort, '__s>( item: Self::Item<'__wlong, '__s> ) -> Self::Item<'__wshort, '__s> { #read_only_item_struct_name { #( #field_members: <#read_only_field_types>::shrink(item.#field_members), )* } } fn provide_extra_access( state: &mut Self::State, access: &mut #path::query::Access, available_access: &#path::query::Access, ) { #(<#field_types>::provide_extra_access(&mut state.#field_aliases, access, available_access);)* } /// SAFETY: we call `fetch` for each member that implements `Fetch`. #[inline(always)] unsafe fn fetch<'__w, '__s>( _state: &'__s Self::State, _fetch: &mut <Self as #path::query::WorldQuery>::Fetch<'__w>, _entity: #path::entity::Entity, _table_row: #path::storage::TableRow, ) -> Option<Self::Item<'__w, '__s>> { Some(Self::Item { #(#field_members: <#read_only_field_types>::fetch(&_state.#field_aliases, &mut _fetch.#field_aliases, _entity, _table_row)?,)* }) } fn iter_access( _state: &Self::State, ) -> impl core::iter::Iterator<Item = #path::query::EcsAccessType<'_>> { core::iter::empty() #(.chain(<#field_types>::iter_access(&_state.#field_aliases)))* } } impl #user_impl_generics #path::query::ReleaseStateQueryData for #read_only_struct_name #user_ty_generics #user_where_clauses // Make these HRTBs with an unused lifetime parameter to allow trivial constraints // See https://github.com/rust-lang/rust/issues/48214 where #(for<'__a> #field_types: #path::query::QueryData<ReadOnly: #path::query::ReleaseStateQueryData>,)* { fn release_state<'__w>(_item: Self::Item<'__w, '_>) -> Self::Item<'__w, 'static> { Self::Item { #(#field_members: <#read_only_field_types>::release_state(_item.#field_members),)* } } } impl #user_impl_generics #path::query::ArchetypeQueryData for #read_only_struct_name #user_ty_generics #user_where_clauses // Make these HRTBs with an unused lifetime parameter to allow trivial constraints // See https://github.com/rust-lang/rust/issues/48214 where #(for<'__a> #field_types: #path::query::ArchetypeQueryData,)* {} } } else { quote! {} }; let is_read_only = !attributes.is_mutable; quote! { /// SAFETY: we assert fields are readonly below unsafe impl #user_impl_generics #path::query::QueryData for #struct_name #user_ty_generics #user_where_clauses { const IS_READ_ONLY: bool = #is_read_only; const IS_ARCHETYPAL: bool = true #(&& <#field_types as #path::query::QueryData>::IS_ARCHETYPAL)*; type ReadOnly = #read_only_struct_name #user_ty_generics; type Item<'__w, '__s> = #item_struct_name #user_ty_generics_with_world_and_state; fn shrink<'__wlong: '__wshort, '__wshort, '__s>( item: Self::Item<'__wlong, '__s> ) -> Self::Item<'__wshort, '__s> { #item_struct_name { #( #field_members: <#field_types>::shrink(item.#field_members), )* } } fn provide_extra_access( state: &mut Self::State, access: &mut #path::query::Access, available_access: &#path::query::Access, ) { #(<#field_types>::provide_extra_access(&mut state.#field_aliases, access, available_access);)* } /// SAFETY: we call `fetch` for each member that implements `Fetch`. #[inline(always)] unsafe fn fetch<'__w, '__s>( _state: &'__s Self::State, _fetch: &mut <Self as #path::query::WorldQuery>::Fetch<'__w>, _entity: #path::entity::Entity, _table_row: #path::storage::TableRow, ) -> Option<Self::Item<'__w, '__s>> { Some(Self::Item { #(#field_members: <#field_types>::fetch(&_state.#field_aliases, &mut _fetch.#field_aliases, _entity, _table_row)?,)* }) } fn iter_access( _state: &Self::State, ) -> impl core::iter::Iterator<Item = #path::query::EcsAccessType<'_>> { core::iter::empty() #(.chain(<#field_types>::iter_access(&_state.#field_aliases)))* } } impl #user_impl_generics #path::query::ReleaseStateQueryData for #struct_name #user_ty_generics #user_where_clauses // Make these HRTBs with an unused lifetime parameter to allow trivial constraints // See https://github.com/rust-lang/rust/issues/48214 where #(for<'__a> #field_types: #path::query::ReleaseStateQueryData,)* { fn release_state<'__w>(_item: Self::Item<'__w, '_>) -> Self::Item<'__w, 'static> { Self::Item { #(#field_members: <#field_types>::release_state(_item.#field_members),)* } } } impl #user_impl_generics #path::query::ArchetypeQueryData for #struct_name #user_ty_generics #user_where_clauses // Make these HRTBs with an unused lifetime parameter to allow trivial constraints // See https://github.com/rust-lang/rust/issues/48214 where #(for<'__a> #field_types: #path::query::ArchetypeQueryData,)* {} #read_only_data_impl } }; let read_only_data_impl = quote! { /// SAFETY: we assert fields are readonly below unsafe impl #user_impl_generics #path::query::ReadOnlyQueryData for #read_only_struct_name #user_ty_generics #user_where_clauses {} }; let read_only_asserts = if attributes.is_mutable { quote! { // Double-check that the data fetched by `<_ as WorldQuery>::ReadOnly` is read-only. // This is technically unnecessary as `<_ as WorldQuery>::ReadOnly: ReadOnlyQueryData` // but to protect against future mistakes we assert the assoc type implements `ReadOnlyQueryData` anyway #( assert_readonly::<#read_only_field_types>(); )* } } else { quote! { // Statically checks that the safety guarantee of `ReadOnlyQueryData` for `$fetch_struct_name` actually holds true. // We need this to make sure that we don't compile `ReadOnlyQueryData` if our struct contains nested `QueryData` // members that don't implement it. I.e.: // ``` // #[derive(QueryData)] // pub struct Foo { a: &'static mut MyComponent } // ``` #( assert_readonly::<#field_types>(); )* } }; let data_asserts = quote! { #( assert_data::<#field_types>(); )* }; TokenStream::from(quote! { #mutable_item_struct #read_only_struct const _: () = { #[doc(hidden)] #[doc = concat!( "Automatically generated internal [`WorldQuery`](", stringify!(#path), "::query::WorldQuery) state type for [`", stringify!(#struct_name), "`], used for caching." )] #[automatically_derived] #visibility struct #state_struct_name #user_impl_generics #user_where_clauses { #(#field_aliases: <#field_types as #path::query::WorldQuery>::State,)* } #mutable_world_query_impl #read_only_impl #data_impl #read_only_data_impl }; #[allow(dead_code)] const _: () = { fn assert_readonly<T>() where T: #path::query::ReadOnlyQueryData, { } fn assert_data<T>() where T: #path::query::QueryData, { } // We generate a readonly assertion for every struct member. fn assert_all #user_impl_generics_with_world () #user_where_clauses_with_world { #read_only_asserts #data_asserts } }; // The original struct will most likely be left unused. As we don't want our users having // to specify `#[allow(dead_code)]` for their custom queries, we are using this cursed // workaround. #[allow(dead_code)] const _: () = { fn dead_code_workaround #user_impl_generics ( q: #struct_name #user_ty_generics, q2: #read_only_struct_name #user_ty_generics ) #user_where_clauses { #(q.#field_members;)* #(q2.#field_members;)* } }; }) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/macros/src/component.rs
crates/bevy_ecs/macros/src/component.rs
use proc_macro::TokenStream; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::{format_ident, quote, ToTokens}; use std::collections::HashSet; use syn::{ braced, parenthesized, parse::Parse, parse_macro_input, parse_quote, punctuated::Punctuated, spanned::Spanned, token::{Brace, Comma, Paren}, Data, DataEnum, DataStruct, DeriveInput, Expr, ExprCall, ExprPath, Field, Fields, Ident, LitStr, Member, Path, Result, Token, Type, Visibility, }; pub fn derive_resource(input: TokenStream) -> TokenStream { let mut ast = parse_macro_input!(input as DeriveInput); let bevy_ecs_path: Path = crate::bevy_ecs_path(); // We want to raise a compile time error when the generic lifetimes // are not bound to 'static lifetime let non_static_lifetime_error = ast .generics .lifetimes() .filter(|lifetime| !lifetime.bounds.iter().any(|bound| bound.ident == "static")) .map(|param| syn::Error::new(param.span(), "Lifetimes must be 'static")) .reduce(|mut err_acc, err| { err_acc.combine(err); err_acc }); if let Some(err) = non_static_lifetime_error { return err.into_compile_error().into(); } ast.generics .make_where_clause() .predicates .push(parse_quote! { Self: Send + Sync + 'static }); let struct_name = &ast.ident; let (impl_generics, type_generics, where_clause) = &ast.generics.split_for_impl(); TokenStream::from(quote! { impl #impl_generics #bevy_ecs_path::resource::Resource for #struct_name #type_generics #where_clause { } }) } /// Component derive syntax is documented on both the macro and the trait. pub fn derive_component(input: TokenStream) -> TokenStream { let mut ast = parse_macro_input!(input as DeriveInput); let bevy_ecs_path: Path = crate::bevy_ecs_path(); let attrs = match parse_component_attr(&ast) { Ok(attrs) => attrs, Err(e) => return e.into_compile_error().into(), }; let relationship = match derive_relationship(&ast, &attrs, &bevy_ecs_path) { Ok(value) => value, Err(err) => err.into_compile_error().into(), }; let relationship_target = match derive_relationship_target(&ast, &attrs, &bevy_ecs_path) { Ok(value) => value, Err(err) => err.into_compile_error().into(), }; let map_entities = map_entities( &ast.data, &bevy_ecs_path, Ident::new("this", Span::call_site()), relationship.is_some(), relationship_target.is_some(), attrs.map_entities ).map(|map_entities_impl| quote! { fn map_entities<M: #bevy_ecs_path::entity::EntityMapper>(this: &mut Self, mapper: &mut M) { use #bevy_ecs_path::entity::MapEntities; #map_entities_impl } }); let storage = storage_path(&bevy_ecs_path, attrs.storage); let on_add_path = attrs .on_add .map(|path| path.to_token_stream(&bevy_ecs_path)); let on_remove_path = attrs .on_remove .map(|path| path.to_token_stream(&bevy_ecs_path)); let on_insert_path = if relationship.is_some() { if attrs.on_insert.is_some() { return syn::Error::new( ast.span(), "Custom on_insert hooks are not supported as relationships already define an on_insert hook", ) .into_compile_error() .into(); } Some(quote!(<Self as #bevy_ecs_path::relationship::Relationship>::on_insert)) } else { attrs .on_insert .map(|path| path.to_token_stream(&bevy_ecs_path)) }; let on_replace_path = if relationship.is_some() { if attrs.on_replace.is_some() { return syn::Error::new( ast.span(), "Custom on_replace hooks are not supported as Relationships already define an on_replace hook", ) .into_compile_error() .into(); } Some(quote!(<Self as #bevy_ecs_path::relationship::Relationship>::on_replace)) } else if attrs.relationship_target.is_some() { if attrs.on_replace.is_some() { return syn::Error::new( ast.span(), "Custom on_replace hooks are not supported as RelationshipTarget already defines an on_replace hook", ) .into_compile_error() .into(); } Some(quote!(<Self as #bevy_ecs_path::relationship::RelationshipTarget>::on_replace)) } else { attrs .on_replace .map(|path| path.to_token_stream(&bevy_ecs_path)) }; let on_despawn_path = if attrs .relationship_target .is_some_and(|target| target.linked_spawn) { if attrs.on_despawn.is_some() { return syn::Error::new( ast.span(), "Custom on_despawn hooks are not supported as this RelationshipTarget already defines an on_despawn hook, via the 'linked_spawn' attribute", ) .into_compile_error() .into(); } Some(quote!(<Self as #bevy_ecs_path::relationship::RelationshipTarget>::on_despawn)) } else { attrs .on_despawn .map(|path| path.to_token_stream(&bevy_ecs_path)) }; let on_add = hook_register_function_call(&bevy_ecs_path, quote! {on_add}, on_add_path); let on_insert = hook_register_function_call(&bevy_ecs_path, quote! {on_insert}, on_insert_path); let on_replace = hook_register_function_call(&bevy_ecs_path, quote! {on_replace}, on_replace_path); let on_remove = hook_register_function_call(&bevy_ecs_path, quote! {on_remove}, on_remove_path); let on_despawn = hook_register_function_call(&bevy_ecs_path, quote! {on_despawn}, on_despawn_path); ast.generics .make_where_clause() .predicates .push(parse_quote! { Self: Send + Sync + 'static }); let requires = &attrs.requires; let mut register_required = Vec::with_capacity(attrs.requires.iter().len()); if let Some(requires) = requires { for require in requires { let ident = &require.path; let constructor = match &require.func { Some(func) => quote! { || { let x: #ident = (#func)().into(); x } }, None => quote! { <#ident as Default>::default }, }; register_required.push(quote! { required_components.register_required::<#ident>(#constructor); }); } } let struct_name = &ast.ident; let (impl_generics, type_generics, where_clause) = &ast.generics.split_for_impl(); let required_component_docs = attrs.requires.map(|r| { let paths = r .iter() .map(|r| format!("[`{}`]", r.path.to_token_stream())) .collect::<Vec<_>>() .join(", "); let doc = format!("**Required Components**: {paths}. \n\n A component's Required Components are inserted whenever it is inserted. Note that this will also insert the required components _of_ the required components, recursively, in depth-first order."); quote! { #[doc = #doc] } }); let mutable_type = (attrs.immutable || relationship.is_some()) .then_some(quote! { #bevy_ecs_path::component::Immutable }) .unwrap_or(quote! { #bevy_ecs_path::component::Mutable }); let clone_behavior = if relationship_target.is_some() || relationship.is_some() { quote!( use #bevy_ecs_path::relationship::{ RelationshipCloneBehaviorBase, RelationshipCloneBehaviorViaClone, RelationshipCloneBehaviorViaReflect, RelationshipTargetCloneBehaviorViaClone, RelationshipTargetCloneBehaviorViaReflect, RelationshipTargetCloneBehaviorHierarchy }; (&&&&&&&#bevy_ecs_path::relationship::RelationshipCloneBehaviorSpecialization::<Self>::default()).default_clone_behavior() ) } else if let Some(behavior) = attrs.clone_behavior { quote!(#bevy_ecs_path::component::ComponentCloneBehavior::#behavior) } else { quote!( use #bevy_ecs_path::component::{DefaultCloneBehaviorBase, DefaultCloneBehaviorViaClone}; (&&&#bevy_ecs_path::component::DefaultCloneBehaviorSpecialization::<Self>::default()).default_clone_behavior() ) }; let relationship_accessor = if (relationship.is_some() || relationship_target.is_some()) && let Data::Struct(DataStruct { fields, struct_token, .. }) = &ast.data && let Ok(field) = relationship_field(fields, "Relationship", struct_token.span()) { let relationship_member = field.ident.clone().map_or(Member::from(0), Member::Named); if relationship.is_some() { quote! { Some( // Safety: we pass valid offset of a field containing Entity (obtained via offset_off!) unsafe { #bevy_ecs_path::relationship::ComponentRelationshipAccessor::<Self>::relationship( core::mem::offset_of!(Self, #relationship_member) ) } ) } } else { quote! { Some(#bevy_ecs_path::relationship::ComponentRelationshipAccessor::<Self>::relationship_target()) } } } else { quote! {None} }; // This puts `register_required` before `register_recursive_requires` to ensure that the constructors of _all_ top // level components are initialized first, giving them precedence over recursively defined constructors for the same component type TokenStream::from(quote! { #required_component_docs impl #impl_generics #bevy_ecs_path::component::Component for #struct_name #type_generics #where_clause { const STORAGE_TYPE: #bevy_ecs_path::component::StorageType = #storage; type Mutability = #mutable_type; fn register_required_components( _requiree: #bevy_ecs_path::component::ComponentId, required_components: &mut #bevy_ecs_path::component::RequiredComponentsRegistrator, ) { #(#register_required)* } #on_add #on_insert #on_replace #on_remove #on_despawn fn clone_behavior() -> #bevy_ecs_path::component::ComponentCloneBehavior { #clone_behavior } #map_entities fn relationship_accessor() -> Option<#bevy_ecs_path::relationship::ComponentRelationshipAccessor<Self>> { #relationship_accessor } } #relationship #relationship_target }) } const ENTITIES: &str = "entities"; pub(crate) fn map_entities( data: &Data, bevy_ecs_path: &Path, self_ident: Ident, is_relationship: bool, is_relationship_target: bool, map_entities_attr: Option<MapEntitiesAttributeKind>, ) -> Option<TokenStream2> { if let Some(map_entities_override) = map_entities_attr { let map_entities_tokens = map_entities_override.to_token_stream(bevy_ecs_path); return Some(quote!( #map_entities_tokens(#self_ident, mapper) )); } match data { Data::Struct(DataStruct { fields, .. }) => { let mut map = Vec::with_capacity(fields.len()); let relationship = if is_relationship || is_relationship_target { relationship_field(fields, "MapEntities", fields.span()).ok() } else { None }; fields .iter() .enumerate() .filter(|(_, field)| { field.attrs.iter().any(|a| a.path().is_ident(ENTITIES)) || relationship.is_some_and(|relationship| relationship == *field) }) .for_each(|(index, field)| { let field_member = field .ident .clone() .map_or(Member::from(index), Member::Named); map.push(quote!(#self_ident.#field_member.map_entities(mapper);)); }); if map.is_empty() { return None; }; Some(quote!( #(#map)* )) } Data::Enum(DataEnum { variants, .. }) => { let mut map = Vec::with_capacity(variants.len()); for variant in variants.iter() { let field_members = variant .fields .iter() .enumerate() .filter(|(_, field)| field.attrs.iter().any(|a| a.path().is_ident(ENTITIES))) .map(|(index, field)| { field .ident .clone() .map_or(Member::from(index), Member::Named) }) .collect::<Vec<_>>(); let ident = &variant.ident; let field_idents = field_members .iter() .map(|member| format_ident!("__self{}", member)) .collect::<Vec<_>>(); map.push( quote!(Self::#ident {#(#field_members: #field_idents,)* ..} => { #(#field_idents.map_entities(mapper);)* }), ); } if map.is_empty() { return None; }; Some(quote!( match #self_ident { #(#map,)* _ => {} } )) } Data::Union(_) => None, } } pub const COMPONENT: &str = "component"; pub const STORAGE: &str = "storage"; pub const REQUIRE: &str = "require"; pub const RELATIONSHIP: &str = "relationship"; pub const RELATIONSHIP_TARGET: &str = "relationship_target"; pub const ON_ADD: &str = "on_add"; pub const ON_INSERT: &str = "on_insert"; pub const ON_REPLACE: &str = "on_replace"; pub const ON_REMOVE: &str = "on_remove"; pub const ON_DESPAWN: &str = "on_despawn"; pub const MAP_ENTITIES: &str = "map_entities"; pub const IMMUTABLE: &str = "immutable"; pub const CLONE_BEHAVIOR: &str = "clone_behavior"; /// All allowed attribute value expression kinds for component hooks. /// This doesn't simply use general expressions because of conflicting needs: /// - we want to be able to use `Self` & generic parameters in paths /// - call expressions producing a closure need to be wrapped in a function /// to turn them into function pointers, which prevents access to the outer generic params #[derive(Debug)] enum HookAttributeKind { /// expressions like function or struct names /// /// structs will throw compile errors on the code generation so this is safe Path(ExprPath), /// function call like expressions Call(ExprCall), } impl HookAttributeKind { fn parse( input: syn::parse::ParseStream, default_hook_path: impl FnOnce() -> ExprPath, ) -> Result<Self> { if input.peek(Token![=]) { input.parse::<Token![=]>()?; input.parse::<Expr>().and_then(Self::from_expr) } else { Ok(Self::Path(default_hook_path())) } } fn from_expr(value: Expr) -> Result<Self> { match value { Expr::Path(path) => Ok(HookAttributeKind::Path(path)), Expr::Call(call) => Ok(HookAttributeKind::Call(call)), // throw meaningful error on all other expressions _ => Err(syn::Error::new( value.span(), [ "Not supported in this position, please use one of the following:", "- path to function", "- call to function yielding closure", ] .join("\n"), )), } } fn to_token_stream(&self, bevy_ecs_path: &Path) -> TokenStream2 { match self { HookAttributeKind::Path(path) => path.to_token_stream(), HookAttributeKind::Call(call) => { quote!({ fn _internal_hook(world: #bevy_ecs_path::world::DeferredWorld, ctx: #bevy_ecs_path::lifecycle::HookContext) { (#call)(world, ctx) } _internal_hook }) } } } } #[derive(Debug)] pub(super) enum MapEntitiesAttributeKind { /// expressions like function or struct names /// /// structs will throw compile errors on the code generation so this is safe Path(ExprPath), /// When no value is specified Default, } impl MapEntitiesAttributeKind { fn from_expr(value: Expr) -> Result<Self> { match value { Expr::Path(path) => Ok(Self::Path(path)), // throw meaningful error on all other expressions _ => Err(syn::Error::new( value.span(), [ "Not supported in this position, please use one of the following:", "- path to function", "- nothing to default to MapEntities implementation", ] .join("\n"), )), } } fn to_token_stream(&self, bevy_ecs_path: &Path) -> TokenStream2 { match self { MapEntitiesAttributeKind::Path(path) => path.to_token_stream(), MapEntitiesAttributeKind::Default => { quote!( <Self as #bevy_ecs_path::entity::MapEntities>::map_entities ) } } } } impl Parse for MapEntitiesAttributeKind { fn parse(input: syn::parse::ParseStream) -> Result<Self> { if input.peek(Token![=]) { input.parse::<Token![=]>()?; input.parse::<Expr>().and_then(Self::from_expr) } else { Ok(Self::Default) } } } struct Attrs { storage: StorageTy, requires: Option<Punctuated<Require, Comma>>, on_add: Option<HookAttributeKind>, on_insert: Option<HookAttributeKind>, on_replace: Option<HookAttributeKind>, on_remove: Option<HookAttributeKind>, on_despawn: Option<HookAttributeKind>, relationship: Option<Relationship>, relationship_target: Option<RelationshipTarget>, immutable: bool, clone_behavior: Option<Expr>, map_entities: Option<MapEntitiesAttributeKind>, } #[derive(Clone, Copy)] enum StorageTy { Table, SparseSet, } struct Require { path: Path, func: Option<TokenStream2>, } struct Relationship { relationship_target: Type, } struct RelationshipTarget { relationship: Type, linked_spawn: bool, } // values for `storage` attribute const TABLE: &str = "Table"; const SPARSE_SET: &str = "SparseSet"; fn parse_component_attr(ast: &DeriveInput) -> Result<Attrs> { let mut attrs = Attrs { storage: StorageTy::Table, on_add: None, on_insert: None, on_replace: None, on_remove: None, on_despawn: None, requires: None, relationship: None, relationship_target: None, immutable: false, clone_behavior: None, map_entities: None, }; let mut require_paths = HashSet::new(); for attr in ast.attrs.iter() { if attr.path().is_ident(COMPONENT) { attr.parse_nested_meta(|nested| { if nested.path.is_ident(STORAGE) { attrs.storage = match nested.value()?.parse::<LitStr>()?.value() { s if s == TABLE => StorageTy::Table, s if s == SPARSE_SET => StorageTy::SparseSet, s => { return Err(nested.error(format!( "Invalid storage type `{s}`, expected '{TABLE}' or '{SPARSE_SET}'.", ))); } }; Ok(()) } else if nested.path.is_ident(ON_ADD) { attrs.on_add = Some(HookAttributeKind::parse(nested.input, || { parse_quote! { Self::on_add } })?); Ok(()) } else if nested.path.is_ident(ON_INSERT) { attrs.on_insert = Some(HookAttributeKind::parse(nested.input, || { parse_quote! { Self::on_insert } })?); Ok(()) } else if nested.path.is_ident(ON_REPLACE) { attrs.on_replace = Some(HookAttributeKind::parse(nested.input, || { parse_quote! { Self::on_replace } })?); Ok(()) } else if nested.path.is_ident(ON_REMOVE) { attrs.on_remove = Some(HookAttributeKind::parse(nested.input, || { parse_quote! { Self::on_remove } })?); Ok(()) } else if nested.path.is_ident(ON_DESPAWN) { attrs.on_despawn = Some(HookAttributeKind::parse(nested.input, || { parse_quote! { Self::on_despawn } })?); Ok(()) } else if nested.path.is_ident(IMMUTABLE) { attrs.immutable = true; Ok(()) } else if nested.path.is_ident(CLONE_BEHAVIOR) { attrs.clone_behavior = Some(nested.value()?.parse()?); Ok(()) } else if nested.path.is_ident(MAP_ENTITIES) { attrs.map_entities = Some(nested.input.parse::<MapEntitiesAttributeKind>()?); Ok(()) } else { Err(nested.error("Unsupported attribute")) } })?; } else if attr.path().is_ident(REQUIRE) { let punctuated = attr.parse_args_with(Punctuated::<Require, Comma>::parse_terminated)?; for require in punctuated.iter() { if !require_paths.insert(require.path.to_token_stream().to_string()) { return Err(syn::Error::new( require.path.span(), "Duplicate required components are not allowed.", )); } } if let Some(current) = &mut attrs.requires { current.extend(punctuated); } else { attrs.requires = Some(punctuated); } } else if attr.path().is_ident(RELATIONSHIP) { let relationship = attr.parse_args::<Relationship>()?; attrs.relationship = Some(relationship); } else if attr.path().is_ident(RELATIONSHIP_TARGET) { let relationship_target = attr.parse_args::<RelationshipTarget>()?; attrs.relationship_target = Some(relationship_target); } } if attrs.relationship_target.is_some() && attrs.clone_behavior.is_some() { return Err(syn::Error::new( attrs.clone_behavior.span(), "A Relationship Target already has its own clone behavior, please remove `clone_behavior = ...`", )); } Ok(attrs) } impl Parse for Require { fn parse(input: syn::parse::ParseStream) -> Result<Self> { let mut path = input.parse::<Path>()?; let mut last_segment_is_lower = false; let mut is_constructor_call = false; // Use the case of the type name to check if it's an enum // This doesn't match everything that can be an enum according to the rust spec // but it matches what clippy is OK with let is_enum = { let mut first_chars = path .segments .iter() .rev() .filter_map(|s| s.ident.to_string().chars().next()); if let Some(last) = first_chars.next() { if last.is_uppercase() { if let Some(last) = first_chars.next() { last.is_uppercase() } else { false } } else { last_segment_is_lower = true; false } } else { false } }; let func = if input.peek(Token![=]) { // If there is an '=', then this is a "function style" require input.parse::<Token![=]>()?; let expr: Expr = input.parse()?; Some(quote!(|| #expr )) } else if input.peek(Brace) { // This is a "value style" named-struct-like require let content; braced!(content in input); let content = content.parse::<TokenStream2>()?; Some(quote!(|| #path { #content })) } else if input.peek(Paren) { // This is a "value style" tuple-struct-like require let content; parenthesized!(content in input); let content = content.parse::<TokenStream2>()?; is_constructor_call = last_segment_is_lower; Some(quote!(|| #path (#content))) } else if is_enum { // if this is an enum, then it is an inline enum component declaration Some(quote!(|| #path)) } else { // if this isn't any of the above, then it is a component ident, which will use Default None }; if is_enum || is_constructor_call { path.segments.pop(); path.segments.pop_punct(); } Ok(Require { path, func }) } } fn storage_path(bevy_ecs_path: &Path, ty: StorageTy) -> TokenStream2 { let storage_type = match ty { StorageTy::Table => Ident::new("Table", Span::call_site()), StorageTy::SparseSet => Ident::new("SparseSet", Span::call_site()), }; quote! { #bevy_ecs_path::component::StorageType::#storage_type } } fn hook_register_function_call( bevy_ecs_path: &Path, hook: TokenStream2, function: Option<TokenStream2>, ) -> Option<TokenStream2> { function.map(|meta| { quote! { fn #hook() -> ::core::option::Option<#bevy_ecs_path::lifecycle::ComponentHook> { ::core::option::Option::Some(#meta) } } }) } mod kw { syn::custom_keyword!(relationship_target); syn::custom_keyword!(relationship); syn::custom_keyword!(linked_spawn); } impl Parse for Relationship { fn parse(input: syn::parse::ParseStream) -> Result<Self> { input.parse::<kw::relationship_target>()?; input.parse::<Token![=]>()?; Ok(Relationship { relationship_target: input.parse::<Type>()?, }) } } impl Parse for RelationshipTarget { fn parse(input: syn::parse::ParseStream) -> Result<Self> { let mut relationship: Option<Type> = None; let mut linked_spawn: bool = false; while !input.is_empty() { let lookahead = input.lookahead1(); if lookahead.peek(kw::linked_spawn) { input.parse::<kw::linked_spawn>()?; linked_spawn = true; } else if lookahead.peek(kw::relationship) { input.parse::<kw::relationship>()?; input.parse::<Token![=]>()?; relationship = Some(input.parse()?); } else { return Err(lookahead.error()); } if !input.is_empty() { input.parse::<Token![,]>()?; } } Ok(RelationshipTarget { relationship: relationship.ok_or_else(|| { syn::Error::new(input.span(), "Missing `relationship = X` attribute") })?, linked_spawn, }) } } fn derive_relationship( ast: &DeriveInput, attrs: &Attrs, bevy_ecs_path: &Path, ) -> Result<Option<TokenStream2>> { let Some(relationship) = &attrs.relationship else { return Ok(None); }; let Data::Struct(DataStruct { fields, struct_token, .. }) = &ast.data else { return Err(syn::Error::new( ast.span(), "Relationship can only be derived for structs.", )); }; let field = relationship_field(fields, "Relationship", struct_token.span())?; let relationship_member = field.ident.clone().map_or(Member::from(0), Member::Named); let members = fields .members() .filter(|member| member != &relationship_member); let struct_name = &ast.ident; let (impl_generics, type_generics, where_clause) = &ast.generics.split_for_impl(); let relationship_target = &relationship.relationship_target; Ok(Some(quote! { impl #impl_generics #bevy_ecs_path::relationship::Relationship for #struct_name #type_generics #where_clause { type RelationshipTarget = #relationship_target; #[inline(always)] fn get(&self) -> #bevy_ecs_path::entity::Entity { self.#relationship_member } #[inline] fn from(entity: #bevy_ecs_path::entity::Entity) -> Self { Self { #(#members: core::default::Default::default(),)* #relationship_member: entity } } #[inline] fn set_risky(&mut self, entity: #bevy_ecs_path::entity::Entity) { self.#relationship_member = entity; } } })) } fn derive_relationship_target( ast: &DeriveInput, attrs: &Attrs, bevy_ecs_path: &Path, ) -> Result<Option<TokenStream2>> { let Some(relationship_target) = &attrs.relationship_target else { return Ok(None); }; let Data::Struct(DataStruct { fields, struct_token, .. }) = &ast.data else { return Err(syn::Error::new( ast.span(), "RelationshipTarget can only be derived for structs.", )); }; let field = relationship_field(fields, "RelationshipTarget", struct_token.span())?; if field.vis != Visibility::Inherited { return Err(syn::Error::new(field.span(), "The collection in RelationshipTarget must be private to prevent users from directly mutating it, which could invalidate the correctness of relationships.")); } let collection = &field.ty; let relationship_member = field.ident.clone().map_or(Member::from(0), Member::Named); let members = fields .members() .filter(|member| member != &relationship_member); let relationship = &relationship_target.relationship; let struct_name = &ast.ident; let (impl_generics, type_generics, where_clause) = &ast.generics.split_for_impl(); let linked_spawn = relationship_target.linked_spawn; Ok(Some(quote! { impl #impl_generics #bevy_ecs_path::relationship::RelationshipTarget for #struct_name #type_generics #where_clause { const LINKED_SPAWN: bool = #linked_spawn; type Relationship = #relationship; type Collection = #collection; #[inline] fn collection(&self) -> &Self::Collection { &self.#relationship_member } #[inline] fn collection_mut_risky(&mut self) -> &mut Self::Collection { &mut self.#relationship_member } #[inline] fn from_collection_risky(collection: Self::Collection) -> Self { Self { #(#members: core::default::Default::default(),)* #relationship_member: collection } } } })) } /// Returns the field with the `#[relationship]` attribute, the only field if unnamed, /// or the only field in a [`Fields::Named`] with one field, otherwise `Err`. fn relationship_field<'a>( fields: &'a Fields, derive: &'static str, span: Span, ) -> Result<&'a Field> { match fields { Fields::Named(fields) if fields.named.len() == 1 => Ok(fields.named.first().unwrap()), Fields::Named(fields) => fields.named.iter().find(|field| { field .attrs .iter() .any(|attr| attr.path().is_ident(RELATIONSHIP))
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/resource.rs
crates/bevy_ecs/src/resource.rs
//! Resources are unique, singleton-like data types that can be accessed from systems and stored in the [`World`](crate::world::World). // The derive macro for the `Resource` trait pub use bevy_ecs_macros::Resource; /// A type that can be inserted into a [`World`] as a singleton. /// /// You can access resource data in systems using the [`Res`] and [`ResMut`] system parameters /// /// Only one resource of each type can be stored in a [`World`] at any given time. /// /// # Examples /// /// ``` /// # let mut world = World::default(); /// # let mut schedule = Schedule::default(); /// # use bevy_ecs::prelude::*; /// #[derive(Resource)] /// struct MyResource { value: u32 } /// /// world.insert_resource(MyResource { value: 42 }); /// /// fn read_resource_system(resource: Res<MyResource>) { /// assert_eq!(resource.value, 42); /// } /// /// fn write_resource_system(mut resource: ResMut<MyResource>) { /// assert_eq!(resource.value, 42); /// resource.value = 0; /// assert_eq!(resource.value, 0); /// } /// # schedule.add_systems((read_resource_system, write_resource_system).chain()); /// # schedule.run(&mut world); /// ``` /// /// # `!Sync` Resources /// A `!Sync` type cannot implement `Resource`. However, it is possible to wrap a `Send` but not `Sync` /// type in [`SyncCell`] or the currently unstable [`Exclusive`] to make it `Sync`. This forces only /// having mutable access (`&mut T` only, never `&T`), but makes it safe to reference across multiple /// threads. /// /// This will fail to compile since `RefCell` is `!Sync`. /// ```compile_fail /// # use std::cell::RefCell; /// # use bevy_ecs::resource::Resource; /// /// #[derive(Resource)] /// struct NotSync { /// counter: RefCell<usize>, /// } /// ``` /// /// This will compile since the `RefCell` is wrapped with `SyncCell`. /// ``` /// # use std::cell::RefCell; /// # use bevy_ecs::resource::Resource; /// use bevy_platform::cell::SyncCell; /// /// #[derive(Resource)] /// struct ActuallySync { /// counter: SyncCell<RefCell<usize>>, /// } /// ``` /// /// [`Exclusive`]: https://doc.rust-lang.org/nightly/std/sync/struct.Exclusive.html /// [`World`]: crate::world::World /// [`Res`]: crate::system::Res /// [`ResMut`]: crate::system::ResMut /// [`SyncCell`]: bevy_platform::cell::SyncCell #[diagnostic::on_unimplemented( message = "`{Self}` is not a `Resource`", label = "invalid `Resource`", note = "consider annotating `{Self}` with `#[derive(Resource)]`" )] pub trait Resource: Send + Sync + 'static {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/batching.rs
crates/bevy_ecs/src/batching.rs
//! Types for controlling batching behavior during parallel processing. use core::ops::Range; /// Dictates how a parallel operation chunks up large quantities /// during iteration. /// /// A parallel query will chunk up large tables and archetypes into /// chunks of at most a certain batch size. Similarly, a parallel event /// reader will chunk up the remaining events. /// /// By default, this batch size is automatically determined by dividing /// the size of the largest matched archetype by the number /// of threads (rounded up). This attempts to minimize the overhead of scheduling /// tasks onto multiple threads, but assumes each entity has roughly the /// same amount of work to be done, which may not hold true in every /// workload. /// /// See [`Query::par_iter`], [`MessageReader::par_read`] for more information. /// /// [`Query::par_iter`]: crate::system::Query::par_iter /// [`MessageReader::par_read`]: crate::message::MessageReader::par_read #[derive(Clone, Debug)] pub struct BatchingStrategy { /// The upper and lower limits for a batch of items. /// /// Setting the bounds to the same value will result in a fixed /// batch size. /// /// Defaults to `[1, usize::MAX]`. pub batch_size_limits: Range<usize>, /// The number of batches per thread in the [`ComputeTaskPool`]. /// Increasing this value will decrease the batch size, which may /// increase the scheduling overhead for the iteration. /// /// Defaults to 1. /// /// [`ComputeTaskPool`]: bevy_tasks::ComputeTaskPool pub batches_per_thread: usize, } impl Default for BatchingStrategy { fn default() -> Self { Self::new() } } impl BatchingStrategy { /// Creates a new unconstrained default batching strategy. pub const fn new() -> Self { Self { batch_size_limits: 1..usize::MAX, batches_per_thread: 1, } } /// Declares a batching strategy with a fixed batch size. pub const fn fixed(batch_size: usize) -> Self { Self { batch_size_limits: batch_size..batch_size, batches_per_thread: 1, } } /// Configures the minimum allowed batch size of this instance. pub const fn min_batch_size(mut self, batch_size: usize) -> Self { self.batch_size_limits.start = batch_size; self } /// Configures the maximum allowed batch size of this instance. pub const fn max_batch_size(mut self, batch_size: usize) -> Self { self.batch_size_limits.end = batch_size; self } /// Configures the number of batches to assign to each thread for this instance. pub fn batches_per_thread(mut self, batches_per_thread: usize) -> Self { assert!( batches_per_thread > 0, "The number of batches per thread must be non-zero." ); self.batches_per_thread = batches_per_thread; self } /// Calculate the batch size according to the given thread count and max item count. /// The count is provided as a closure so that it can be calculated only if needed. /// /// # Panics /// /// Panics if `thread_count` is 0. #[inline] pub fn calc_batch_size(&self, max_items: impl FnOnce() -> usize, thread_count: usize) -> usize { if self.batch_size_limits.is_empty() { return self.batch_size_limits.start; } assert!( thread_count > 0, "Attempted to run parallel iteration with an empty TaskPool" ); let batches = thread_count * self.batches_per_thread; // Round up to the nearest batch size. let batch_size = max_items().div_ceil(batches); batch_size.clamp(self.batch_size_limits.start, self.batch_size_limits.end) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/lib.rs
crates/bevy_ecs/src/lib.rs
#![doc = include_str!("../README.md")] #![cfg_attr( any(docsrs, docsrs_dep), expect( internal_features, reason = "rustdoc_internals is needed for fake_variadic" ) )] #![cfg_attr(any(docsrs, docsrs_dep), feature(doc_cfg, rustdoc_internals))] #![expect(unsafe_code, reason = "Unsafe code is used to improve performance.")] #![doc( html_logo_url = "https://bevy.org/assets/icon.png", html_favicon_url = "https://bevy.org/assets/icon.png" )] #![no_std] #[cfg(feature = "std")] extern crate std; #[cfg(target_pointer_width = "16")] compile_error!("bevy_ecs cannot safely compile for a 16-bit platform."); extern crate alloc; // Required to make proc macros work in bevy itself. extern crate self as bevy_ecs; pub mod archetype; pub mod batching; pub mod bundle; pub mod change_detection; pub mod component; pub mod entity; pub mod entity_disabling; pub mod error; pub mod event; pub mod hierarchy; pub mod intern; pub mod label; pub mod lifecycle; pub mod message; pub mod name; pub mod never; pub mod observer; pub mod query; #[cfg(feature = "bevy_reflect")] pub mod reflect; pub mod relationship; pub mod resource; pub mod schedule; pub mod spawn; pub mod storage; pub mod system; pub mod traversal; pub mod world; pub use bevy_ptr as ptr; #[cfg(feature = "hotpatching")] use message::Message; /// The ECS prelude. /// /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { #[doc(hidden)] pub use crate::{ bundle::Bundle, change_detection::{DetectChanges, DetectChangesMut, Mut, Ref}, children, component::Component, entity::{ContainsEntity, Entity, EntityMapper}, error::{BevyError, Result}, event::{EntityEvent, Event}, hierarchy::{ChildOf, ChildSpawner, ChildSpawnerCommands, Children}, lifecycle::{Add, Despawn, Insert, Remove, RemovedComponents, Replace}, message::{Message, MessageMutator, MessageReader, MessageWriter, Messages}, name::{Name, NameOrEntity}, observer::{Observer, On}, query::{Added, Allow, AnyOf, Changed, Has, Or, QueryBuilder, QueryState, With, Without}, related, relationship::RelationshipTarget, resource::Resource, schedule::{ common_conditions::*, ApplyDeferred, IntoScheduleConfigs, IntoSystemSet, Schedule, Schedules, SystemCondition, SystemSet, }, spawn::{Spawn, SpawnIter, SpawnRelated, SpawnWith, WithOneRelated, WithRelated}, system::{ Command, Commands, Deferred, EntityCommand, EntityCommands, If, In, InMut, InRef, IntoSystem, Local, NonSend, NonSendMut, ParamSet, Populated, Query, ReadOnlySystem, Res, ResMut, Single, System, SystemIn, SystemInput, SystemParamBuilder, SystemParamFunction, }, world::{ EntityMut, EntityRef, EntityWorldMut, FilteredResources, FilteredResourcesMut, FromWorld, World, }, }; #[doc(hidden)] #[cfg(feature = "std")] pub use crate::system::ParallelCommands; #[doc(hidden)] #[cfg(feature = "bevy_reflect")] pub use crate::reflect::{ AppTypeRegistry, ReflectComponent, ReflectEvent, ReflectFromWorld, ReflectResource, }; #[doc(hidden)] #[cfg(feature = "reflect_functions")] pub use crate::reflect::AppFunctionRegistry; } /// Exports used by macros. /// /// These are not meant to be used directly and are subject to breaking changes. #[doc(hidden)] pub mod __macro_exports { // Cannot directly use `alloc::vec::Vec` in macros, as a crate may not have // included `extern crate alloc;`. This re-export ensures we have access // to `Vec` in `no_std` and `std` contexts. pub use crate::query::DebugCheckedUnwrap; pub use alloc::vec::Vec; } /// Event sent when a hotpatch happens. /// /// Can be used for causing custom behavior on hot-patch. #[cfg(feature = "hotpatching")] #[derive(Message, Default)] pub struct HotPatched; /// Resource which "changes" when a hotpatch happens. /// /// Exists solely for change-detection, which allows systems to /// know whether a hotpatch happened even if they only run irregularily and would /// miss the event. /// /// Used by Executors and other places which run systems /// [`System::refresh_hotpatch`](crate::system::System::refresh_hotpatch) only when necessary. #[cfg(feature = "hotpatching")] #[derive(resource::Resource, Default)] pub struct HotPatchChanges; #[cfg(test)] mod tests { use crate::{ bundle::Bundle, change_detection::Ref, component::Component, entity::{Entity, EntityMapper, EntityNotSpawnedError}, entity_disabling::DefaultQueryFilters, prelude::Or, query::{Added, Changed, FilteredAccess, QueryFilter, With, Without}, resource::Resource, world::{error::EntityDespawnError, EntityMut, EntityRef, Mut, World}, }; use alloc::{string::String, sync::Arc, vec, vec::Vec}; use bevy_platform::collections::HashSet; use bevy_tasks::{ComputeTaskPool, TaskPool}; use core::{ any::TypeId, marker::PhantomData, sync::atomic::{AtomicUsize, Ordering}, }; use std::sync::Mutex; #[derive(Component, Debug, PartialEq, Eq, Hash, Clone, Copy)] struct A(usize); #[derive(Resource, Debug, PartialEq, Eq)] struct ResA(usize); #[derive(Component, Debug, PartialEq, Eq, Hash, Clone, Copy)] struct B(usize); #[derive(Component, Debug, PartialEq, Eq, Clone, Copy)] struct C; #[derive(Default)] struct NonSendA(PhantomData<*mut ()>); #[derive(Component, Clone, Debug)] struct DropCk(Arc<AtomicUsize>); impl DropCk { fn new_pair() -> (Self, Arc<AtomicUsize>) { let atomic = Arc::new(AtomicUsize::new(0)); (DropCk(atomic.clone()), atomic) } } impl Drop for DropCk { fn drop(&mut self) { self.0.as_ref().fetch_add(1, Ordering::Relaxed); } } #[expect( dead_code, 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." )] #[derive(Component, Clone, Debug)] #[component(storage = "SparseSet")] struct DropCkSparse(DropCk); #[derive(Component, Copy, Clone, PartialEq, Eq, Debug)] #[component(storage = "Table")] struct TableStored(&'static str); #[derive(Component, Copy, Clone, PartialEq, Eq, Hash, Debug)] #[component(storage = "SparseSet")] struct SparseStored(u32); #[test] fn random_access() { let mut world = World::new(); let e = world.spawn((TableStored("abc"), SparseStored(123))).id(); let f = world .spawn((TableStored("def"), SparseStored(456), A(1))) .id(); assert_eq!(world.get::<TableStored>(e).unwrap().0, "abc"); assert_eq!(world.get::<SparseStored>(e).unwrap().0, 123); assert_eq!(world.get::<TableStored>(f).unwrap().0, "def"); assert_eq!(world.get::<SparseStored>(f).unwrap().0, 456); // test archetype get_mut() world.get_mut::<TableStored>(e).unwrap().0 = "xyz"; assert_eq!(world.get::<TableStored>(e).unwrap().0, "xyz"); // test sparse set get_mut() world.get_mut::<SparseStored>(f).unwrap().0 = 42; assert_eq!(world.get::<SparseStored>(f).unwrap().0, 42); } #[test] fn bundle_derive() { let mut world = World::new(); #[derive(Bundle, PartialEq, Debug)] struct FooBundle { x: TableStored, y: SparseStored, } let ids: Vec<_> = <FooBundle as Bundle>::component_ids(&mut world.components_registrator()).collect(); assert_eq!( ids, &[ world.register_component::<TableStored>(), world.register_component::<SparseStored>(), ] ); let e1 = world .spawn(FooBundle { x: TableStored("abc"), y: SparseStored(123), }) .id(); let e2 = world .spawn((TableStored("def"), SparseStored(456), A(1))) .id(); assert_eq!(world.get::<TableStored>(e1).unwrap().0, "abc"); assert_eq!(world.get::<SparseStored>(e1).unwrap().0, 123); assert_eq!(world.get::<TableStored>(e2).unwrap().0, "def"); assert_eq!(world.get::<SparseStored>(e2).unwrap().0, 456); // test archetype get_mut() world.get_mut::<TableStored>(e1).unwrap().0 = "xyz"; assert_eq!(world.get::<TableStored>(e1).unwrap().0, "xyz"); // test sparse set get_mut() world.get_mut::<SparseStored>(e2).unwrap().0 = 42; assert_eq!(world.get::<SparseStored>(e2).unwrap().0, 42); assert_eq!( world.entity_mut(e1).take::<FooBundle>().unwrap(), FooBundle { x: TableStored("xyz"), y: SparseStored(123), } ); #[derive(Bundle, PartialEq, Debug)] struct NestedBundle { a: A, foo: FooBundle, b: B, } let ids: Vec<_> = <NestedBundle as Bundle>::component_ids(&mut world.components_registrator()).collect(); assert_eq!( ids, &[ world.register_component::<A>(), world.register_component::<TableStored>(), world.register_component::<SparseStored>(), world.register_component::<B>(), ] ); let e3 = world .spawn(NestedBundle { a: A(1), foo: FooBundle { x: TableStored("ghi"), y: SparseStored(789), }, b: B(2), }) .id(); assert_eq!(world.get::<TableStored>(e3).unwrap().0, "ghi"); assert_eq!(world.get::<SparseStored>(e3).unwrap().0, 789); assert_eq!(world.get::<A>(e3).unwrap().0, 1); assert_eq!(world.get::<B>(e3).unwrap().0, 2); assert_eq!( world.entity_mut(e3).take::<NestedBundle>().unwrap(), NestedBundle { a: A(1), foo: FooBundle { x: TableStored("ghi"), y: SparseStored(789), }, b: B(2), } ); #[derive(Default, Component, PartialEq, Debug)] struct Ignored; #[derive(Bundle, PartialEq, Debug)] struct BundleWithIgnored { c: C, #[bundle(ignore)] ignored: Ignored, } let ids: Vec<_> = <BundleWithIgnored as Bundle>::component_ids(&mut world.components_registrator()) .collect(); assert_eq!(ids, &[world.register_component::<C>(),]); let e4 = world .spawn(BundleWithIgnored { c: C, ignored: Ignored, }) .id(); assert_eq!(world.get::<C>(e4).unwrap(), &C); assert_eq!(world.get::<Ignored>(e4), None); assert_eq!( world.entity_mut(e4).take::<BundleWithIgnored>().unwrap(), BundleWithIgnored { c: C, ignored: Ignored, } ); } #[test] fn spawning_with_manual_entity_allocation() { let mut world = World::new(); let e1 = world.entities_allocator_mut().alloc(); world.spawn_at(e1, (TableStored("abc"), A(123))).unwrap(); let e2 = world.entities_allocator_mut().alloc(); assert!(matches!( world.try_despawn_no_free(e2), Err(EntityDespawnError( EntityNotSpawnedError::ValidButNotSpawned(_) )) )); assert!(!world.despawn(e2)); world.entities_allocator_mut().free(e2); let e3 = world.entities_allocator_mut().alloc(); let e3 = world .spawn_at(e3, (TableStored("junk"), A(0))) .unwrap() .despawn_no_free(); world.spawn_at(e3, (TableStored("def"), A(456))).unwrap(); assert_eq!(world.entities.count_spawned(), 2); assert!(world.despawn(e1)); assert_eq!(world.entities.count_spawned(), 1); assert!(world.get::<TableStored>(e1).is_none()); assert!(world.get::<A>(e1).is_none()); assert_eq!(world.get::<TableStored>(e3).unwrap().0, "def"); assert_eq!(world.get::<A>(e3).unwrap().0, 456); } #[test] fn despawn_table_storage() { let mut world = World::new(); let e = world.spawn((TableStored("abc"), A(123))).id(); let f = world.spawn((TableStored("def"), A(456))).id(); assert_eq!(world.query::<&TableStored>().query(&world).count(), 2); assert!(world.despawn(e)); assert_eq!(world.query::<&TableStored>().query(&world).count(), 1); assert!(world.get::<TableStored>(e).is_none()); assert!(world.get::<A>(e).is_none()); assert_eq!(world.get::<TableStored>(f).unwrap().0, "def"); assert_eq!(world.get::<A>(f).unwrap().0, 456); } #[test] fn despawn_mixed_storage() { let mut world = World::new(); let e = world.spawn((TableStored("abc"), SparseStored(123))).id(); let f = world.spawn((TableStored("def"), SparseStored(456))).id(); assert_eq!(world.query::<&TableStored>().query(&world).count(), 2); assert!(world.despawn(e)); assert_eq!(world.query::<&TableStored>().query(&world).count(), 1); assert!(world.get::<TableStored>(e).is_none()); assert!(world.get::<SparseStored>(e).is_none()); assert_eq!(world.get::<TableStored>(f).unwrap().0, "def"); assert_eq!(world.get::<SparseStored>(f).unwrap().0, 456); } #[test] fn query_all() { let mut world = World::new(); let e = world.spawn((TableStored("abc"), A(123))).id(); let f = world.spawn((TableStored("def"), A(456))).id(); let ents = world .query::<(Entity, &A, &TableStored)>() .iter(&world) .map(|(e, &i, &s)| (e, i, s)) .collect::<Vec<_>>(); assert_eq!( ents, &[ (e, A(123), TableStored("abc")), (f, A(456), TableStored("def")) ] ); } #[test] fn query_all_for_each() { let mut world = World::new(); let e = world.spawn((TableStored("abc"), A(123))).id(); let f = world.spawn((TableStored("def"), A(456))).id(); let mut results = Vec::new(); world .query::<(Entity, &A, &TableStored)>() .iter(&world) .for_each(|(e, &i, &s)| results.push((e, i, s))); assert_eq!( results, &[ (e, A(123), TableStored("abc")), (f, A(456), TableStored("def")) ] ); } #[test] fn query_single_component() { let mut world = World::new(); let e = world.spawn((TableStored("abc"), A(123))).id(); let f = world.spawn((TableStored("def"), A(456), B(1))).id(); let ents = world .query::<(Entity, &A)>() .iter(&world) .map(|(e, &i)| (e, i)) .collect::<HashSet<_>>(); assert!(ents.contains(&(e, A(123)))); assert!(ents.contains(&(f, A(456)))); } #[test] fn stateful_query_handles_new_archetype() { let mut world = World::new(); let e = world.spawn((TableStored("abc"), A(123))).id(); let mut query = world.query::<(Entity, &A)>(); let ents = query.iter(&world).map(|(e, &i)| (e, i)).collect::<Vec<_>>(); assert_eq!(ents, &[(e, A(123))]); let f = world.spawn((TableStored("def"), A(456), B(1))).id(); let ents = query.iter(&world).map(|(e, &i)| (e, i)).collect::<Vec<_>>(); assert_eq!(ents, &[(e, A(123)), (f, A(456))]); } #[test] fn query_single_component_for_each() { let mut world = World::new(); let e = world.spawn((TableStored("abc"), A(123))).id(); let f = world.spawn((TableStored("def"), A(456), B(1))).id(); let mut results = <HashSet<_>>::default(); world .query::<(Entity, &A)>() .iter(&world) .for_each(|(e, &i)| { results.insert((e, i)); }); assert!(results.contains(&(e, A(123)))); assert!(results.contains(&(f, A(456)))); } #[test] fn par_for_each_dense() { ComputeTaskPool::get_or_init(TaskPool::default); let mut world = World::new(); let e1 = world.spawn(A(1)).id(); let e2 = world.spawn(A(2)).id(); let e3 = world.spawn(A(3)).id(); let e4 = world.spawn((A(4), B(1))).id(); let e5 = world.spawn((A(5), B(1))).id(); let results = Arc::new(Mutex::new(Vec::new())); world .query::<(Entity, &A)>() .par_iter(&world) .for_each(|(e, &A(i))| { results.lock().unwrap().push((e, i)); }); results.lock().unwrap().sort(); let mut expected = [(e1, 1), (e2, 2), (e3, 3), (e4, 4), (e5, 5)]; expected.sort(); assert_eq!(&*results.lock().unwrap(), &expected); } #[test] fn par_for_each_sparse() { ComputeTaskPool::get_or_init(TaskPool::default); let mut world = World::new(); let e1 = world.spawn(SparseStored(1)).id(); let e2 = world.spawn(SparseStored(2)).id(); let e3 = world.spawn(SparseStored(3)).id(); let e4 = world.spawn((SparseStored(4), A(1))).id(); let e5 = world.spawn((SparseStored(5), A(1))).id(); let results = Arc::new(Mutex::new(Vec::new())); world .query::<(Entity, &SparseStored)>() .par_iter(&world) .for_each(|(e, &SparseStored(i))| results.lock().unwrap().push((e, i))); results.lock().unwrap().sort(); let mut expected = [(e1, 1), (e2, 2), (e3, 3), (e4, 4), (e5, 5)]; expected.sort(); assert_eq!(&*results.lock().unwrap(), &expected); } #[test] fn query_missing_component() { let mut world = World::new(); world.spawn((TableStored("abc"), A(123))); world.spawn((TableStored("def"), A(456))); assert!(world.query::<(&B, &A)>().iter(&world).next().is_none()); } #[test] fn query_sparse_component() { let mut world = World::new(); world.spawn((TableStored("abc"), A(123))); let f = world.spawn((TableStored("def"), A(456), B(1))).id(); let ents = world .query::<(Entity, &B)>() .iter(&world) .map(|(e, &b)| (e, b)) .collect::<Vec<_>>(); assert_eq!(ents, &[(f, B(1))]); } #[test] fn query_filter_with() { let mut world = World::new(); world.spawn((A(123), B(1))); world.spawn(A(456)); let result = world .query_filtered::<&A, With<B>>() .iter(&world) .cloned() .collect::<Vec<_>>(); assert_eq!(result, vec![A(123)]); } #[test] fn query_filter_with_for_each() { let mut world = World::new(); world.spawn((A(123), B(1))); world.spawn(A(456)); let mut results = Vec::new(); world .query_filtered::<&A, With<B>>() .iter(&world) .for_each(|i| results.push(*i)); assert_eq!(results, vec![A(123)]); } #[test] fn query_filter_with_sparse() { let mut world = World::new(); world.spawn((A(123), SparseStored(321))); world.spawn(A(456)); let result = world .query_filtered::<&A, With<SparseStored>>() .iter(&world) .cloned() .collect::<Vec<_>>(); assert_eq!(result, vec![A(123)]); } #[test] fn query_filter_with_sparse_for_each() { let mut world = World::new(); world.spawn((A(123), SparseStored(321))); world.spawn(A(456)); let mut results = Vec::new(); world .query_filtered::<&A, With<SparseStored>>() .iter(&world) .for_each(|i| results.push(*i)); assert_eq!(results, vec![A(123)]); } #[test] fn query_filter_without() { let mut world = World::new(); world.spawn((A(123), B(321))); world.spawn(A(456)); let result = world .query_filtered::<&A, Without<B>>() .iter(&world) .cloned() .collect::<Vec<_>>(); assert_eq!(result, vec![A(456)]); } #[test] fn query_optional_component_table() { let mut world = World::new(); let e = world.spawn((TableStored("abc"), A(123))).id(); let f = world.spawn((TableStored("def"), A(456), B(1))).id(); // this should be skipped world.spawn(TableStored("abc")); let ents = world .query::<(Entity, Option<&B>, &A)>() .iter(&world) .map(|(e, b, &i)| (e, b.copied(), i)) .collect::<HashSet<_>>(); assert!(ents.contains(&(e, None, A(123)))); assert!(ents.contains(&(f, Some(B(1)), A(456)))); } #[test] fn query_optional_component_sparse() { let mut world = World::new(); let e = world.spawn((TableStored("abc"), A(123))).id(); let f = world .spawn((TableStored("def"), A(456), SparseStored(1))) .id(); // this should be skipped // world.spawn(SparseStored(1)); let ents = world .query::<(Entity, Option<&SparseStored>, &A)>() .iter(&world) .map(|(e, b, &i)| (e, b.copied(), i)) .collect::<HashSet<_>>(); assert_eq!( ents, [(e, None, A(123)), (f, Some(SparseStored(1)), A(456))] .into_iter() .collect::<HashSet<_>>() ); } #[test] fn query_optional_component_sparse_no_match() { let mut world = World::new(); let e = world.spawn((TableStored("abc"), A(123))).id(); let f = world.spawn((TableStored("def"), A(456))).id(); // // this should be skipped world.spawn(TableStored("abc")); let ents = world .query::<(Entity, Option<&SparseStored>, &A)>() .iter(&world) .map(|(e, b, &i)| (e, b.copied(), i)) .collect::<Vec<_>>(); assert_eq!(ents, &[(e, None, A(123)), (f, None, A(456))]); } #[test] fn add_remove_components() { let mut world = World::new(); let e1 = world.spawn((A(1), B(3), TableStored("abc"))).id(); let e2 = world.spawn((A(2), B(4), TableStored("xyz"))).id(); assert_eq!( world .query::<(Entity, &A, &B)>() .iter(&world) .map(|(e, &i, &b)| (e, i, b)) .collect::<HashSet<_>>(), [(e1, A(1), B(3)), (e2, A(2), B(4))] .into_iter() .collect::<HashSet<_>>() ); assert_eq!(world.entity_mut(e1).take::<A>(), Some(A(1))); assert_eq!( world .query::<(Entity, &A, &B)>() .iter(&world) .map(|(e, &i, &b)| (e, i, b)) .collect::<Vec<_>>(), &[(e2, A(2), B(4))] ); assert_eq!( world .query::<(Entity, &B, &TableStored)>() .iter(&world) .map(|(e, &B(b), &TableStored(s))| (e, b, s)) .collect::<HashSet<_>>(), [(e2, 4, "xyz"), (e1, 3, "abc")] .into_iter() .collect::<HashSet<_>>() ); world.entity_mut(e1).insert(A(43)); assert_eq!( world .query::<(Entity, &A, &B)>() .iter(&world) .map(|(e, &i, &b)| (e, i, b)) .collect::<HashSet<_>>(), [(e2, A(2), B(4)), (e1, A(43), B(3))] .into_iter() .collect::<HashSet<_>>() ); world.entity_mut(e1).insert(C); assert_eq!( world .query::<(Entity, &C)>() .iter(&world) .map(|(e, &f)| (e, f)) .collect::<Vec<_>>(), &[(e1, C)] ); } #[test] fn table_add_remove_many() { let mut world = World::default(); #[cfg(miri)] let (mut entities, to) = { let to = 10; (Vec::with_capacity(to), to) }; #[cfg(not(miri))] let (mut entities, to) = { let to = 10_000; (Vec::with_capacity(to), to) }; for _ in 0..to { entities.push(world.spawn(B(0)).id()); } for (i, entity) in entities.iter().cloned().enumerate() { world.entity_mut(entity).insert(A(i)); } for (i, entity) in entities.iter().cloned().enumerate() { assert_eq!(world.entity_mut(entity).take::<A>(), Some(A(i))); } } #[test] fn sparse_set_add_remove_many() { let mut world = World::default(); let mut entities = Vec::with_capacity(1000); for _ in 0..4 { entities.push(world.spawn(A(2)).id()); } for (i, entity) in entities.iter().cloned().enumerate() { world.entity_mut(entity).insert(SparseStored(i as u32)); } for (i, entity) in entities.iter().cloned().enumerate() { assert_eq!( world.entity_mut(entity).take::<SparseStored>(), Some(SparseStored(i as u32)) ); } } #[test] fn remove_missing() { let mut world = World::new(); let e = world.spawn((TableStored("abc"), A(123))).id(); assert!(world.entity_mut(e).take::<B>().is_none()); } #[test] fn spawn_batch() { let mut world = World::new(); world.spawn_batch((0..100).map(|x| (A(x), TableStored("abc")))); let values = world .query::<&A>() .iter(&world) .map(|v| v.0) .collect::<Vec<_>>(); let expected = (0..100).collect::<Vec<_>>(); assert_eq!(values, expected); } #[test] fn query_get() { let mut world = World::new(); let a = world.spawn((TableStored("abc"), A(123))).id(); let b = world.spawn((TableStored("def"), A(456))).id(); let c = world.spawn((TableStored("ghi"), A(789), B(1))).id(); let mut i32_query = world.query::<&A>(); assert_eq!(i32_query.get(&world, a).unwrap().0, 123); assert_eq!(i32_query.get(&world, b).unwrap().0, 456); let mut i32_bool_query = world.query::<(&A, &B)>(); assert!(i32_bool_query.get(&world, a).is_err()); assert_eq!(i32_bool_query.get(&world, c).unwrap(), (&A(789), &B(1))); assert!(world.despawn(a)); assert!(i32_query.get(&world, a).is_err()); } #[test] fn query_get_works_across_sparse_removal() { // Regression test for: https://github.com/bevyengine/bevy/issues/6623 let mut world = World::new(); let a = world.spawn((TableStored("abc"), SparseStored(123))).id(); let b = world.spawn((TableStored("def"), SparseStored(456))).id(); let c = world .spawn((TableStored("ghi"), SparseStored(789), B(1))) .id(); let mut query = world.query::<&TableStored>(); assert_eq!(query.get(&world, a).unwrap(), &TableStored("abc")); assert_eq!(query.get(&world, b).unwrap(), &TableStored("def")); assert_eq!(query.get(&world, c).unwrap(), &TableStored("ghi")); world.entity_mut(b).remove::<SparseStored>(); world.entity_mut(c).remove::<SparseStored>(); assert_eq!(query.get(&world, a).unwrap(), &TableStored("abc")); assert_eq!(query.get(&world, b).unwrap(), &TableStored("def")); assert_eq!(query.get(&world, c).unwrap(), &TableStored("ghi")); } #[test] fn remove_tracking() { let mut world = World::new(); let a = world.spawn((SparseStored(0), A(123))).id(); let b = world.spawn((SparseStored(1), A(123))).id(); world.entity_mut(a).despawn(); assert_eq!( world.removed::<A>().collect::<Vec<_>>(), &[a], "despawning results in 'removed component' state for table components" ); assert_eq!( world.removed::<SparseStored>().collect::<Vec<_>>(), &[a], "despawning results in 'removed component' state for sparse set components" ); world.entity_mut(b).insert(B(1)); assert_eq!( world.removed::<A>().collect::<Vec<_>>(), &[a], "archetype moves does not result in 'removed component' state" ); world.entity_mut(b).remove::<A>(); assert_eq!( world.removed::<A>().collect::<Vec<_>>(), &[a, b], "removing a component results in a 'removed component' state" ); world.clear_trackers(); assert_eq!( world.removed::<A>().collect::<Vec<_>>(), &[], "clearing trackers clears removals" ); assert_eq!( world.removed::<SparseStored>().collect::<Vec<_>>(), &[], "clearing trackers clears removals" ); assert_eq!( world.removed::<B>().collect::<Vec<_>>(), &[], "clearing trackers clears removals" ); // TODO: uncomment when world.clear() is implemented // let c = world.spawn(("abc", 123)).id(); // let d = world.spawn(("abc", 123)).id(); // world.clear(); // assert_eq!( // world.removed::<i32>(), // &[c, d], // "world clears result in 'removed component' states" // ); // assert_eq!( // world.removed::<&'static str>(), // &[c, d, b], // "world clears result in 'removed component' states" // ); // assert_eq!( // world.removed::<f64>(), // &[b], // "world clears result in 'removed component' states" // ); } #[test] fn added_tracking() { let mut world = World::new(); let a = world.spawn(A(123)).id(); assert_eq!(world.query::<&A>().iter(&world).count(), 1); assert_eq!( world.query_filtered::<(), Added<A>>().iter(&world).count(), 1 ); assert_eq!(world.query::<&A>().iter(&world).count(), 1); assert_eq!( world.query_filtered::<(), Added<A>>().iter(&world).count(), 1 ); assert!(world.query::<&A>().get(&world, a).is_ok()); assert!(world .query_filtered::<(), Added<A>>() .get(&world, a) .is_ok()); assert!(world.query::<&A>().get(&world, a).is_ok()); assert!(world .query_filtered::<(), Added<A>>() .get(&world, a) .is_ok()); world.clear_trackers(); assert_eq!(world.query::<&A>().iter(&world).count(), 1); assert_eq!( world.query_filtered::<(), Added<A>>().iter(&world).count(), 0 ); assert_eq!(world.query::<&A>().iter(&world).count(), 1); assert_eq!( world.query_filtered::<(), Added<A>>().iter(&world).count(), 0 ); assert!(world.query::<&A>().get(&world, a).is_ok()); assert!(world .query_filtered::<(), Added<A>>() .get(&world, a) .is_err()); assert!(world.query::<&A>().get(&world, a).is_ok()); assert!(world .query_filtered::<(), Added<A>>() .get(&world, a) .is_err()); } #[test] fn added_queries() { let mut world = World::default(); let e1 = world.spawn(A(0)).id(); fn get_added<Com: Component>(world: &mut World) -> Vec<Entity> { world .query_filtered::<Entity, Added<Com>>() .iter(world) .collect::<Vec<Entity>>() } assert_eq!(get_added::<A>(&mut world), vec![e1]);
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/hierarchy.rs
crates/bevy_ecs/src/hierarchy.rs
//! The canonical "parent-child" [`Relationship`] for entities, driven by //! the [`ChildOf`] [`Relationship`] and the [`Children`] [`RelationshipTarget`]. //! //! See [`ChildOf`] for a full description of the relationship and how to use it. //! //! [`Relationship`]: crate::relationship::Relationship //! [`RelationshipTarget`]: crate::relationship::RelationshipTarget #[cfg(feature = "bevy_reflect")] use crate::reflect::{ReflectComponent, ReflectFromWorld}; use crate::{ bundle::Bundle, component::Component, entity::Entity, lifecycle::HookContext, name::Name, relationship::{RelatedSpawner, RelatedSpawnerCommands}, system::EntityCommands, world::{DeferredWorld, EntityWorldMut, FromWorld, World}, }; use alloc::{format, vec::Vec}; #[cfg(feature = "bevy_reflect")] use bevy_reflect::std_traits::ReflectDefault; #[cfg(all(feature = "serialize", feature = "bevy_reflect"))] use bevy_reflect::{ReflectDeserialize, ReflectSerialize}; use bevy_utils::prelude::DebugName; use core::ops::Deref; use core::slice; use log::warn; /// Stores the parent entity of this child entity with this component. /// /// This is a [`Relationship`] component, and creates the canonical /// "parent / child" hierarchy. This is the "source of truth" component, and it pairs with /// the [`Children`] [`RelationshipTarget`](crate::relationship::RelationshipTarget). /// /// This relationship should be used for things like: /// /// 1. Organizing entities in a scene /// 2. Propagating configuration or data inherited from a parent, such as "visibility" or "world-space global transforms". /// 3. Ensuring a hierarchy is despawned when an entity is despawned. /// /// [`ChildOf`] contains a single "target" [`Entity`]. When [`ChildOf`] is inserted on a "source" entity, /// the "target" entity will automatically (and immediately, via a component hook) have a [`Children`] /// component inserted, and the "source" entity will be added to that [`Children`] instance. /// /// If the [`ChildOf`] component is replaced with a different "target" entity, the old target's [`Children`] /// will be automatically (and immediately, via a component hook) be updated to reflect that change. /// /// Likewise, when the [`ChildOf`] component is removed, the "source" entity will be removed from the old /// target's [`Children`]. If this results in [`Children`] being empty, [`Children`] will be automatically removed. /// /// When a parent is despawned, all children (and their descendants) will _also_ be despawned. /// /// You can create parent-child relationships in a variety of ways. The most direct way is to insert a [`ChildOf`] component: /// /// ``` /// # use bevy_ecs::prelude::*; /// # let mut world = World::new(); /// let root = world.spawn_empty().id(); /// let child1 = world.spawn(ChildOf(root)).id(); /// let child2 = world.spawn(ChildOf(root)).id(); /// let grandchild = world.spawn(ChildOf(child1)).id(); /// /// assert_eq!(&**world.entity(root).get::<Children>().unwrap(), &[child1, child2]); /// assert_eq!(&**world.entity(child1).get::<Children>().unwrap(), &[grandchild]); /// /// world.entity_mut(child2).remove::<ChildOf>(); /// assert_eq!(&**world.entity(root).get::<Children>().unwrap(), &[child1]); /// /// world.entity_mut(root).despawn(); /// assert!(world.get_entity(root).is_err()); /// assert!(world.get_entity(child1).is_err()); /// assert!(world.get_entity(grandchild).is_err()); /// ``` /// /// However if you are spawning many children, you might want to use the [`EntityWorldMut::with_children`] helper instead: /// /// ``` /// # use bevy_ecs::prelude::*; /// # let mut world = World::new(); /// let mut child1 = Entity::PLACEHOLDER; /// let mut child2 = Entity::PLACEHOLDER; /// let mut grandchild = Entity::PLACEHOLDER; /// let root = world.spawn_empty().with_children(|p| { /// child1 = p.spawn_empty().with_children(|p| { /// grandchild = p.spawn_empty().id(); /// }).id(); /// child2 = p.spawn_empty().id(); /// }).id(); /// /// assert_eq!(&**world.entity(root).get::<Children>().unwrap(), &[child1, child2]); /// assert_eq!(&**world.entity(child1).get::<Children>().unwrap(), &[grandchild]); /// ``` /// /// [`Relationship`]: crate::relationship::Relationship #[derive(Component, Clone, PartialEq, Eq, Debug)] #[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))] #[cfg_attr( feature = "bevy_reflect", reflect(Component, PartialEq, Debug, FromWorld, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] #[relationship(relationship_target = Children)] #[doc(alias = "IsChild", alias = "Parent")] pub struct ChildOf(#[entities] pub Entity); impl ChildOf { /// The parent entity of this child entity. #[inline] pub fn parent(&self) -> Entity { self.0 } } // TODO: We need to impl either FromWorld or Default so ChildOf can be registered as Reflect. // This is because Reflect deserialize by creating an instance and apply a patch on top. // However ChildOf should only ever be set with a real user-defined entity. Its worth looking into // better ways to handle cases like this. impl FromWorld for ChildOf { #[inline(always)] fn from_world(_world: &mut World) -> Self { ChildOf(Entity::PLACEHOLDER) } } /// Tracks which entities are children of this parent entity. /// /// A [`RelationshipTarget`] collection component that is populated /// with entities that "target" this entity with the [`ChildOf`] [`Relationship`] component. /// /// Together, these components form the "canonical parent-child hierarchy". See the [`ChildOf`] component for the full /// description of this relationship and instructions on how to use it. /// /// # Usage /// /// Like all [`RelationshipTarget`] components, this data should not be directly manipulated to avoid desynchronization. /// Instead, modify the [`ChildOf`] components on the "source" entities. /// /// To access the children of an entity, you can iterate over the [`Children`] component, /// using the [`IntoIterator`] trait. /// For more complex access patterns, see the [`RelationshipTarget`] trait. /// /// [`Relationship`]: crate::relationship::Relationship /// [`RelationshipTarget`]: crate::relationship::RelationshipTarget #[derive(Component, Default, Debug, PartialEq, Eq)] #[relationship_target(relationship = ChildOf, linked_spawn)] #[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))] #[cfg_attr(feature = "bevy_reflect", reflect(Component, FromWorld, Default))] #[doc(alias = "IsParent")] pub struct Children(Vec<Entity>); impl Children { /// Swaps the child at `a_index` with the child at `b_index`. #[inline] pub fn swap(&mut self, a_index: usize, b_index: usize) { self.0.swap(a_index, b_index); } /// Sorts children [stably](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability) /// in place using the provided comparator function. /// /// For the underlying implementation, see [`slice::sort_by`]. /// /// For the unstable version, see [`sort_unstable_by`](Children::sort_unstable_by). /// /// See also [`sort_by_key`](Children::sort_by_key), [`sort_by_cached_key`](Children::sort_by_cached_key). #[inline] pub fn sort_by<F>(&mut self, compare: F) where F: FnMut(&Entity, &Entity) -> core::cmp::Ordering, { self.0.sort_by(compare); } /// Sorts children [stably](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability) /// in place using the provided key extraction function. /// /// For the underlying implementation, see [`slice::sort_by_key`]. /// /// For the unstable version, see [`sort_unstable_by_key`](Children::sort_unstable_by_key). /// /// See also [`sort_by`](Children::sort_by), [`sort_by_cached_key`](Children::sort_by_cached_key). #[inline] pub fn sort_by_key<K, F>(&mut self, compare: F) where F: FnMut(&Entity) -> K, K: Ord, { self.0.sort_by_key(compare); } /// Sorts children [stably](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability) /// in place using the provided key extraction function. Only evaluates each key at most /// once per sort, caching the intermediate results in memory. /// /// For the underlying implementation, see [`slice::sort_by_cached_key`]. /// /// See also [`sort_by`](Children::sort_by), [`sort_by_key`](Children::sort_by_key). #[inline] pub fn sort_by_cached_key<K, F>(&mut self, compare: F) where F: FnMut(&Entity) -> K, K: Ord, { self.0.sort_by_cached_key(compare); } /// Sorts children [unstably](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability) /// in place using the provided comparator function. /// /// For the underlying implementation, see [`slice::sort_unstable_by`]. /// /// For the stable version, see [`sort_by`](Children::sort_by). /// /// See also [`sort_unstable_by_key`](Children::sort_unstable_by_key). #[inline] pub fn sort_unstable_by<F>(&mut self, compare: F) where F: FnMut(&Entity, &Entity) -> core::cmp::Ordering, { self.0.sort_unstable_by(compare); } /// Sorts children [unstably](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability) /// in place using the provided key extraction function. /// /// For the underlying implementation, see [`slice::sort_unstable_by_key`]. /// /// For the stable version, see [`sort_by_key`](Children::sort_by_key). /// /// See also [`sort_unstable_by`](Children::sort_unstable_by). #[inline] pub fn sort_unstable_by_key<K, F>(&mut self, compare: F) where F: FnMut(&Entity) -> K, K: Ord, { self.0.sort_unstable_by_key(compare); } } impl<'a> IntoIterator for &'a Children { type Item = <Self::IntoIter as Iterator>::Item; type IntoIter = slice::Iter<'a, Entity>; #[inline(always)] fn into_iter(self) -> Self::IntoIter { self.0.iter() } } impl Deref for Children { type Target = [Entity]; fn deref(&self) -> &Self::Target { &self.0 } } /// A type alias over [`RelatedSpawner`] used to spawn child entities containing a [`ChildOf`] relationship. pub type ChildSpawner<'w> = RelatedSpawner<'w, ChildOf>; /// A type alias over [`RelatedSpawnerCommands`] used to spawn child entities containing a [`ChildOf`] relationship. pub type ChildSpawnerCommands<'w> = RelatedSpawnerCommands<'w, ChildOf>; impl<'w> EntityWorldMut<'w> { /// Spawns children of this entity (with a [`ChildOf`] relationship) by taking a function that operates on a [`ChildSpawner`]. /// See also [`with_related`](Self::with_related). pub fn with_children(&mut self, func: impl FnOnce(&mut ChildSpawner)) -> &mut Self { self.with_related_entities(func); self } /// Adds the given children to this entity. /// See also [`add_related`](Self::add_related). pub fn add_children(&mut self, children: &[Entity]) -> &mut Self { self.add_related::<ChildOf>(children) } /// Removes all the children from this entity. /// See also [`detach_all_related`](Self::detach_all_related) #[deprecated = "Use detach_all_children() instead"] pub fn clear_children(&mut self) -> &mut Self { self.detach_all_children() } /// Removes all the parent-child relationships from this entity. /// To despawn the child entities, instead use [`EntityWorldMut::despawn_children`](EntityWorldMut::despawn_children). /// See also [`detach_all_related`](Self::detach_all_related) pub fn detach_all_children(&mut self) -> &mut Self { self.detach_all_related::<ChildOf>() } /// Insert children at specific index. /// See also [`insert_related`](Self::insert_related). pub fn insert_children(&mut self, index: usize, children: &[Entity]) -> &mut Self { self.insert_related::<ChildOf>(index, children) } /// Insert child at specific index. /// See also [`insert_related`](Self::insert_related). pub fn insert_child(&mut self, index: usize, child: Entity) -> &mut Self { self.insert_related::<ChildOf>(index, &[child]) } /// Adds the given child to this entity. /// See also [`add_related`](Self::add_related). pub fn add_child(&mut self, child: Entity) -> &mut Self { self.add_related::<ChildOf>(&[child]) } /// Removes the relationship between this entity and the given entities. #[deprecated = "Use detach_children() instead"] pub fn remove_children(&mut self, children: &[Entity]) -> &mut Self { self.detach_children(children) } /// Removes the parent-child relationship between this entity and the given entities. /// Does not despawn the children. pub fn detach_children(&mut self, children: &[Entity]) -> &mut Self { self.remove_related::<ChildOf>(children) } /// Removes the relationship between this entity and the given entity. #[deprecated = "Use detach_child() instead"] pub fn remove_child(&mut self, child: Entity) -> &mut Self { self.detach_child(child) } /// Removes the parent-child relationship between this entity and the given entity. /// Does not despawn the child. pub fn detach_child(&mut self, child: Entity) -> &mut Self { self.remove_related::<ChildOf>(&[child]) } /// Replaces all the related children with a new set of children. pub fn replace_children(&mut self, children: &[Entity]) -> &mut Self { self.replace_related::<ChildOf>(children) } /// Replaces all the related children with a new set of children. /// /// # Warning /// /// Failing to maintain the functions invariants may lead to erratic engine behavior including random crashes. /// Refer to [`Self::replace_related_with_difference`] for a list of these invariants. /// /// # Panics /// /// Panics when debug assertions are enabled if an invariant is broken and the command is executed. pub fn replace_children_with_difference( &mut self, entities_to_unrelate: &[Entity], entities_to_relate: &[Entity], newly_related_entities: &[Entity], ) -> &mut Self { self.replace_related_with_difference::<ChildOf>( entities_to_unrelate, entities_to_relate, newly_related_entities, ) } /// Spawns the passed bundle and adds it to this entity as a child. /// /// For efficient spawning of multiple children, use [`with_children`]. /// /// [`with_children`]: EntityWorldMut::with_children pub fn with_child(&mut self, bundle: impl Bundle) -> &mut Self { let parent = self.id(); self.world_scope(|world| { world.spawn((bundle, ChildOf(parent))); }); self } } impl<'a> EntityCommands<'a> { /// Spawns children of this entity (with a [`ChildOf`] relationship) by taking a function that operates on a [`ChildSpawner`]. pub fn with_children( &mut self, func: impl FnOnce(&mut RelatedSpawnerCommands<ChildOf>), ) -> &mut Self { self.with_related_entities(func); self } /// Adds the given children to this entity. pub fn add_children(&mut self, children: &[Entity]) -> &mut Self { self.add_related::<ChildOf>(children) } /// Removes all the children from this entity. /// See also [`detach_all_related`](Self::detach_all_related) #[deprecated = "Use detach_all_children() instead"] pub fn clear_children(&mut self) -> &mut Self { self.detach_all_children() } /// Removes all the parent-child relationships from this entity. /// To despawn the child entities, instead use [`EntityWorldMut::despawn_children`](EntityWorldMut::despawn_children). /// See also [`detach_all_related`](Self::detach_all_related) pub fn detach_all_children(&mut self) -> &mut Self { self.detach_all_related::<ChildOf>() } /// Insert children at specific index. /// See also [`insert_related`](Self::insert_related). pub fn insert_children(&mut self, index: usize, children: &[Entity]) -> &mut Self { self.insert_related::<ChildOf>(index, children) } /// Insert children at specific index. /// See also [`insert_related`](Self::insert_related). pub fn insert_child(&mut self, index: usize, child: Entity) -> &mut Self { self.insert_related::<ChildOf>(index, &[child]) } /// Adds the given child to this entity. pub fn add_child(&mut self, child: Entity) -> &mut Self { self.add_related::<ChildOf>(&[child]) } /// Removes the relationship between this entity and the given entities. #[deprecated = "Use detach_children() instead"] pub fn remove_children(&mut self, children: &[Entity]) -> &mut Self { self.detach_children(children) } /// Removes the parent-child relationship between this entity and the given entities. /// Does not despawn the children. pub fn detach_children(&mut self, children: &[Entity]) -> &mut Self { self.remove_related::<ChildOf>(children) } /// Removes the relationship between this entity and the given entity. #[deprecated = "Use detach_child() instead"] pub fn remove_child(&mut self, child: Entity) -> &mut Self { self.detach_child(child) } /// Removes the parent-child relationship between this entity and the given entity. /// Does not despawn the child. pub fn detach_child(&mut self, child: Entity) -> &mut Self { self.remove_related::<ChildOf>(&[child]) } /// Replaces the children on this entity with a new list of children. pub fn replace_children(&mut self, children: &[Entity]) -> &mut Self { self.replace_related::<ChildOf>(children) } /// Replaces all the related entities with a new set of entities. /// /// # Warning /// /// Failing to maintain the functions invariants may lead to erratic engine behavior including random crashes. /// Refer to [`EntityWorldMut::replace_related_with_difference`] for a list of these invariants. /// /// # Panics /// /// Panics when debug assertions are enabled if an invariant is broken and the command is executed. pub fn replace_children_with_difference( &mut self, entities_to_unrelate: &[Entity], entities_to_relate: &[Entity], newly_related_entities: &[Entity], ) -> &mut Self { self.replace_related_with_difference::<ChildOf>( entities_to_unrelate, entities_to_relate, newly_related_entities, ) } /// Spawns the passed bundle and adds it to this entity as a child. /// /// For efficient spawning of multiple children, use [`with_children`]. /// /// [`with_children`]: EntityCommands::with_children pub fn with_child(&mut self, bundle: impl Bundle) -> &mut Self { self.with_related::<ChildOf>(bundle); self } } /// An `on_insert` component hook that when run, will validate that the parent of a given entity /// contains component `C`. This will print a warning if the parent does not contain `C`. pub fn validate_parent_has_component<C: Component>( world: DeferredWorld, HookContext { entity, caller, .. }: HookContext, ) { let entity_ref = world.entity(entity); let Some(child_of) = entity_ref.get::<ChildOf>() else { return; }; let parent = child_of.parent(); let maybe_parent_ref = world.get_entity(parent); if let Ok(parent_ref) = maybe_parent_ref && !parent_ref.contains::<C>() { let name = entity_ref.get::<Name>(); let debug_name = DebugName::type_name::<C>(); let parent_name = parent_ref.get::<Name>(); warn!( "warning[B0004]: {}{name} with the {ty_name} component has a parent ({parent_name}) without {ty_name}.\n\ This will cause inconsistent behaviors! See: https://bevy.org/learn/errors/b0004", caller.map(|c| format!("{c}: ")).unwrap_or_default(), ty_name = debug_name.shortname(), name = name.map_or_else( || format!("Entity {entity}"), |s| format!("The {s} entity") ), parent_name = parent_name.map_or_else( || format!("{parent} entity"), |s| format!("the {s} entity") ), ); } } /// Returns a [`SpawnRelatedBundle`] that will insert the [`Children`] component, spawn a [`SpawnableList`] of entities with given bundles that /// relate to the [`Children`] entity via the [`ChildOf`] component, and reserve space in the [`Children`] for each spawned entity. /// /// Any additional arguments will be interpreted as bundles to be spawned. /// /// Also see [`related`](crate::related) for a version of this that works with any [`RelationshipTarget`] type. /// /// ``` /// # use bevy_ecs::hierarchy::Children; /// # use bevy_ecs::name::Name; /// # use bevy_ecs::world::World; /// # use bevy_ecs::children; /// # use bevy_ecs::spawn::{Spawn, SpawnRelated}; /// let mut world = World::new(); /// world.spawn(( /// Name::new("Root"), /// children![ /// Name::new("Child1"), /// ( /// Name::new("Child2"), /// children![Name::new("Grandchild")] /// ) /// ] /// )); /// ``` /// /// [`RelationshipTarget`]: crate::relationship::RelationshipTarget /// [`SpawnRelatedBundle`]: crate::spawn::SpawnRelatedBundle /// [`SpawnableList`]: crate::spawn::SpawnableList #[macro_export] macro_rules! children { [$($child:expr),*$(,)?] => { $crate::hierarchy::Children::spawn($crate::recursive_spawn!($($child),*)) }; } #[cfg(test)] mod tests { use crate::{ entity::Entity, hierarchy::{ChildOf, Children}, relationship::{RelationshipHookMode, RelationshipTarget}, spawn::{Spawn, SpawnRelated}, world::World, }; use alloc::{vec, vec::Vec}; #[derive(PartialEq, Eq, Debug)] struct Node { entity: Entity, children: Vec<Node>, } impl Node { fn new(entity: Entity) -> Self { Self { entity, children: Vec::new(), } } fn new_with(entity: Entity, children: Vec<Node>) -> Self { Self { entity, children } } } fn get_hierarchy(world: &World, entity: Entity) -> Node { Node { entity, children: world .entity(entity) .get::<Children>() .map_or_else(Default::default, |c| { c.iter().map(|e| get_hierarchy(world, e)).collect() }), } } #[test] fn hierarchy() { let mut world = World::new(); let root = world.spawn_empty().id(); let child1 = world.spawn(ChildOf(root)).id(); let grandchild = world.spawn(ChildOf(child1)).id(); let child2 = world.spawn(ChildOf(root)).id(); // Spawn let hierarchy = get_hierarchy(&world, root); assert_eq!( hierarchy, Node::new_with( root, vec![ Node::new_with(child1, vec![Node::new(grandchild)]), Node::new(child2) ] ) ); // Removal world.entity_mut(child1).remove::<ChildOf>(); let hierarchy = get_hierarchy(&world, root); assert_eq!(hierarchy, Node::new_with(root, vec![Node::new(child2)])); // Insert world.entity_mut(child1).insert(ChildOf(root)); let hierarchy = get_hierarchy(&world, root); assert_eq!( hierarchy, Node::new_with( root, vec![ Node::new(child2), Node::new_with(child1, vec![Node::new(grandchild)]) ] ) ); // Recursive Despawn world.entity_mut(root).despawn(); assert!(world.get_entity(root).is_err()); assert!(world.get_entity(child1).is_err()); assert!(world.get_entity(child2).is_err()); assert!(world.get_entity(grandchild).is_err()); } #[test] fn with_children() { let mut world = World::new(); let mut child1 = Entity::PLACEHOLDER; let mut child2 = Entity::PLACEHOLDER; let root = world .spawn_empty() .with_children(|p| { child1 = p.spawn_empty().id(); child2 = p.spawn_empty().id(); }) .id(); let hierarchy = get_hierarchy(&world, root); assert_eq!( hierarchy, Node::new_with(root, vec![Node::new(child1), Node::new(child2)]) ); } #[test] fn add_children() { let mut world = World::new(); let child1 = world.spawn_empty().id(); let child2 = world.spawn_empty().id(); let root = world.spawn_empty().add_children(&[child1, child2]).id(); let hierarchy = get_hierarchy(&world, root); assert_eq!( hierarchy, Node::new_with(root, vec![Node::new(child1), Node::new(child2)]) ); } #[test] fn insert_children() { let mut world = World::new(); let child1 = world.spawn_empty().id(); let child2 = world.spawn_empty().id(); let child3 = world.spawn_empty().id(); let child4 = world.spawn_empty().id(); let mut entity_world_mut = world.spawn_empty(); let first_children = entity_world_mut.add_children(&[child1, child2]); let root = first_children.insert_children(1, &[child3, child4]).id(); let hierarchy = get_hierarchy(&world, root); assert_eq!( hierarchy, Node::new_with( root, vec![ Node::new(child1), Node::new(child3), Node::new(child4), Node::new(child2) ] ) ); } #[test] fn insert_child() { let mut world = World::new(); let child1 = world.spawn_empty().id(); let child2 = world.spawn_empty().id(); let child3 = world.spawn_empty().id(); let mut entity_world_mut = world.spawn_empty(); let first_children = entity_world_mut.add_children(&[child1, child2]); let root = first_children.insert_child(1, child3).id(); let hierarchy = get_hierarchy(&world, root); assert_eq!( hierarchy, Node::new_with( root, vec![Node::new(child1), Node::new(child3), Node::new(child2)] ) ); } // regression test for https://github.com/bevyengine/bevy/pull/19134 #[test] fn insert_children_index_bound() { let mut world = World::new(); let child1 = world.spawn_empty().id(); let child2 = world.spawn_empty().id(); let child3 = world.spawn_empty().id(); let child4 = world.spawn_empty().id(); let mut entity_world_mut = world.spawn_empty(); let first_children = entity_world_mut.add_children(&[child1, child2]).id(); let hierarchy = get_hierarchy(&world, first_children); assert_eq!( hierarchy, Node::new_with(first_children, vec![Node::new(child1), Node::new(child2)]) ); let root = world .entity_mut(first_children) .insert_children(usize::MAX, &[child3, child4]) .id(); let hierarchy = get_hierarchy(&world, root); assert_eq!( hierarchy, Node::new_with( root, vec![ Node::new(child1), Node::new(child2), Node::new(child3), Node::new(child4), ] ) ); } #[test] fn detach_children() { let mut world = World::new(); let child1 = world.spawn_empty().id(); let child2 = world.spawn_empty().id(); let child3 = world.spawn_empty().id(); let child4 = world.spawn_empty().id(); let mut root = world.spawn_empty(); root.add_children(&[child1, child2, child3, child4]); root.detach_children(&[child2, child3]); let root = root.id(); let hierarchy = get_hierarchy(&world, root); assert_eq!( hierarchy, Node::new_with(root, vec![Node::new(child1), Node::new(child4)]) ); } #[test] fn detach_child() { let mut world = World::new(); let child1 = world.spawn_empty().id(); let child2 = world.spawn_empty().id(); let child3 = world.spawn_empty().id(); let mut root = world.spawn_empty(); root.add_children(&[child1, child2, child3]); root.detach_child(child2); let root = root.id(); let hierarchy = get_hierarchy(&world, root); assert_eq!( hierarchy, Node::new_with(root, vec![Node::new(child1), Node::new(child3)]) ); } #[test] fn self_parenting_invalid() { let mut world = World::new(); let id = world.spawn_empty().id(); world.entity_mut(id).insert(ChildOf(id)); assert!( world.entity(id).get::<ChildOf>().is_none(), "invalid ChildOf relationships should self-remove" ); } #[test] fn missing_parent_invalid() { let mut world = World::new(); let parent = world.spawn_empty().id(); world.entity_mut(parent).despawn(); let id = world.spawn(ChildOf(parent)).id(); assert!( world.entity(id).get::<ChildOf>().is_none(), "invalid ChildOf relationships should self-remove" ); } #[test] fn reinsert_same_parent() { let mut world = World::new(); let parent = world.spawn_empty().id(); let id = world.spawn(ChildOf(parent)).id(); world.entity_mut(id).insert(ChildOf(parent)); assert_eq!( Some(&ChildOf(parent)), world.entity(id).get::<ChildOf>(), "ChildOf should still be there" ); } #[test] fn spawn_children() { let mut world = World::new(); let id = world.spawn(Children::spawn((Spawn(()), Spawn(())))).id(); assert_eq!(world.entity(id).get::<Children>().unwrap().len(), 2,); } #[test] fn spawn_many_children() { let mut world = World::new(); // ensure an empty set can be mentioned world.spawn(children![]); // 12 children should result in a flat tuple let id = world .spawn(children![(), (), (), (), (), (), (), (), (), (), (), ()]) .id(); assert_eq!(world.entity(id).get::<Children>().unwrap().len(), 12,); // 13 will start nesting, but should nonetheless produce a flat hierarchy let id = world .spawn(children![ (), (), (), (), (), (), (), (), (), (), (), (), (), ]) .id(); assert_eq!(world.entity(id).get::<Children>().unwrap().len(), 13,); } #[test] fn replace_children() { let mut world = World::new(); let parent = world.spawn(Children::spawn((Spawn(()), Spawn(())))).id(); let &[child_a, child_b] = &world.entity(parent).get::<Children>().unwrap().0[..] else { panic!("Tried to spawn 2 children on an entity and didn't get 2 children"); }; let child_c = world.spawn_empty().id(); world .entity_mut(parent) .replace_children(&[child_a, child_c]); let children = world.entity(parent).get::<Children>().unwrap(); assert!(children.contains(&child_a)); assert!(children.contains(&child_c)); assert!(!children.contains(&child_b)); assert_eq!( world.entity(child_a).get::<ChildOf>().unwrap(), &ChildOf(parent) ); assert_eq!( world.entity(child_c).get::<ChildOf>().unwrap(), &ChildOf(parent) ); assert!(world.entity(child_b).get::<ChildOf>().is_none()); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/never.rs
crates/bevy_ecs/src/never.rs
//! A workaround for the `!` type in stable Rust. //! //! This approach is taken from the [`never_say_never`] crate, //! reimplemented here to avoid adding a new dependency. //! //! This module exists due to a change in [never type fallback inference] in the Rust 2024 edition. //! This caused failures in `bevy_ecs`'s traits which are implemented for functions //! (like [`System`](crate::system::System)) when working with panicking closures. //! //! Note that using this hack is not recommended in general; //! by doing so you are knowingly opting out of rustc's stability guarantees. //! Code that compiles due to this hack may break in future versions of Rust. //! //! Please read [issue #18778](https://github.com/bevyengine/bevy/issues/18778) for an explanation of why //! Bevy has chosen to use this workaround. //! //! [`never_say_never`]: https://crates.io/crates/never_say_never //! [never type fallback inference]: https://doc.rust-lang.org/edition-guide/rust-2024/never-type-fallback.html mod fn_ret { /// A helper trait for naming the ! type. #[doc(hidden)] pub trait FnRet { /// The return type of the function. type Output; } /// This blanket implementation allows us to name the never type, /// by using the associated type of this trait for `fn() -> !`. impl<R> FnRet for fn() -> R { type Output = R; } } /// A hacky type alias for the `!` (never) type. /// /// This knowingly opts out of rustc's stability guarantees. /// Read the module documentation carefully before using this! pub type Never = <fn() -> ! as fn_ret::FnRet>::Output;
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/spawn.rs
crates/bevy_ecs/src/spawn.rs
//! Entity spawning abstractions, largely focused on spawning related hierarchies of entities. See [`related`](crate::related) and [`SpawnRelated`] //! for the best entry points into these APIs and examples of how to use them. use crate::{ bundle::{Bundle, DynamicBundle, InsertMode, NoBundleEffect}, change_detection::MaybeLocation, entity::Entity, relationship::{RelatedSpawner, Relationship, RelationshipHookMode, RelationshipTarget}, world::{EntityWorldMut, World}, }; use alloc::vec::Vec; use bevy_ptr::{move_as_ptr, MovingPtr}; use core::{ marker::PhantomData, mem::{self, MaybeUninit}, }; use variadics_please::all_tuples_enumerated; /// A wrapper over a [`Bundle`] indicating that an entity should be spawned with that [`Bundle`]. /// This is intended to be used for hierarchical spawning via traits like [`SpawnableList`] and [`SpawnRelated`]. /// /// Also see the [`children`](crate::children) and [`related`](crate::related) macros that abstract over the [`Spawn`] API. /// /// ``` /// # use bevy_ecs::hierarchy::Children; /// # use bevy_ecs::spawn::{Spawn, SpawnRelated}; /// # use bevy_ecs::name::Name; /// # use bevy_ecs::world::World; /// let mut world = World::new(); /// world.spawn(( /// Name::new("Root"), /// Children::spawn(( /// Spawn(Name::new("Child1")), /// Spawn(( /// Name::new("Child2"), /// Children::spawn(Spawn(Name::new("Grandchild"))), /// )) /// )), /// )); /// ``` pub struct Spawn<B: Bundle>(pub B); /// A spawn-able list of changes to a given [`World`] and relative to a given [`Entity`]. This is generally used /// for spawning "related" entities, such as children. pub trait SpawnableList<R>: Sized { /// Spawn this list of changes in a given [`World`] and relative to a given [`Entity`]. This is generally used /// for spawning "related" entities, such as children. // This function explicitly uses `MovingPtr` to avoid potentially large stack copies of the bundle // when inserting into ECS storage. See https://github.com/bevyengine/bevy/issues/20571 for more // information. fn spawn(this: MovingPtr<'_, Self>, world: &mut World, entity: Entity); /// Returns a size hint, which is used to reserve space for this list in a [`RelationshipTarget`]. This should be /// less than or equal to the actual size of the list. When in doubt, just use 0. fn size_hint(&self) -> usize; } impl<R: Relationship, B: Bundle<Effect: NoBundleEffect>> SpawnableList<R> for Vec<B> { fn spawn(ptr: MovingPtr<'_, Self>, world: &mut World, entity: Entity) { let mapped_bundles = ptr.read().into_iter().map(|b| (R::from(entity), b)); world.spawn_batch(mapped_bundles); } fn size_hint(&self) -> usize { self.len() } } impl<R: Relationship, B: Bundle> SpawnableList<R> for Spawn<B> { fn spawn(this: MovingPtr<'_, Self>, world: &mut World, entity: Entity) { #[track_caller] fn spawn<B: Bundle, R: Relationship>( this: MovingPtr<'_, Spawn<B>>, world: &mut World, entity: Entity, ) { let caller = MaybeLocation::caller(); bevy_ptr::deconstruct_moving_ptr!({ let Spawn { 0: bundle } = this; }); let r = R::from(entity); move_as_ptr!(r); let mut entity = world.spawn_with_caller(r, caller); entity.insert_with_caller( bundle, InsertMode::Replace, caller, RelationshipHookMode::Run, ); } spawn::<B, R>(this, world, entity); } fn size_hint(&self) -> usize { 1 } } /// A [`SpawnableList`] that spawns entities using an iterator of a given [`Bundle`]: /// /// ``` /// # use bevy_ecs::hierarchy::Children; /// # use bevy_ecs::spawn::{Spawn, SpawnIter, SpawnRelated}; /// # use bevy_ecs::name::Name; /// # use bevy_ecs::world::World; /// let mut world = World::new(); /// world.spawn(( /// Name::new("Root"), /// Children::spawn(( /// Spawn(Name::new("Child1")), /// SpawnIter(["Child2", "Child3"].into_iter().map(Name::new)), /// )), /// )); /// ``` pub struct SpawnIter<I>(pub I); impl<R: Relationship, I: Iterator<Item = B> + Send + Sync + 'static, B: Bundle> SpawnableList<R> for SpawnIter<I> { fn spawn(mut this: MovingPtr<'_, Self>, world: &mut World, entity: Entity) { for bundle in &mut this.0 { world.spawn((R::from(entity), bundle)); } } fn size_hint(&self) -> usize { self.0.size_hint().0 } } /// A [`SpawnableList`] that spawns entities using a [`FnOnce`] with a [`RelatedSpawner`] as an argument: /// /// ``` /// # use bevy_ecs::hierarchy::{Children, ChildOf}; /// # use bevy_ecs::spawn::{Spawn, SpawnWith, SpawnRelated}; /// # use bevy_ecs::name::Name; /// # use bevy_ecs::relationship::RelatedSpawner; /// # use bevy_ecs::world::World; /// let mut world = World::new(); /// world.spawn(( /// Name::new("Root"), /// Children::spawn(( /// Spawn(Name::new("Child1")), /// SpawnWith(|parent: &mut RelatedSpawner<ChildOf>| { /// parent.spawn(Name::new("Child2")); /// parent.spawn(Name::new("Child3")); /// }), /// )), /// )); /// ``` pub struct SpawnWith<F>(pub F); impl<R: Relationship, F: FnOnce(&mut RelatedSpawner<R>) + Send + Sync + 'static> SpawnableList<R> for SpawnWith<F> { fn spawn(this: MovingPtr<'_, Self>, world: &mut World, entity: Entity) { world .entity_mut(entity) .with_related_entities(this.read().0); } fn size_hint(&self) -> usize { 1 } } /// A [`SpawnableList`] that links already spawned entities to the root entity via relations of type `I`. /// /// This is useful if the entity has already been spawned earlier or if you spawn multiple relationships link to the same entity at the same time. /// If you only need to do this for a single entity, consider using [`WithOneRelated`]. /// /// ``` /// # use bevy_ecs::hierarchy::Children; /// # use bevy_ecs::spawn::{Spawn, WithRelated, SpawnRelated}; /// # use bevy_ecs::name::Name; /// # use bevy_ecs::world::World; /// let mut world = World::new(); /// /// let child2 = world.spawn(Name::new("Child2")).id(); /// let child3 = world.spawn(Name::new("Child3")).id(); /// /// world.spawn(( /// Name::new("Root"), /// Children::spawn(( /// Spawn(Name::new("Child1")), /// // This adds the already existing entities as children of Root. /// WithRelated::new([child2, child3]), /// )), /// )); /// ``` pub struct WithRelated<I>(pub I); impl<I> WithRelated<I> { /// Creates a new [`WithRelated`] from a collection of entities. pub fn new(iter: impl IntoIterator<IntoIter = I>) -> Self { Self(iter.into_iter()) } } impl<R: Relationship, I: Iterator<Item = Entity>> SpawnableList<R> for WithRelated<I> { fn spawn(mut this: MovingPtr<'_, Self>, world: &mut World, entity: Entity) { let related = (&mut this.0).collect::<Vec<_>>(); world.entity_mut(entity).add_related::<R>(&related); } fn size_hint(&self) -> usize { self.0.size_hint().0 } } /// A wrapper over an [`Entity`] indicating that an entity should be added. /// This is intended to be used for hierarchical spawning via traits like [`SpawnableList`] and [`SpawnRelated`]. /// /// Unlike [`WithRelated`] this only adds one entity. /// /// Also see the [`children`](crate::children) and [`related`](crate::related) macros that abstract over the [`Spawn`] API. /// /// ``` /// # use bevy_ecs::hierarchy::Children; /// # use bevy_ecs::spawn::{Spawn, WithOneRelated, SpawnRelated}; /// # use bevy_ecs::name::Name; /// # use bevy_ecs::world::World; /// let mut world = World::new(); /// /// let child1 = world.spawn(Name::new("Child1")).id(); /// /// world.spawn(( /// Name::new("Root"), /// Children::spawn(( /// // This adds the already existing entity as a child of Root. /// WithOneRelated(child1), /// )), /// )); /// ``` pub struct WithOneRelated(pub Entity); impl<R: Relationship> SpawnableList<R> for WithOneRelated { fn spawn(this: MovingPtr<'_, Self>, world: &mut World, entity: Entity) { world.entity_mut(entity).add_one_related::<R>(this.read().0); } fn size_hint(&self) -> usize { 1 } } macro_rules! spawnable_list_impl { ($(#[$meta:meta])* $(($index:tt, $list: ident, $alias: ident)),*) => { $(#[$meta])* impl<R: Relationship, $($list: SpawnableList<R>),*> SpawnableList<R> for ($($list,)*) { #[expect( clippy::allow_attributes, reason = "This is a tuple-related macro; as such, the lints below may not always apply." )] #[allow(unused_unsafe, reason = "The empty tuple will leave the unsafe blocks unused.")] fn spawn(_this: MovingPtr<'_, Self>, _world: &mut World, _entity: Entity) where Self: Sized, { bevy_ptr::deconstruct_moving_ptr!({ let tuple { $($index: $alias),* } = _this; }); $( SpawnableList::<R>::spawn($alias, _world, _entity); )* } fn size_hint(&self) -> usize { let ($($alias,)*) = self; 0 $(+ $alias.size_hint())* } } } } all_tuples_enumerated!( #[doc(fake_variadic)] spawnable_list_impl, 0, 12, P, field_ ); /// A [`Bundle`] that: /// 1. Contains a [`RelationshipTarget`] component (associated with the given [`Relationship`]). This reserves space for the [`SpawnableList`]. /// 2. Spawns a [`SpawnableList`] of related entities with a given [`Relationship`]. /// /// This is intended to be created using [`SpawnRelated`]. pub struct SpawnRelatedBundle<R: Relationship, L: SpawnableList<R>> { list: L, marker: PhantomData<R>, } // SAFETY: This internally relies on the RelationshipTarget's Bundle implementation, which is sound. unsafe impl<R: Relationship, L: SpawnableList<R> + Send + Sync + 'static> Bundle for SpawnRelatedBundle<R, L> { fn component_ids( components: &mut crate::component::ComponentsRegistrator, ) -> impl Iterator<Item = crate::component::ComponentId> + use<R, L> { <R::RelationshipTarget as Bundle>::component_ids(components) } fn get_component_ids( components: &crate::component::Components, ) -> impl Iterator<Item = Option<crate::component::ComponentId>> { <R::RelationshipTarget as Bundle>::get_component_ids(components) } } impl<R: Relationship, L: SpawnableList<R>> DynamicBundle for SpawnRelatedBundle<R, L> { type Effect = Self; unsafe fn get_components( ptr: MovingPtr<'_, Self>, func: &mut impl FnMut(crate::component::StorageType, bevy_ptr::OwningPtr<'_>), ) { let target = <R::RelationshipTarget as RelationshipTarget>::with_capacity(ptr.list.size_hint()); move_as_ptr!(target); // SAFETY: // - The caller must ensure that this is called exactly once before `apply_effect`. // - Assuming `DynamicBundle` is implemented correctly for `R::Relationship` target, `func` should be // called exactly once for each component being fetched with the correct `StorageType` // - `Effect: !NoBundleEffect`, which means the caller is responsible for calling this type's `apply_effect` // at least once before returning to safe code. unsafe { <R::RelationshipTarget as DynamicBundle>::get_components(target, func) }; // Forget the pointer so that the value is available in `apply_effect`. mem::forget(ptr); } unsafe fn apply_effect(ptr: MovingPtr<'_, MaybeUninit<Self>>, entity: &mut EntityWorldMut) { // SAFETY: The value was not moved out in `get_components`, only borrowed, and thus should still // be valid and initialized. let effect = unsafe { ptr.assume_init() }; let id = entity.id(); entity.world_scope(|world: &mut World| { bevy_ptr::deconstruct_moving_ptr!({ let Self { list, marker: _ } = effect; }); L::spawn(list, world, id); }); } } /// A [`Bundle`] that: /// 1. Contains a [`RelationshipTarget`] component (associated with the given [`Relationship`]). This reserves space for a single entity. /// 2. Spawns a single related entity containing the given `B` [`Bundle`] and the given [`Relationship`]. /// /// This is intended to be created using [`SpawnRelated`]. pub struct SpawnOneRelated<R: Relationship, B: Bundle> { bundle: B, marker: PhantomData<R>, } impl<R: Relationship, B: Bundle> DynamicBundle for SpawnOneRelated<R, B> { type Effect = Self; unsafe fn get_components( ptr: MovingPtr<'_, Self>, func: &mut impl FnMut(crate::component::StorageType, bevy_ptr::OwningPtr<'_>), ) { let target = <R::RelationshipTarget as RelationshipTarget>::with_capacity(1); move_as_ptr!(target); // SAFETY: // - The caller must ensure that this is called exactly once before `apply_effect`. // - Assuming `DynamicBundle` is implemented correctly for `R::Relationship` target, `func` should be // called exactly once for each component being fetched with the correct `StorageType` // - `Effect: !NoBundleEffect`, which means the caller is responsible for calling this type's `apply_effect` // at least once before returning to safe code. unsafe { <R::RelationshipTarget as DynamicBundle>::get_components(target, func) }; // Forget the pointer so that the value is available in `apply_effect`. mem::forget(ptr); } unsafe fn apply_effect(ptr: MovingPtr<'_, MaybeUninit<Self>>, entity: &mut EntityWorldMut) { // SAFETY: The value was not moved out in `get_components`, only borrowed, and thus should still // be valid and initialized. let effect = unsafe { ptr.assume_init() }; let effect = effect.read(); entity.with_related::<R>(effect.bundle); } } // SAFETY: This internally relies on the RelationshipTarget's Bundle implementation, which is sound. unsafe impl<R: Relationship, B: Bundle> Bundle for SpawnOneRelated<R, B> { fn component_ids( components: &mut crate::component::ComponentsRegistrator, ) -> impl Iterator<Item = crate::component::ComponentId> + use<R, B> { <R::RelationshipTarget as Bundle>::component_ids(components) } fn get_component_ids( components: &crate::component::Components, ) -> impl Iterator<Item = Option<crate::component::ComponentId>> { <R::RelationshipTarget as Bundle>::get_component_ids(components) } } /// [`RelationshipTarget`] methods that create a [`Bundle`] with a [`DynamicBundle::Effect`] that: /// /// 1. Contains the [`RelationshipTarget`] component, pre-allocated with the necessary space for spawned entities. /// 2. Spawns an entity (or a list of entities) that relate to the entity the [`Bundle`] is added to via the [`RelationshipTarget::Relationship`]. pub trait SpawnRelated: RelationshipTarget { /// Returns a [`Bundle`] containing this [`RelationshipTarget`] component. It also spawns a [`SpawnableList`] of entities, each related to the bundle's entity /// via [`RelationshipTarget::Relationship`]. The [`RelationshipTarget`] (when possible) will pre-allocate space for the related entities. /// /// See [`Spawn`], [`SpawnIter`], [`SpawnWith`], [`WithRelated`] and [`WithOneRelated`] for usage examples. fn spawn<L: SpawnableList<Self::Relationship>>( list: L, ) -> SpawnRelatedBundle<Self::Relationship, L>; /// Returns a [`Bundle`] containing this [`RelationshipTarget`] component. It also spawns a single entity containing [`Bundle`] that is related to the bundle's entity /// via [`RelationshipTarget::Relationship`]. /// /// ``` /// # use bevy_ecs::hierarchy::Children; /// # use bevy_ecs::spawn::SpawnRelated; /// # use bevy_ecs::name::Name; /// # use bevy_ecs::world::World; /// let mut world = World::new(); /// world.spawn(( /// Name::new("Root"), /// Children::spawn_one(Name::new("Child")), /// )); /// ``` fn spawn_one<B: Bundle>(bundle: B) -> SpawnOneRelated<Self::Relationship, B>; } impl<T: RelationshipTarget> SpawnRelated for T { fn spawn<L: SpawnableList<Self::Relationship>>( list: L, ) -> SpawnRelatedBundle<Self::Relationship, L> { SpawnRelatedBundle { list, marker: PhantomData, } } fn spawn_one<B: Bundle>(bundle: B) -> SpawnOneRelated<Self::Relationship, B> { SpawnOneRelated { bundle, marker: PhantomData, } } } /// Returns a [`SpawnRelatedBundle`] that will insert the given [`RelationshipTarget`], spawn a [`SpawnableList`] of entities with given bundles that /// relate to the [`RelationshipTarget`] entity via the [`RelationshipTarget::Relationship`] component, and reserve space in the [`RelationshipTarget`] for each spawned entity. /// /// The first argument is the [`RelationshipTarget`] type. Any additional arguments will be interpreted as bundles to be spawned. /// /// Also see [`children`](crate::children) for a [`Children`](crate::hierarchy::Children)-specific equivalent. /// /// ``` /// # use bevy_ecs::hierarchy::Children; /// # use bevy_ecs::name::Name; /// # use bevy_ecs::world::World; /// # use bevy_ecs::related; /// let mut world = World::new(); /// world.spawn(( /// Name::new("Root"), /// related!(Children[ /// Name::new("Child1"), /// ( /// Name::new("Child2"), /// related!(Children[ /// Name::new("Grandchild"), /// ]) /// ) /// ]) /// )); /// ``` #[macro_export] macro_rules! related { ($relationship_target:ty [$($child:expr),*$(,)?]) => { <$relationship_target as $crate::spawn::SpawnRelated>::spawn($crate::recursive_spawn!($($child),*)) }; } // A tail-recursive spawn utility. // // Since `SpawnableList` is only implemented for tuples // up to twelve elements long, this macro will nest // longer sequences recursively. By default, this recursion // will top out at around 1400 elements, but it would be // ill-advised to spawn that many entities with this method. // // For spawning large batches of entities at a time, // consider `SpawnIter` or eagerly spawning with `Commands`. #[macro_export] #[doc(hidden)] macro_rules! recursive_spawn { // direct expansion () => { () }; ($a:expr) => { $crate::spawn::Spawn($a) }; ($a:expr, $b:expr) => { ( $crate::spawn::Spawn($a), $crate::spawn::Spawn($b), ) }; ($a:expr, $b:expr, $c:expr) => { ( $crate::spawn::Spawn($a), $crate::spawn::Spawn($b), $crate::spawn::Spawn($c), ) }; ($a:expr, $b:expr, $c:expr, $d:expr) => { ( $crate::spawn::Spawn($a), $crate::spawn::Spawn($b), $crate::spawn::Spawn($c), $crate::spawn::Spawn($d), ) }; ($a:expr, $b:expr, $c:expr, $d:expr, $e:expr) => { ( $crate::spawn::Spawn($a), $crate::spawn::Spawn($b), $crate::spawn::Spawn($c), $crate::spawn::Spawn($d), $crate::spawn::Spawn($e), ) }; ($a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr) => { ( $crate::spawn::Spawn($a), $crate::spawn::Spawn($b), $crate::spawn::Spawn($c), $crate::spawn::Spawn($d), $crate::spawn::Spawn($e), $crate::spawn::Spawn($f), ) }; ($a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr, $g:expr) => { ( $crate::spawn::Spawn($a), $crate::spawn::Spawn($b), $crate::spawn::Spawn($c), $crate::spawn::Spawn($d), $crate::spawn::Spawn($e), $crate::spawn::Spawn($f), $crate::spawn::Spawn($g), ) }; ($a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr, $g:expr, $h:expr) => { ( $crate::spawn::Spawn($a), $crate::spawn::Spawn($b), $crate::spawn::Spawn($c), $crate::spawn::Spawn($d), $crate::spawn::Spawn($e), $crate::spawn::Spawn($f), $crate::spawn::Spawn($g), $crate::spawn::Spawn($h), ) }; ($a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr, $g:expr, $h:expr, $i:expr) => { ( $crate::spawn::Spawn($a), $crate::spawn::Spawn($b), $crate::spawn::Spawn($c), $crate::spawn::Spawn($d), $crate::spawn::Spawn($e), $crate::spawn::Spawn($f), $crate::spawn::Spawn($g), $crate::spawn::Spawn($h), $crate::spawn::Spawn($i), ) }; ($a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr, $g:expr, $h:expr, $i:expr, $j:expr) => { ( $crate::spawn::Spawn($a), $crate::spawn::Spawn($b), $crate::spawn::Spawn($c), $crate::spawn::Spawn($d), $crate::spawn::Spawn($e), $crate::spawn::Spawn($f), $crate::spawn::Spawn($g), $crate::spawn::Spawn($h), $crate::spawn::Spawn($i), $crate::spawn::Spawn($j), ) }; ($a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr, $g:expr, $h:expr, $i:expr, $j:expr, $k:expr) => { ( $crate::spawn::Spawn($a), $crate::spawn::Spawn($b), $crate::spawn::Spawn($c), $crate::spawn::Spawn($d), $crate::spawn::Spawn($e), $crate::spawn::Spawn($f), $crate::spawn::Spawn($g), $crate::spawn::Spawn($h), $crate::spawn::Spawn($i), $crate::spawn::Spawn($j), $crate::spawn::Spawn($k), ) }; // recursive expansion ( $a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr, $g:expr, $h:expr, $i:expr, $j:expr, $k:expr, $($rest:expr),* ) => { ( $crate::spawn::Spawn($a), $crate::spawn::Spawn($b), $crate::spawn::Spawn($c), $crate::spawn::Spawn($d), $crate::spawn::Spawn($e), $crate::spawn::Spawn($f), $crate::spawn::Spawn($g), $crate::spawn::Spawn($h), $crate::spawn::Spawn($i), $crate::spawn::Spawn($j), $crate::spawn::Spawn($k), $crate::recursive_spawn!($($rest),*) ) }; } #[cfg(test)] mod tests { use crate::{ name::Name, prelude::{ChildOf, Children, RelationshipTarget}, relationship::RelatedSpawner, world::World, }; use super::{Spawn, SpawnIter, SpawnRelated, SpawnWith, WithOneRelated, WithRelated}; #[test] fn spawn() { let mut world = World::new(); let parent = world .spawn(( Name::new("Parent"), Children::spawn(Spawn(Name::new("Child1"))), )) .id(); let children = world .query::<&Children>() .get(&world, parent) .expect("An entity with Children should exist"); assert_eq!(children.iter().count(), 1); for ChildOf(child) in world.query::<&ChildOf>().iter(&world) { assert_eq!(child, &parent); } } #[test] fn spawn_iter() { let mut world = World::new(); let parent = world .spawn(( Name::new("Parent"), Children::spawn(SpawnIter(["Child1", "Child2"].into_iter().map(Name::new))), )) .id(); let children = world .query::<&Children>() .get(&world, parent) .expect("An entity with Children should exist"); assert_eq!(children.iter().count(), 2); for ChildOf(child) in world.query::<&ChildOf>().iter(&world) { assert_eq!(child, &parent); } } #[test] fn spawn_with() { let mut world = World::new(); let parent = world .spawn(( Name::new("Parent"), Children::spawn(SpawnWith(|parent: &mut RelatedSpawner<ChildOf>| { parent.spawn(Name::new("Child1")); })), )) .id(); let children = world .query::<&Children>() .get(&world, parent) .expect("An entity with Children should exist"); assert_eq!(children.iter().count(), 1); for ChildOf(child) in world.query::<&ChildOf>().iter(&world) { assert_eq!(child, &parent); } } #[test] fn with_related() { let mut world = World::new(); let child1 = world.spawn(Name::new("Child1")).id(); let child2 = world.spawn(Name::new("Child2")).id(); let parent = world .spawn(( Name::new("Parent"), Children::spawn(WithRelated::new([child1, child2])), )) .id(); let children = world .query::<&Children>() .get(&world, parent) .expect("An entity with Children should exist"); assert_eq!(children.iter().count(), 2); assert_eq!( world.entity(child1).get::<ChildOf>(), Some(&ChildOf(parent)) ); assert_eq!( world.entity(child2).get::<ChildOf>(), Some(&ChildOf(parent)) ); } #[test] fn with_one_related() { let mut world = World::new(); let child1 = world.spawn(Name::new("Child1")).id(); let parent = world .spawn((Name::new("Parent"), Children::spawn(WithOneRelated(child1)))) .id(); let children = world .query::<&Children>() .get(&world, parent) .expect("An entity with Children should exist"); assert_eq!(children.iter().count(), 1); assert_eq!( world.entity(child1).get::<ChildOf>(), Some(&ChildOf(parent)) ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/lifecycle.rs
crates/bevy_ecs/src/lifecycle.rs
//! This module contains various tools to allow you to react to component insertion or removal, //! as well as entity spawning and despawning. //! //! There are four main ways to react to these lifecycle events: //! //! 1. Using component hooks, which act as inherent constructors and destructors for components. //! 2. Using [observers], which are a user-extensible way to respond to events, including component lifecycle events. //! 3. Using the [`RemovedComponents`] system parameter, which offers an event-style interface. //! 4. Using the [`Added`] query filter, which checks each component to see if it has been added since the last time a system ran. //! //! [observers]: crate::observer //! [`Added`]: crate::query::Added //! //! # Types of lifecycle events //! //! There are five types of lifecycle events, split into two categories. First, we have lifecycle events that are triggered //! when a component is added to an entity: //! //! - [`Add`]: Triggered when a component is added to an entity that did not already have it. //! - [`Insert`]: Triggered when a component is added to an entity, regardless of whether it already had it. //! //! When both events occur, [`Add`] hooks are evaluated before [`Insert`]. //! //! Next, we have lifecycle events that are triggered when a component is removed from an entity: //! //! - [`Replace`]: Triggered when a component is removed from an entity, regardless if it is then replaced with a new value. //! - [`Remove`]: Triggered when a component is removed from an entity and not replaced, before the component is removed. //! - [`Despawn`]: Triggered for each component on an entity when it is despawned. //! //! [`Replace`] hooks are evaluated before [`Remove`], then finally [`Despawn`] hooks are evaluated. //! //! [`Add`] and [`Remove`] are counterparts: they are only triggered when a component is added or removed //! from an entity in such a way as to cause a change in the component's presence on that entity. //! Similarly, [`Insert`] and [`Replace`] are counterparts: they are triggered when a component is added or replaced //! on an entity, regardless of whether this results in a change in the component's presence on that entity. //! //! To reliably synchronize data structures using with component lifecycle events, //! you can combine [`Insert`] and [`Replace`] to fully capture any changes to the data. //! This is particularly useful in combination with immutable components, //! to avoid any lifecycle-bypassing mutations. //! //! ## Lifecycle events and component types //! //! Despite the absence of generics, each lifecycle event is associated with a specific component. //! When defining a component hook for a [`Component`] type, that component is used. //! When observers watch lifecycle events, the `B: Bundle` generic is used. //! //! Each of these lifecycle events also corresponds to a fixed [`ComponentId`], //! which are assigned during [`World`] initialization. //! For example, [`Add`] corresponds to [`ADD`]. //! This is used to skip [`TypeId`](core::any::TypeId) lookups in hot paths. use crate::{ change_detection::{MaybeLocation, Tick}, component::{Component, ComponentId, ComponentIdFor}, entity::Entity, event::{EntityComponentsTrigger, EntityEvent, EventKey}, message::{ Message, MessageCursor, MessageId, MessageIterator, MessageIteratorWithId, Messages, }, query::FilteredAccessSet, relationship::RelationshipHookMode, storage::SparseSet, system::{Local, ReadOnlySystemParam, SystemMeta, SystemParam}, world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, World}, }; use derive_more::derive::Into; #[cfg(feature = "bevy_reflect")] use bevy_reflect::Reflect; use core::{ fmt::Debug, iter, marker::PhantomData, ops::{Deref, DerefMut}, option, }; /// The type used for [`Component`] lifecycle hooks such as `on_add`, `on_insert` or `on_remove`. pub type ComponentHook = for<'w> fn(DeferredWorld<'w>, HookContext); /// Context provided to a [`ComponentHook`]. #[derive(Clone, Copy, Debug)] pub struct HookContext { /// The [`Entity`] this hook was invoked for. pub entity: Entity, /// The [`ComponentId`] this hook was invoked for. pub component_id: ComponentId, /// The caller location is `Some` if the `track_caller` feature is enabled. pub caller: MaybeLocation, /// Configures how relationship hooks will run pub relationship_hook_mode: RelationshipHookMode, } /// [`World`]-mutating functions that run as part of lifecycle events of a [`Component`]. /// /// Hooks are functions that run when a component is added, overwritten, or removed from an entity. /// These are intended to be used for structural side effects that need to happen when a component is added or removed, /// and are not intended for general-purpose logic. /// /// For example, you might use a hook to update a cached index when a component is added, /// to clean up resources when a component is removed, /// or to keep hierarchical data structures across entities in sync. /// /// This information is stored in the [`ComponentInfo`](crate::component::ComponentInfo) of the associated component. /// /// There are two ways of configuring hooks for a component: /// 1. Defining the relevant hooks on the [`Component`] implementation /// 2. Using the [`World::register_component_hooks`] method /// /// # Example /// /// ``` /// use bevy_ecs::prelude::*; /// use bevy_platform::collections::HashSet; /// /// #[derive(Component)] /// struct MyTrackedComponent; /// /// #[derive(Resource, Default)] /// struct TrackedEntities(HashSet<Entity>); /// /// let mut world = World::new(); /// world.init_resource::<TrackedEntities>(); /// /// // No entities with `MyTrackedComponent` have been added yet, so we can safely add component hooks /// let mut tracked_component_query = world.query::<&MyTrackedComponent>(); /// assert!(tracked_component_query.iter(&world).next().is_none()); /// /// world.register_component_hooks::<MyTrackedComponent>().on_add(|mut world, context| { /// let mut tracked_entities = world.resource_mut::<TrackedEntities>(); /// tracked_entities.0.insert(context.entity); /// }); /// /// world.register_component_hooks::<MyTrackedComponent>().on_remove(|mut world, context| { /// let mut tracked_entities = world.resource_mut::<TrackedEntities>(); /// tracked_entities.0.remove(&context.entity); /// }); /// /// let entity = world.spawn(MyTrackedComponent).id(); /// let tracked_entities = world.resource::<TrackedEntities>(); /// assert!(tracked_entities.0.contains(&entity)); /// /// world.despawn(entity); /// let tracked_entities = world.resource::<TrackedEntities>(); /// assert!(!tracked_entities.0.contains(&entity)); /// ``` #[derive(Debug, Clone, Default)] pub struct ComponentHooks { pub(crate) on_add: Option<ComponentHook>, pub(crate) on_insert: Option<ComponentHook>, pub(crate) on_replace: Option<ComponentHook>, pub(crate) on_remove: Option<ComponentHook>, pub(crate) on_despawn: Option<ComponentHook>, } impl ComponentHooks { pub(crate) fn update_from_component<C: Component + ?Sized>(&mut self) -> &mut Self { if let Some(hook) = C::on_add() { self.on_add(hook); } if let Some(hook) = C::on_insert() { self.on_insert(hook); } if let Some(hook) = C::on_replace() { self.on_replace(hook); } if let Some(hook) = C::on_remove() { self.on_remove(hook); } if let Some(hook) = C::on_despawn() { self.on_despawn(hook); } self } /// Register a [`ComponentHook`] that will be run when this component is added to an entity. /// An `on_add` hook will always run before `on_insert` hooks. Spawning an entity counts as /// adding all of its components. /// /// # Panics /// /// Will panic if the component already has an `on_add` hook pub fn on_add(&mut self, hook: ComponentHook) -> &mut Self { self.try_on_add(hook) .expect("Component already has an on_add hook") } /// Register a [`ComponentHook`] that will be run when this component is added (with `.insert`) /// or replaced. /// /// An `on_insert` hook always runs after any `on_add` hooks (if the entity didn't already have the component). /// /// # Warning /// /// The hook won't run if the component is already present and is only mutated, such as in a system via a query. /// As a result, this needs to be combined with immutable components to serve as a mechanism for reliably updating indexes and other caches. /// /// # Panics /// /// Will panic if the component already has an `on_insert` hook pub fn on_insert(&mut self, hook: ComponentHook) -> &mut Self { self.try_on_insert(hook) .expect("Component already has an on_insert hook") } /// Register a [`ComponentHook`] that will be run when this component is about to be dropped, /// such as being replaced (with `.insert`) or removed. /// /// If this component is inserted onto an entity that already has it, this hook will run before the value is replaced, /// allowing access to the previous data just before it is dropped. /// This hook does *not* run if the entity did not already have this component. /// /// An `on_replace` hook always runs before any `on_remove` hooks (if the component is being removed from the entity). /// /// # Warning /// /// The hook won't run if the component is already present and is only mutated, such as in a system via a query. /// As a result, this needs to be combined with immutable components to serve as a mechanism for reliably updating indexes and other caches. /// /// # Panics /// /// Will panic if the component already has an `on_replace` hook pub fn on_replace(&mut self, hook: ComponentHook) -> &mut Self { self.try_on_replace(hook) .expect("Component already has an on_replace hook") } /// Register a [`ComponentHook`] that will be run when this component is removed from an entity. /// Despawning an entity counts as removing all of its components. /// /// # Panics /// /// Will panic if the component already has an `on_remove` hook pub fn on_remove(&mut self, hook: ComponentHook) -> &mut Self { self.try_on_remove(hook) .expect("Component already has an on_remove hook") } /// Register a [`ComponentHook`] that will be run for each component on an entity when it is despawned. /// /// # Panics /// /// Will panic if the component already has an `on_despawn` hook pub fn on_despawn(&mut self, hook: ComponentHook) -> &mut Self { self.try_on_despawn(hook) .expect("Component already has an on_despawn hook") } /// Attempt to register a [`ComponentHook`] that will be run when this component is added to an entity. /// /// This is a fallible version of [`Self::on_add`]. /// /// Returns `None` if the component already has an `on_add` hook. pub fn try_on_add(&mut self, hook: ComponentHook) -> Option<&mut Self> { if self.on_add.is_some() { return None; } self.on_add = Some(hook); Some(self) } /// Attempt to register a [`ComponentHook`] that will be run when this component is added (with `.insert`) /// /// This is a fallible version of [`Self::on_insert`]. /// /// Returns `None` if the component already has an `on_insert` hook. pub fn try_on_insert(&mut self, hook: ComponentHook) -> Option<&mut Self> { if self.on_insert.is_some() { return None; } self.on_insert = Some(hook); Some(self) } /// Attempt to register a [`ComponentHook`] that will be run when this component is replaced (with `.insert`) or removed /// /// This is a fallible version of [`Self::on_replace`]. /// /// Returns `None` if the component already has an `on_replace` hook. pub fn try_on_replace(&mut self, hook: ComponentHook) -> Option<&mut Self> { if self.on_replace.is_some() { return None; } self.on_replace = Some(hook); Some(self) } /// Attempt to register a [`ComponentHook`] that will be run when this component is removed from an entity. /// /// This is a fallible version of [`Self::on_remove`]. /// /// Returns `None` if the component already has an `on_remove` hook. pub fn try_on_remove(&mut self, hook: ComponentHook) -> Option<&mut Self> { if self.on_remove.is_some() { return None; } self.on_remove = Some(hook); Some(self) } /// Attempt to register a [`ComponentHook`] that will be run for each component on an entity when it is despawned. /// /// This is a fallible version of [`Self::on_despawn`]. /// /// Returns `None` if the component already has an `on_despawn` hook. pub fn try_on_despawn(&mut self, hook: ComponentHook) -> Option<&mut Self> { if self.on_despawn.is_some() { return None; } self.on_despawn = Some(hook); Some(self) } } /// [`EventKey`] for [`Add`] pub const ADD: EventKey = EventKey(ComponentId::new(0)); /// [`EventKey`] for [`Insert`] pub const INSERT: EventKey = EventKey(ComponentId::new(1)); /// [`EventKey`] for [`Replace`] pub const REPLACE: EventKey = EventKey(ComponentId::new(2)); /// [`EventKey`] for [`Remove`] pub const REMOVE: EventKey = EventKey(ComponentId::new(3)); /// [`EventKey`] for [`Despawn`] pub const DESPAWN: EventKey = EventKey(ComponentId::new(4)); /// Trigger emitted when a component is inserted onto an entity that does not already have that /// component. Runs before `Insert`. /// See [`ComponentHooks::on_add`](`crate::lifecycle::ComponentHooks::on_add`) for more information. #[derive(Debug, Clone, EntityEvent)] #[entity_event(trigger = EntityComponentsTrigger<'a>)] #[cfg_attr(feature = "bevy_reflect", derive(Reflect))] #[cfg_attr(feature = "bevy_reflect", reflect(Debug))] #[doc(alias = "OnAdd")] pub struct Add { /// The entity this component was added to. pub entity: Entity, } /// Trigger emitted when a component is inserted, regardless of whether or not the entity already /// had that component. Runs after `Add`, if it ran. /// See [`ComponentHooks::on_insert`](`crate::lifecycle::ComponentHooks::on_insert`) for more information. #[derive(Debug, Clone, EntityEvent)] #[entity_event(trigger = EntityComponentsTrigger<'a>)] #[cfg_attr(feature = "bevy_reflect", derive(Reflect))] #[cfg_attr(feature = "bevy_reflect", reflect(Debug))] #[doc(alias = "OnInsert")] pub struct Insert { /// The entity this component was inserted into. pub entity: Entity, } /// Trigger emitted when a component is removed from an entity, regardless /// of whether or not it is later replaced. /// /// Runs before the value is replaced, so you can still access the original component data. /// See [`ComponentHooks::on_replace`](`crate::lifecycle::ComponentHooks::on_replace`) for more information. #[derive(Debug, Clone, EntityEvent)] #[entity_event(trigger = EntityComponentsTrigger<'a>)] #[cfg_attr(feature = "bevy_reflect", derive(Reflect))] #[cfg_attr(feature = "bevy_reflect", reflect(Debug))] #[doc(alias = "OnReplace")] pub struct Replace { /// The entity that held this component before it was replaced. pub entity: Entity, } /// Trigger emitted when a component is removed from an entity, and runs before the component is /// removed, so you can still access the component data. /// See [`ComponentHooks::on_remove`](`crate::lifecycle::ComponentHooks::on_remove`) for more information. #[derive(Debug, Clone, EntityEvent)] #[entity_event(trigger = EntityComponentsTrigger<'a>)] #[cfg_attr(feature = "bevy_reflect", derive(Reflect))] #[cfg_attr(feature = "bevy_reflect", reflect(Debug))] #[doc(alias = "OnRemove")] pub struct Remove { /// The entity this component was removed from. pub entity: Entity, } /// [`EntityEvent`] emitted for each component on an entity when it is despawned. /// See [`ComponentHooks::on_despawn`](`crate::lifecycle::ComponentHooks::on_despawn`) for more information. #[derive(Debug, Clone, EntityEvent)] #[entity_event(trigger = EntityComponentsTrigger<'a>)] #[cfg_attr(feature = "bevy_reflect", derive(Reflect))] #[cfg_attr(feature = "bevy_reflect", reflect(Debug))] #[doc(alias = "OnDespawn")] pub struct Despawn { /// The entity that held this component before it was despawned. pub entity: Entity, } /// Wrapper around [`Entity`] for [`RemovedComponents`]. /// Internally, `RemovedComponents` uses these as an [`Messages<RemovedComponentEntity>`]. #[derive(Message, Debug, Clone, Into)] #[cfg_attr(feature = "bevy_reflect", derive(Reflect))] #[cfg_attr(feature = "bevy_reflect", reflect(Debug, Clone))] pub struct RemovedComponentEntity(Entity); /// Wrapper around a [`MessageCursor<RemovedComponentEntity>`] so that we /// can differentiate messages between components. #[derive(Debug)] pub struct RemovedComponentReader<T> where T: Component, { reader: MessageCursor<RemovedComponentEntity>, marker: PhantomData<T>, } impl<T: Component> Default for RemovedComponentReader<T> { fn default() -> Self { Self { reader: Default::default(), marker: PhantomData, } } } impl<T: Component> Deref for RemovedComponentReader<T> { type Target = MessageCursor<RemovedComponentEntity>; fn deref(&self) -> &Self::Target { &self.reader } } impl<T: Component> DerefMut for RemovedComponentReader<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.reader } } /// Stores the [`RemovedComponents`] event buffers for all types of component in a given [`World`]. #[derive(Default, Debug)] pub struct RemovedComponentMessages { event_sets: SparseSet<ComponentId, Messages<RemovedComponentEntity>>, } impl RemovedComponentMessages { /// Creates an empty storage buffer for component removal messages. pub fn new() -> Self { Self::default() } /// For each type of component, swaps the event buffers and clears the oldest event buffer. /// In general, this should be called once per frame/update. pub fn update(&mut self) { for (_component_id, messages) in self.event_sets.iter_mut() { messages.update(); } } /// Returns an iterator over components and their entity messages. pub fn iter(&self) -> impl Iterator<Item = (&ComponentId, &Messages<RemovedComponentEntity>)> { self.event_sets.iter() } /// Gets the event storage for a given component. pub fn get( &self, component_id: impl Into<ComponentId>, ) -> Option<&Messages<RemovedComponentEntity>> { self.event_sets.get(component_id.into()) } /// Writes a removal message for the specified component. pub fn write(&mut self, component_id: impl Into<ComponentId>, entity: Entity) { self.event_sets .get_or_insert_with(component_id.into(), Default::default) .write(RemovedComponentEntity(entity)); } } /// A [`SystemParam`] that yields entities that had their `T` [`Component`] /// removed or have been despawned with it. /// /// This acts effectively the same as a [`MessageReader`](crate::message::MessageReader). /// /// Unlike hooks or observers (see the [lifecycle](crate) module docs), /// this does not allow you to see which data existed before removal. /// /// If you are using `bevy_ecs` as a standalone crate, /// note that the [`RemovedComponents`] list will not be automatically cleared for you, /// and will need to be manually flushed using [`World::clear_trackers`](World::clear_trackers). /// /// For users of `bevy` and `bevy_app`, [`World::clear_trackers`](World::clear_trackers) is /// automatically called by `bevy_app::App::update` and `bevy_app::SubApp::update`. /// For the main world, this is delayed until after all `SubApp`s have run. /// /// # Examples /// /// Basic usage: /// /// ``` /// # use bevy_ecs::component::Component; /// # use bevy_ecs::system::IntoSystem; /// # use bevy_ecs::lifecycle::RemovedComponents; /// # /// # #[derive(Component)] /// # struct MyComponent; /// fn react_on_removal(mut removed: RemovedComponents<MyComponent>) { /// removed.read().for_each(|removed_entity| println!("{}", removed_entity)); /// } /// # bevy_ecs::system::assert_is_system(react_on_removal); /// ``` #[derive(SystemParam)] pub struct RemovedComponents<'w, 's, T: Component> { component_id: ComponentIdFor<'s, T>, reader: Local<'s, RemovedComponentReader<T>>, message_sets: &'w RemovedComponentMessages, } /// Iterator over entities that had a specific component removed. /// /// See [`RemovedComponents`]. pub type RemovedIter<'a> = iter::Map< iter::Flatten<option::IntoIter<iter::Cloned<MessageIterator<'a, RemovedComponentEntity>>>>, fn(RemovedComponentEntity) -> Entity, >; /// Iterator over entities that had a specific component removed. /// /// See [`RemovedComponents`]. pub type RemovedIterWithId<'a> = iter::Map< iter::Flatten<option::IntoIter<MessageIteratorWithId<'a, RemovedComponentEntity>>>, fn( (&RemovedComponentEntity, MessageId<RemovedComponentEntity>), ) -> (Entity, MessageId<RemovedComponentEntity>), >; fn map_id_messages( (entity, id): (&RemovedComponentEntity, MessageId<RemovedComponentEntity>), ) -> (Entity, MessageId<RemovedComponentEntity>) { (entity.clone().into(), id) } // For all practical purposes, the api surface of `RemovedComponents<T>` // should be similar to `MessageReader<T>` to reduce confusion. impl<'w, 's, T: Component> RemovedComponents<'w, 's, T> { /// Fetch underlying [`MessageCursor`]. pub fn reader(&self) -> &MessageCursor<RemovedComponentEntity> { &self.reader } /// Fetch underlying [`MessageCursor`] mutably. pub fn reader_mut(&mut self) -> &mut MessageCursor<RemovedComponentEntity> { &mut self.reader } /// Fetch underlying [`Messages`]. pub fn messages(&self) -> Option<&Messages<RemovedComponentEntity>> { self.message_sets.get(self.component_id.get()) } /// Destructures to get a mutable reference to the `MessageCursor` /// and a reference to `Messages`. /// /// This is necessary since Rust can't detect destructuring through methods and most /// usecases of the reader uses the `Messages` as well. pub fn reader_mut_with_messages( &mut self, ) -> Option<( &mut RemovedComponentReader<T>, &Messages<RemovedComponentEntity>, )> { self.message_sets .get(self.component_id.get()) .map(|messages| (&mut *self.reader, messages)) } /// Iterates over the messages this [`RemovedComponents`] has not seen yet. This updates the /// [`RemovedComponents`]'s message counter, which means subsequent message reads will not include messages /// that happened before now. pub fn read(&mut self) -> RemovedIter<'_> { self.reader_mut_with_messages() .map(|(reader, messages)| reader.read(messages).cloned()) .into_iter() .flatten() .map(RemovedComponentEntity::into) } /// Like [`read`](Self::read), except also returning the [`MessageId`] of the messages. pub fn read_with_id(&mut self) -> RemovedIterWithId<'_> { self.reader_mut_with_messages() .map(|(reader, messages)| reader.read_with_id(messages)) .into_iter() .flatten() .map(map_id_messages) } /// Determines the number of removal messages available to be read from this [`RemovedComponents`] without consuming any. pub fn len(&self) -> usize { self.messages() .map(|messages| self.reader.len(messages)) .unwrap_or(0) } /// Returns `true` if there are no messages available to read. pub fn is_empty(&self) -> bool { self.messages() .is_none_or(|messages| self.reader.is_empty(messages)) } /// Consumes all available messages. /// /// This means these messages will not appear in calls to [`RemovedComponents::read()`] or /// [`RemovedComponents::read_with_id()`] and [`RemovedComponents::is_empty()`] will return `true`. pub fn clear(&mut self) { if let Some((reader, messages)) = self.reader_mut_with_messages() { reader.clear(messages); } } } // SAFETY: Only reads World removed component messages unsafe impl<'a> ReadOnlySystemParam for &'a RemovedComponentMessages {} // SAFETY: no component value access. unsafe impl<'a> SystemParam for &'a RemovedComponentMessages { type State = (); type Item<'w, 's> = &'w RemovedComponentMessages; fn init_state(_world: &mut World) -> Self::State {} fn init_access( _state: &Self::State, _system_meta: &mut SystemMeta, _component_access_set: &mut FilteredAccessSet, _world: &mut World, ) { } #[inline] unsafe fn get_param<'w, 's>( _state: &'s mut Self::State, _system_meta: &SystemMeta, world: UnsafeWorldCell<'w>, _change_tick: Tick, ) -> Self::Item<'w, 's> { world.removed_components() } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/archetype.rs
crates/bevy_ecs/src/archetype.rs
//! Types for defining [`Archetype`]s, collections of entities that have the same set of //! components. //! //! An archetype uniquely describes a group of entities that share the same components: //! a world only has one archetype for each unique combination of components, and all //! entities that have those components and only those components belong to that //! archetype. //! //! Archetypes are not to be confused with [`Table`]s. Each archetype stores its table //! components in one table, and each archetype uniquely points to one table, but multiple //! archetypes may store their table components in the same table. These archetypes //! differ only by the [`SparseSet`] components. //! //! Like tables, archetypes can be created but are never cleaned up. Empty archetypes are //! not removed, and persist until the world is dropped. //! //! Archetypes can be fetched from [`Archetypes`], which is accessible via [`World::archetypes`]. //! //! [`Table`]: crate::storage::Table //! [`World::archetypes`]: crate::world::World::archetypes use crate::{ bundle::BundleId, component::{ComponentId, Components, RequiredComponentConstructor, StorageType}, entity::{Entity, EntityLocation}, event::Event, observer::Observers, query::DebugCheckedUnwrap, storage::{ImmutableSparseSet, SparseArray, SparseSet, TableId, TableRow}, }; use alloc::{boxed::Box, vec::Vec}; use bevy_platform::collections::{hash_map::Entry, HashMap}; use core::{ hash::Hash, ops::{Index, IndexMut, RangeFrom}, }; use nonmax::NonMaxU32; #[derive(Event)] #[expect(dead_code, reason = "Prepare for the upcoming Query as Entities")] pub(crate) struct ArchetypeCreated(pub ArchetypeId); /// An opaque location within a [`Archetype`]. /// /// This can be used in conjunction with [`ArchetypeId`] to find the exact location /// of an [`Entity`] within a [`World`]. An entity's archetype and index can be /// retrieved via [`Entities::get`]. /// /// [`World`]: crate::world::World /// [`Entities::get`]: crate::entity::Entities #[derive(Debug, Copy, Clone, Eq, PartialEq)] // SAFETY: Must be repr(transparent) due to the safety requirements on EntityLocation #[repr(transparent)] pub struct ArchetypeRow(NonMaxU32); impl ArchetypeRow { /// Creates a `ArchetypeRow`. #[inline] pub const fn new(index: NonMaxU32) -> Self { Self(index) } /// Gets the index of the row. #[inline] pub const fn index(self) -> usize { self.0.get() as usize } /// Gets the index of the row. #[inline] pub const fn index_u32(self) -> u32 { self.0.get() } } /// An opaque unique ID for a single [`Archetype`] within a [`World`]. /// /// Archetype IDs are only valid for a given World, and are not globally unique. /// Attempting to use an archetype ID on a world that it wasn't sourced from will /// not return the archetype with the same components. The only exception to this is /// [`EMPTY`] which is guaranteed to be identical for all Worlds. /// /// [`World`]: crate::world::World /// [`EMPTY`]: ArchetypeId::EMPTY #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)] // SAFETY: Must be repr(transparent) due to the safety requirements on EntityLocation #[repr(transparent)] pub struct ArchetypeId(u32); impl ArchetypeId { /// The ID for the [`Archetype`] without any components. pub const EMPTY: ArchetypeId = ArchetypeId(0); /// Create an `ArchetypeId` from a plain value. /// /// This is useful if you need to store the `ArchetypeId` as a plain value, /// for example in a specialized data structure such as a bitset. /// /// While it doesn't break any safety invariants, you should ensure the /// values comes from a pre-existing [`ArchetypeId::index`] in this world /// to avoid panics and other unexpected behaviors. #[inline] pub const fn new(index: usize) -> Self { ArchetypeId(index as u32) } /// The plain value of this `ArchetypeId`. /// /// In bevy, this is mostly used to store archetype ids in [`FixedBitSet`]s. /// /// [`FixedBitSet`]: fixedbitset::FixedBitSet #[inline] pub fn index(self) -> usize { self.0 as usize } } /// Used in [`ArchetypeAfterBundleInsert`] to track whether components in the bundle are newly /// added or already existed in the entity's archetype. #[derive(Copy, Clone, Eq, PartialEq)] pub(crate) enum ComponentStatus { Added, Existing, } /// Used in [`Edges`] to cache the result of inserting a bundle into the source archetype. pub(crate) struct ArchetypeAfterBundleInsert { /// The target archetype after the bundle is inserted into the source archetype. pub archetype_id: ArchetypeId, /// For each component iterated in the same order as the source [`Bundle`](crate::bundle::Bundle), /// indicate if the component is newly added to the target archetype or if it already existed. bundle_status: Box<[ComponentStatus]>, /// The set of additional required components that must be initialized immediately when adding this Bundle. /// /// The initial values are determined based on the provided constructor, falling back to the `Default` trait if none is given. pub required_components: Box<[RequiredComponentConstructor]>, /// The components inserted by this bundle, with added components before existing ones. /// Added components includes any Required Components that are inserted when adding this bundle, /// but existing components only includes ones explicitly contributed by this bundle. inserted: Box<[ComponentId]>, /// The number of components added by this bundle, including Required Components. added_len: usize, } impl ArchetypeAfterBundleInsert { pub(crate) fn inserted(&self) -> &[ComponentId] { &self.inserted } pub(crate) fn added(&self) -> &[ComponentId] { // SAFETY: `added_len` is always in range `0..=inserted.len()` unsafe { self.inserted.get(..self.added_len).debug_checked_unwrap() } } pub(crate) fn existing(&self) -> &[ComponentId] { // SAFETY: `added_len` is always in range `0..=inserted.len()` unsafe { self.inserted.get(self.added_len..).debug_checked_unwrap() } } } /// This trait is used to report the status of [`Bundle`](crate::bundle::Bundle) components /// being inserted into a given entity, relative to that entity's original archetype. /// See [`BundleInfo::write_components`](`crate::bundle::BundleInfo::write_components`) for more info. pub(crate) trait BundleComponentStatus { /// Returns the Bundle's component status for the given "bundle index". /// /// # Safety /// Callers must ensure that index is always a valid bundle index for the /// Bundle associated with this [`BundleComponentStatus`] unsafe fn get_status(&self, index: usize) -> ComponentStatus; } impl BundleComponentStatus for ArchetypeAfterBundleInsert { #[inline] unsafe fn get_status(&self, index: usize) -> ComponentStatus { // SAFETY: caller has ensured index is a valid bundle index for this bundle unsafe { *self.bundle_status.get_unchecked(index) } } } pub(crate) struct SpawnBundleStatus; impl BundleComponentStatus for SpawnBundleStatus { #[inline] unsafe fn get_status(&self, _index: usize) -> ComponentStatus { // Components inserted during a spawn call are always treated as added. ComponentStatus::Added } } /// Archetypes and bundles form a graph. Adding or removing a bundle moves /// an [`Entity`] to a new [`Archetype`]. /// /// [`Edges`] caches the results of these moves. Each archetype caches /// the result of a structural alteration. This can be used to monitor the /// state of the archetype graph. /// /// Note: This type only contains edges the [`World`] has already traversed. /// If any of functions return `None`, it doesn't mean there is guaranteed /// not to be a result of adding or removing that bundle, but rather that /// operation that has moved an entity along that edge has not been performed /// yet. /// /// [`World`]: crate::world::World #[derive(Default)] pub struct Edges { insert_bundle: SparseArray<BundleId, ArchetypeAfterBundleInsert>, remove_bundle: SparseArray<BundleId, Option<ArchetypeId>>, take_bundle: SparseArray<BundleId, Option<ArchetypeId>>, } impl Edges { /// Checks the cache for the target archetype when inserting a bundle into the /// source archetype. /// /// If this returns `None`, it means there has not been a transition from /// the source archetype via the provided bundle. #[inline] pub fn get_archetype_after_bundle_insert(&self, bundle_id: BundleId) -> Option<ArchetypeId> { self.get_archetype_after_bundle_insert_internal(bundle_id) .map(|bundle| bundle.archetype_id) } /// Internal version of `get_archetype_after_bundle_insert` that /// fetches the full `ArchetypeAfterBundleInsert`. #[inline] pub(crate) fn get_archetype_after_bundle_insert_internal( &self, bundle_id: BundleId, ) -> Option<&ArchetypeAfterBundleInsert> { self.insert_bundle.get(bundle_id) } /// Caches the target archetype when inserting a bundle into the source archetype. #[inline] pub(crate) fn cache_archetype_after_bundle_insert( &mut self, bundle_id: BundleId, archetype_id: ArchetypeId, bundle_status: impl Into<Box<[ComponentStatus]>>, required_components: impl Into<Box<[RequiredComponentConstructor]>>, mut added: Vec<ComponentId>, existing: Vec<ComponentId>, ) { let added_len = added.len(); // Make sure `extend` doesn't over-reserve, since the conversion to `Box<[_]>` would reallocate to shrink. added.reserve_exact(existing.len()); added.extend(existing); self.insert_bundle.insert( bundle_id, ArchetypeAfterBundleInsert { archetype_id, bundle_status: bundle_status.into(), required_components: required_components.into(), added_len, inserted: added.into(), }, ); } /// Checks the cache for the target archetype when removing a bundle from the /// source archetype. /// /// If this returns `None`, it means there has not been a transition from /// the source archetype via the provided bundle. /// /// If this returns `Some(None)`, it means that the bundle cannot be removed /// from the source archetype. #[inline] pub fn get_archetype_after_bundle_remove( &self, bundle_id: BundleId, ) -> Option<Option<ArchetypeId>> { self.remove_bundle.get(bundle_id).cloned() } /// Caches the target archetype when removing a bundle from the source archetype. #[inline] pub(crate) fn cache_archetype_after_bundle_remove( &mut self, bundle_id: BundleId, archetype_id: Option<ArchetypeId>, ) { self.remove_bundle.insert(bundle_id, archetype_id); } /// Checks the cache for the target archetype when taking a bundle from the /// source archetype. /// /// Unlike `remove`, `take` will only succeed if the source archetype /// contains all of the components in the bundle. /// /// If this returns `None`, it means there has not been a transition from /// the source archetype via the provided bundle. /// /// If this returns `Some(None)`, it means that the bundle cannot be taken /// from the source archetype. #[inline] pub fn get_archetype_after_bundle_take( &self, bundle_id: BundleId, ) -> Option<Option<ArchetypeId>> { self.take_bundle.get(bundle_id).cloned() } /// Caches the target archetype when taking a bundle from the source archetype. /// /// Unlike `remove`, `take` will only succeed if the source archetype /// contains all of the components in the bundle. #[inline] pub(crate) fn cache_archetype_after_bundle_take( &mut self, bundle_id: BundleId, archetype_id: Option<ArchetypeId>, ) { self.take_bundle.insert(bundle_id, archetype_id); } } /// Metadata about an [`Entity`] in a [`Archetype`]. pub struct ArchetypeEntity { entity: Entity, table_row: TableRow, } impl ArchetypeEntity { /// The ID of the entity. #[inline] pub const fn id(&self) -> Entity { self.entity } /// The row in the [`Table`] where the entity's components are stored. /// /// [`Table`]: crate::storage::Table #[inline] pub const fn table_row(&self) -> TableRow { self.table_row } } /// Internal metadata for an [`Entity`] getting removed from an [`Archetype`]. pub(crate) struct ArchetypeSwapRemoveResult { /// If the [`Entity`] was not the last in the [`Archetype`], it gets removed by swapping it out /// with the last entity in the archetype. In that case, this field contains the swapped entity. pub(crate) swapped_entity: Option<Entity>, /// The [`TableRow`] where the removed entity's components are stored. pub(crate) table_row: TableRow, } /// Internal metadata for a [`Component`] within a given [`Archetype`]. /// /// [`Component`]: crate::component::Component struct ArchetypeComponentInfo { storage_type: StorageType, } bitflags::bitflags! { /// Flags used to keep track of metadata about the component in this [`Archetype`] /// /// Used primarily to early-out when there are no [`ComponentHook`] registered for any contained components. #[derive(Clone, Copy)] pub(crate) struct ArchetypeFlags: u32 { const ON_ADD_HOOK = (1 << 0); const ON_INSERT_HOOK = (1 << 1); const ON_REPLACE_HOOK = (1 << 2); const ON_REMOVE_HOOK = (1 << 3); const ON_DESPAWN_HOOK = (1 << 4); const ON_ADD_OBSERVER = (1 << 5); const ON_INSERT_OBSERVER = (1 << 6); const ON_REPLACE_OBSERVER = (1 << 7); const ON_REMOVE_OBSERVER = (1 << 8); const ON_DESPAWN_OBSERVER = (1 << 9); } } /// Metadata for a single archetype within a [`World`]. /// /// For more information, see the *[module level documentation]*. /// /// [`World`]: crate::world::World /// [module level documentation]: crate::archetype pub struct Archetype { id: ArchetypeId, table_id: TableId, edges: Edges, entities: Vec<ArchetypeEntity>, components: ImmutableSparseSet<ComponentId, ArchetypeComponentInfo>, pub(crate) flags: ArchetypeFlags, } impl Archetype { /// `table_components` and `sparse_set_components` must be sorted pub(crate) fn new( components: &Components, component_index: &mut ComponentIndex, observers: &Observers, id: ArchetypeId, table_id: TableId, table_components: impl Iterator<Item = ComponentId>, sparse_set_components: impl Iterator<Item = ComponentId>, ) -> Self { let (min_table, _) = table_components.size_hint(); let (min_sparse, _) = sparse_set_components.size_hint(); let mut flags = ArchetypeFlags::empty(); let mut archetype_components = SparseSet::with_capacity(min_table + min_sparse); for (idx, component_id) in table_components.enumerate() { // SAFETY: We are creating an archetype that includes this component so it must exist let info = unsafe { components.get_info_unchecked(component_id) }; info.update_archetype_flags(&mut flags); observers.update_archetype_flags(component_id, &mut flags); archetype_components.insert( component_id, ArchetypeComponentInfo { storage_type: StorageType::Table, }, ); // NOTE: the `table_components` are sorted AND they were inserted in the `Table` in the same // sorted order, so the index of the `Column` in the `Table` is the same as the index of the // component in the `table_components` vector component_index .entry(component_id) .or_default() .insert(id, ArchetypeRecord { column: Some(idx) }); } for component_id in sparse_set_components { // SAFETY: We are creating an archetype that includes this component so it must exist let info = unsafe { components.get_info_unchecked(component_id) }; info.update_archetype_flags(&mut flags); observers.update_archetype_flags(component_id, &mut flags); archetype_components.insert( component_id, ArchetypeComponentInfo { storage_type: StorageType::SparseSet, }, ); component_index .entry(component_id) .or_default() .insert(id, ArchetypeRecord { column: None }); } Self { id, table_id, entities: Vec::new(), components: archetype_components.into_immutable(), edges: Default::default(), flags, } } /// Fetches the ID for the archetype. #[inline] pub fn id(&self) -> ArchetypeId { self.id } /// Fetches the flags for the archetype. #[inline] pub(crate) fn flags(&self) -> ArchetypeFlags { self.flags } /// Fetches the archetype's [`Table`] ID. /// /// [`Table`]: crate::storage::Table #[inline] pub fn table_id(&self) -> TableId { self.table_id } /// Fetches the entities contained in this archetype. #[inline] pub fn entities(&self) -> &[ArchetypeEntity] { &self.entities } /// Fetches the entities contained in this archetype. #[inline] pub fn entities_with_location(&self) -> impl Iterator<Item = (Entity, EntityLocation)> { self.entities.iter().enumerate().map( |(archetype_row, &ArchetypeEntity { entity, table_row })| { ( entity, EntityLocation { archetype_id: self.id, // SAFETY: The entities in the archetype must be unique and there are never more than u32::MAX entities. archetype_row: unsafe { ArchetypeRow::new(NonMaxU32::new_unchecked(archetype_row as u32)) }, table_id: self.table_id, table_row, }, ) }, ) } /// Gets an iterator of all of the components stored in [`Table`]s. /// /// All of the IDs are unique. /// /// [`Table`]: crate::storage::Table #[inline] pub fn table_components(&self) -> impl Iterator<Item = ComponentId> + '_ { self.components .iter() .filter(|(_, component)| component.storage_type == StorageType::Table) .map(|(id, _)| *id) } /// Gets an iterator of all of the components stored in [`ComponentSparseSet`]s. /// /// All of the IDs are unique. /// /// [`ComponentSparseSet`]: crate::storage::ComponentSparseSet #[inline] pub fn sparse_set_components(&self) -> impl Iterator<Item = ComponentId> + '_ { self.components .iter() .filter(|(_, component)| component.storage_type == StorageType::SparseSet) .map(|(id, _)| *id) } /// Returns a slice of all of the components in the archetype. /// /// All of the IDs are unique. #[inline] pub fn components(&self) -> &[ComponentId] { self.components.indices() } /// Gets an iterator of all of the components in the archetype. /// /// All of the IDs are unique. #[inline] pub fn iter_components(&self) -> impl Iterator<Item = ComponentId> + Clone { self.components.indices().iter().copied() } /// Returns the total number of components in the archetype #[inline] pub fn component_count(&self) -> usize { self.components.len() } /// Fetches an immutable reference to the archetype's [`Edges`], a cache of /// archetypal relationships. #[inline] pub fn edges(&self) -> &Edges { &self.edges } /// Fetches a mutable reference to the archetype's [`Edges`], a cache of /// archetypal relationships. #[inline] pub(crate) fn edges_mut(&mut self) -> &mut Edges { &mut self.edges } /// Fetches the row in the [`Table`] where the components for the entity at `index` /// is stored. /// /// An entity's archetype row can be fetched from [`EntityLocation::archetype_row`], which /// can be retrieved from [`Entities::get`]. /// /// # Panics /// This function will panic if `index >= self.len()`. /// /// [`Table`]: crate::storage::Table /// [`EntityLocation::archetype_row`]: crate::entity::EntityLocation::archetype_row /// [`Entities::get`]: crate::entity::Entities::get #[inline] pub fn entity_table_row(&self, row: ArchetypeRow) -> TableRow { self.entities[row.index()].table_row } /// Updates if the components for the entity at `index` can be found /// in the corresponding table. /// /// # Panics /// This function will panic if `index >= self.len()`. #[inline] pub(crate) fn set_entity_table_row(&mut self, row: ArchetypeRow, table_row: TableRow) { self.entities[row.index()].table_row = table_row; } /// Allocates an entity to the archetype. /// /// # Safety /// valid component values must be immediately written to the relevant storages /// `table_row` must be valid #[inline] pub(crate) unsafe fn allocate( &mut self, entity: Entity, table_row: TableRow, ) -> EntityLocation { // SAFETY: An entity can not have multiple archetype rows and there can not be more than u32::MAX entities. let archetype_row = unsafe { ArchetypeRow::new(NonMaxU32::new_unchecked(self.len())) }; self.entities.push(ArchetypeEntity { entity, table_row }); EntityLocation { archetype_id: self.id, archetype_row, table_id: self.table_id, table_row, } } #[inline] pub(crate) fn reserve(&mut self, additional: usize) { self.entities.reserve(additional); } /// Removes the entity at `row` by swapping it out. Returns the table row the entity is stored /// in. /// /// # Panics /// This function will panic if `row >= self.entities.len()` #[inline] pub(crate) fn swap_remove(&mut self, row: ArchetypeRow) -> ArchetypeSwapRemoveResult { let is_last = row.index() == self.entities.len() - 1; let entity = self.entities.swap_remove(row.index()); ArchetypeSwapRemoveResult { swapped_entity: if is_last { None } else { Some(self.entities[row.index()].entity) }, table_row: entity.table_row, } } /// Gets the total number of entities that belong to the archetype. #[inline] pub fn len(&self) -> u32 { // No entity may have more than one archetype row, so there are no duplicates, // and there may only ever be u32::MAX entities, so the length never exceeds u32's capacity. self.entities.len() as u32 } /// Checks if the archetype has any entities. #[inline] pub fn is_empty(&self) -> bool { self.entities.is_empty() } /// Checks if the archetype contains a specific component. This runs in `O(1)` time. #[inline] pub fn contains(&self, component_id: ComponentId) -> bool { self.components.contains(component_id) } /// Gets the type of storage where a component in the archetype can be found. /// Returns `None` if the component is not part of the archetype. /// This runs in `O(1)` time. #[inline] pub fn get_storage_type(&self, component_id: ComponentId) -> Option<StorageType> { self.components .get(component_id) .map(|info| info.storage_type) } /// Clears all entities from the archetype. pub(crate) fn clear_entities(&mut self) { self.entities.clear(); } /// Returns true if any of the components in this archetype have `on_add` hooks #[inline] pub fn has_add_hook(&self) -> bool { self.flags().contains(ArchetypeFlags::ON_ADD_HOOK) } /// Returns true if any of the components in this archetype have `on_insert` hooks #[inline] pub fn has_insert_hook(&self) -> bool { self.flags().contains(ArchetypeFlags::ON_INSERT_HOOK) } /// Returns true if any of the components in this archetype have `on_replace` hooks #[inline] pub fn has_replace_hook(&self) -> bool { self.flags().contains(ArchetypeFlags::ON_REPLACE_HOOK) } /// Returns true if any of the components in this archetype have `on_remove` hooks #[inline] pub fn has_remove_hook(&self) -> bool { self.flags().contains(ArchetypeFlags::ON_REMOVE_HOOK) } /// Returns true if any of the components in this archetype have `on_despawn` hooks #[inline] pub fn has_despawn_hook(&self) -> bool { self.flags().contains(ArchetypeFlags::ON_DESPAWN_HOOK) } /// Returns true if any of the components in this archetype have at least one [`Add`] observer /// /// [`Add`]: crate::lifecycle::Add #[inline] pub fn has_add_observer(&self) -> bool { self.flags().contains(ArchetypeFlags::ON_ADD_OBSERVER) } /// Returns true if any of the components in this archetype have at least one [`Insert`] observer /// /// [`Insert`]: crate::lifecycle::Insert #[inline] pub fn has_insert_observer(&self) -> bool { self.flags().contains(ArchetypeFlags::ON_INSERT_OBSERVER) } /// Returns true if any of the components in this archetype have at least one [`Replace`] observer /// /// [`Replace`]: crate::lifecycle::Replace #[inline] pub fn has_replace_observer(&self) -> bool { self.flags().contains(ArchetypeFlags::ON_REPLACE_OBSERVER) } /// Returns true if any of the components in this archetype have at least one [`Remove`] observer /// /// [`Remove`]: crate::lifecycle::Remove #[inline] pub fn has_remove_observer(&self) -> bool { self.flags().contains(ArchetypeFlags::ON_REMOVE_OBSERVER) } /// Returns true if any of the components in this archetype have at least one [`Despawn`] observer /// /// [`Despawn`]: crate::lifecycle::Despawn #[inline] pub fn has_despawn_observer(&self) -> bool { self.flags().contains(ArchetypeFlags::ON_DESPAWN_OBSERVER) } } /// The next [`ArchetypeId`] in an [`Archetypes`] collection. /// /// This is used in archetype update methods to limit archetype updates to the /// ones added since the last time the method ran. #[derive(Debug, Copy, Clone, PartialEq)] pub struct ArchetypeGeneration(pub(crate) ArchetypeId); impl ArchetypeGeneration { /// The first archetype. #[inline] pub const fn initial() -> Self { ArchetypeGeneration(ArchetypeId::EMPTY) } } #[derive(Hash, PartialEq, Eq)] struct ArchetypeComponents { table_components: Box<[ComponentId]>, sparse_set_components: Box<[ComponentId]>, } /// Maps a [`ComponentId`] to the list of [`Archetypes`]([`Archetype`]) that contain the [`Component`](crate::component::Component), /// along with an [`ArchetypeRecord`] which contains some metadata about how the component is stored in the archetype. pub type ComponentIndex = HashMap<ComponentId, HashMap<ArchetypeId, ArchetypeRecord>>; /// The backing store of all [`Archetype`]s within a [`World`]. /// /// For more information, see the *[module level documentation]*. /// /// [`World`]: crate::world::World /// [module level documentation]: crate::archetype pub struct Archetypes { pub(crate) archetypes: Vec<Archetype>, /// find the archetype id by the archetype's components by_components: HashMap<ArchetypeComponents, ArchetypeId>, /// find all the archetypes that contain a component pub(crate) by_component: ComponentIndex, } /// Metadata about how a component is stored in an [`Archetype`]. pub struct ArchetypeRecord { /// Index of the component in the archetype's [`Table`](crate::storage::Table), /// or None if the component is a sparse set component. #[expect( dead_code, reason = "Currently unused, but planned to be used to implement a component index to improve performance of fragmenting relations." )] pub(crate) column: Option<usize>, } impl Archetypes { pub(crate) fn new() -> Self { let mut archetypes = Archetypes { archetypes: Vec::new(), by_components: Default::default(), by_component: Default::default(), }; // SAFETY: Empty archetype has no components unsafe { archetypes.get_id_or_insert( &Components::default(), &Observers::default(), TableId::empty(), Vec::new(), Vec::new(), ); } archetypes } /// Returns the "generation", a handle to the current highest archetype ID. /// /// This can be used with the `Index` [`Archetypes`] implementation to /// iterate over newly introduced [`Archetype`]s since the last time this /// function was called. #[inline] pub fn generation(&self) -> ArchetypeGeneration { let id = ArchetypeId::new(self.archetypes.len()); ArchetypeGeneration(id) } /// Fetches the total number of [`Archetype`]s within the world. #[inline] #[expect( clippy::len_without_is_empty, reason = "The internal vec is never empty" )] pub fn len(&self) -> usize { self.archetypes.len() } /// Fetches an immutable reference to the archetype without any components. /// /// Shorthand for `archetypes.get(ArchetypeId::EMPTY).unwrap()` #[inline] pub fn empty(&self) -> &Archetype { // SAFETY: empty archetype always exists unsafe { self.archetypes.get_unchecked(ArchetypeId::EMPTY.index()) } } /// Fetches a mutable reference to the archetype without any components. #[inline] pub(crate) fn empty_mut(&mut self) -> &mut Archetype { // SAFETY: empty archetype always exists unsafe { self.archetypes .get_unchecked_mut(ArchetypeId::EMPTY.index()) } } /// Fetches an immutable reference to an [`Archetype`] using its /// ID. Returns `None` if no corresponding archetype exists. #[inline] pub fn get(&self, id: ArchetypeId) -> Option<&Archetype> { self.archetypes.get(id.index()) } /// # Panics /// /// Panics if `a` and `b` are equal. #[inline] pub(crate) fn get_2_mut( &mut self, a: ArchetypeId, b: ArchetypeId, ) -> (&mut Archetype, &mut Archetype) { if a.index() > b.index() { let (b_slice, a_slice) = self.archetypes.split_at_mut(a.index()); (&mut a_slice[0], &mut b_slice[b.index()]) } else { let (a_slice, b_slice) = self.archetypes.split_at_mut(b.index()); (&mut a_slice[a.index()], &mut b_slice[0]) } } /// Returns a read-only iterator over all archetypes. #[inline] pub fn iter(&self) -> impl Iterator<Item = &Archetype> { self.archetypes.iter() } /// Gets the archetype id matching the given inputs or inserts a new one if it doesn't exist. /// /// Specifically, it returns a tuple where the first element /// is the [`ArchetypeId`] that the given inputs belong to, and the second element is a boolean indicating whether a new archetype was created. /// /// `table_components` and `sparse_set_components` must be sorted /// /// # Safety /// [`TableId`] must exist in tables /// `table_components` and `sparse_set_components` must exist in `components` pub(crate) unsafe fn get_id_or_insert( &mut self, components: &Components, observers: &Observers, table_id: TableId, table_components: Vec<ComponentId>, sparse_set_components: Vec<ComponentId>, ) -> (ArchetypeId, bool) { let archetype_identity = ArchetypeComponents {
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/entity_disabling.rs
crates/bevy_ecs/src/entity_disabling.rs
//! Disabled entities do not show up in queries unless the query explicitly mentions them. //! //! Entities which are disabled in this way are not removed from the [`World`], //! and their relationships remain intact. //! In many cases, you may want to disable entire trees of entities at once, //! using [`EntityCommands::insert_recursive`](crate::prelude::EntityCommands::insert_recursive). //! //! While Bevy ships with a built-in [`Disabled`] component, you can also create your own //! disabling components, which will operate in the same way but can have distinct semantics. //! //! ``` //! use bevy_ecs::prelude::*; //! //! // Our custom disabling component! //! #[derive(Component, Clone)] //! struct Prefab; //! //! #[derive(Component)] //! struct A; //! //! let mut world = World::new(); //! world.register_disabling_component::<Prefab>(); //! world.spawn((A, Prefab)); //! world.spawn((A,)); //! world.spawn((A,)); //! //! let mut normal_query = world.query::<&A>(); //! assert_eq!(2, normal_query.iter(&world).count()); //! //! let mut prefab_query = world.query_filtered::<&A, With<Prefab>>(); //! assert_eq!(1, prefab_query.iter(&world).count()); //! //! let mut maybe_prefab_query = world.query::<(&A, Has<Prefab>)>(); //! assert_eq!(3, maybe_prefab_query.iter(&world).count()); //! ``` //! //! ## Default query filters //! //! In Bevy, entity disabling is implemented through the construction of a global "default query filter" resource. //! Queries which do not explicitly mention the disabled component will not include entities with that component. //! If an entity has multiple disabling components, it will only be included in queries that mention all of them. //! //! For example, `Query<&Position>` will not include entities with the [`Disabled`] component, //! even if they have a `Position` component, //! but `Query<&Position, With<Disabled>>` or `Query<(&Position, Has<Disabled>)>` will see them. //! //! The [`Allow`](crate::query::Allow) query filter is designed to be used with default query filters, //! and ensures that the query will include entities both with and without the specified disabling component. //! //! Entities with disabling components are still present in the [`World`] and can be accessed directly, //! using methods on [`World`] or [`Commands`](crate::prelude::Commands). //! //! As default query filters are implemented through a resource, //! it's possible to temporarily ignore any default filters by using [`World::resource_scope`](crate::prelude::World). //! //! ``` //! use bevy_ecs::prelude::*; //! use bevy_ecs::entity_disabling::{DefaultQueryFilters, Disabled}; //! //! let mut world = World::default(); //! //! #[derive(Component)] //! struct CustomDisabled; //! //! world.register_disabling_component::<CustomDisabled>(); //! //! world.spawn(Disabled); //! world.spawn(CustomDisabled); //! //! // resource_scope removes DefaultQueryFilters temporarily before re-inserting into the world. //! world.resource_scope(|world: &mut World, _: Mut<DefaultQueryFilters>| { //! // within this scope, we can query like no components are disabled. //! assert_eq!(world.query::<&Disabled>().query(&world).count(), 1); //! assert_eq!(world.query::<&CustomDisabled>().query(&world).count(), 1); //! assert_eq!(world.query::<()>().query(&world).count(), world.entities().count_spawned() as usize); //! }) //! ``` //! //! ### Warnings //! //! Currently, only queries for which the cache is built after enabling a default query filter will have entities //! with those components filtered. As a result, they should generally only be modified before the //! app starts. //! //! Because filters are applied to all queries they can have performance implication for //! the entire [`World`], especially when they cause queries to mix sparse and table components. //! See [`Query` performance] for more info. //! //! Custom disabling components can cause significant interoperability issues within the ecosystem, //! as users must be aware of each disabling component in use. //! Libraries should think carefully about whether they need to use a new disabling component, //! and clearly communicate their presence to their users to avoid the new for library compatibility flags. //! //! [`With`]: crate::prelude::With //! [`Has`]: crate::prelude::Has //! [`World`]: crate::prelude::World //! [`Query` performance]: crate::prelude::Query#performance use crate::{ component::{ComponentId, Components, StorageType}, query::FilteredAccess, world::{FromWorld, World}, }; use bevy_ecs_macros::{Component, Resource}; use smallvec::SmallVec; #[cfg(feature = "bevy_reflect")] use { crate::reflect::ReflectComponent, bevy_reflect::std_traits::ReflectDefault, bevy_reflect::Reflect, }; /// A marker component for disabled entities. /// /// Semantically, this component is used to mark entities that are temporarily disabled (typically for gameplay reasons), /// but will likely be re-enabled at some point. /// /// Like all disabling components, this only disables the entity itself, /// not its children or other entities that reference it. /// To disable an entire tree of entities, use [`EntityCommands::insert_recursive`](crate::prelude::EntityCommands::insert_recursive). /// /// Every [`World`] has a default query filter that excludes entities with this component, /// registered in the [`DefaultQueryFilters`] resource. /// See [the module docs] for more info. /// /// [the module docs]: crate::entity_disabling #[derive(Component, Clone, Debug, Default)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Component), reflect(Debug, Clone, Default) )] // This component is registered as a disabling component during World::bootstrap pub struct Disabled; /// Default query filters work by excluding entities with certain components from most queries. /// /// If a query does not explicitly mention a given disabling component, it will not include entities with that component. /// To be more precise, this checks if the query's [`FilteredAccess`] contains the component, /// and if it does not, adds a [`Without`](crate::prelude::Without) filter for that component to the query. /// /// [`Allow`](crate::query::Allow) and [`Has`](crate::prelude::Has) can be used to include entities /// with and without the disabling component. /// [`Allow`](crate::query::Allow) is a [`QueryFilter`](crate::query::QueryFilter) and will simply change /// the list of shown entities, while [`Has`](crate::prelude::Has) is a [`QueryData`](crate::query::QueryData) /// and will allow you to see if each entity has the disabling component or not. /// /// This resource is initialized in the [`World`] whenever a new world is created, /// with the [`Disabled`] component as a disabling component. /// /// Note that you can remove default query filters by overwriting the [`DefaultQueryFilters`] resource. /// This can be useful as a last resort escape hatch, but is liable to break compatibility with other libraries. /// /// See the [module docs](crate::entity_disabling) for more info. /// /// /// # Warning /// /// Default query filters are a global setting that affects all queries in the [`World`], /// and incur a small performance cost for each query. /// /// They can cause significant interoperability issues within the ecosystem, /// as users must be aware of each disabling component in use. /// /// Think carefully about whether you need to use a new disabling component, /// and clearly communicate their presence in any libraries you publish. #[derive(Resource, Debug)] #[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))] pub struct DefaultQueryFilters { // We only expect a few components per application to act as disabling components, so we use a SmallVec here // to avoid heap allocation in most cases. disabling: SmallVec<[ComponentId; 4]>, } impl FromWorld for DefaultQueryFilters { fn from_world(world: &mut World) -> Self { let mut filters = DefaultQueryFilters::empty(); let disabled_component_id = world.register_component::<Disabled>(); filters.register_disabling_component(disabled_component_id); filters } } impl DefaultQueryFilters { /// Creates a new, completely empty [`DefaultQueryFilters`]. /// /// This is provided as an escape hatch; in most cases you should initialize this using [`FromWorld`], /// which is automatically called when creating a new [`World`]. #[must_use] pub fn empty() -> Self { DefaultQueryFilters { disabling: SmallVec::new(), } } /// Adds this [`ComponentId`] to the set of [`DefaultQueryFilters`], /// causing entities with this component to be excluded from queries. /// /// This method is idempotent, and will not add the same component multiple times. /// /// # Warning /// /// This method should only be called before the app starts, as it will not affect queries /// initialized before it is called. /// /// As discussed in the [module docs](crate::entity_disabling), this can have performance implications, /// as well as create interoperability issues, and should be used with caution. pub fn register_disabling_component(&mut self, component_id: ComponentId) { if !self.disabling.contains(&component_id) { self.disabling.push(component_id); } } /// Get an iterator over all of the components which disable entities when present. pub fn disabling_ids(&self) -> impl Iterator<Item = ComponentId> { self.disabling.iter().copied() } /// Modifies the provided [`FilteredAccess`] to include the filters from this [`DefaultQueryFilters`]. pub(super) fn modify_access(&self, component_access: &mut FilteredAccess) { for component_id in self.disabling_ids() { if !component_access.contains(component_id) { component_access.and_without(component_id); } } } pub(super) fn is_dense(&self, components: &Components) -> bool { self.disabling_ids().all(|component_id| { components .get_info(component_id) .is_some_and(|info| info.storage_type() == StorageType::Table) }) } } #[cfg(test)] mod tests { use super::*; use crate::{ prelude::{EntityMut, EntityRef, World}, query::{Has, With}, }; use alloc::{vec, vec::Vec}; #[test] fn filters_modify_access() { let mut filters = DefaultQueryFilters::empty(); filters.register_disabling_component(ComponentId::new(1)); // A component access with an unrelated component let mut component_access = FilteredAccess::default(); component_access .access_mut() .add_component_read(ComponentId::new(2)); let mut applied_access = component_access.clone(); filters.modify_access(&mut applied_access); assert_eq!(0, applied_access.with_filters().count()); assert_eq!( vec![ComponentId::new(1)], applied_access.without_filters().collect::<Vec<_>>() ); // We add a with filter, now we expect to see both filters component_access.and_with(ComponentId::new(4)); let mut applied_access = component_access.clone(); filters.modify_access(&mut applied_access); assert_eq!( vec![ComponentId::new(4)], applied_access.with_filters().collect::<Vec<_>>() ); assert_eq!( vec![ComponentId::new(1)], applied_access.without_filters().collect::<Vec<_>>() ); let copy = component_access.clone(); // We add a rule targeting a default component, that filter should no longer be added component_access.and_with(ComponentId::new(1)); let mut applied_access = component_access.clone(); filters.modify_access(&mut applied_access); assert_eq!( vec![ComponentId::new(1), ComponentId::new(4)], applied_access.with_filters().collect::<Vec<_>>() ); assert_eq!(0, applied_access.without_filters().count()); // Archetypal access should also filter rules component_access = copy.clone(); component_access .access_mut() .add_archetypal(ComponentId::new(1)); let mut applied_access = component_access.clone(); filters.modify_access(&mut applied_access); assert_eq!( vec![ComponentId::new(4)], applied_access.with_filters().collect::<Vec<_>>() ); assert_eq!(0, applied_access.without_filters().count()); } #[derive(Component)] struct CustomDisabled; #[derive(Component)] struct Dummy; #[test] fn multiple_disabling_components() { let mut world = World::new(); world.register_disabling_component::<CustomDisabled>(); // Use powers of two so we can uniquely identify the set of matching archetypes from the count. world.spawn(Dummy); world.spawn_batch((0..2).map(|_| (Dummy, Disabled))); world.spawn_batch((0..4).map(|_| (Dummy, CustomDisabled))); world.spawn_batch((0..8).map(|_| (Dummy, Disabled, CustomDisabled))); let mut query = world.query::<&Dummy>(); assert_eq!(1, query.iter(&world).count()); let mut query = world.query_filtered::<EntityRef, With<Dummy>>(); assert_eq!(1, query.iter(&world).count()); let mut query = world.query_filtered::<EntityMut, With<Dummy>>(); assert_eq!(1, query.iter(&world).count()); let mut query = world.query_filtered::<&Dummy, With<Disabled>>(); assert_eq!(2, query.iter(&world).count()); let mut query = world.query_filtered::<Has<Disabled>, With<Dummy>>(); assert_eq!(3, query.iter(&world).count()); let mut query = world.query_filtered::<&Dummy, With<CustomDisabled>>(); assert_eq!(4, query.iter(&world).count()); let mut query = world.query_filtered::<Has<CustomDisabled>, With<Dummy>>(); assert_eq!(5, query.iter(&world).count()); let mut query = world.query_filtered::<&Dummy, (With<Disabled>, With<CustomDisabled>)>(); assert_eq!(8, query.iter(&world).count()); let mut query = world.query_filtered::<(Has<Disabled>, Has<CustomDisabled>), With<Dummy>>(); assert_eq!(15, query.iter(&world).count()); // This seems like it ought to count as a mention of `Disabled`, but it does not. // We don't consider read access, since that would count `EntityRef` as a mention of *all* components. let mut query = world.query_filtered::<Option<&Disabled>, With<Dummy>>(); assert_eq!(1, query.iter(&world).count()); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/name.rs
crates/bevy_ecs/src/name.rs
//! Provides the [`Name`] [`Component`], used for identifying an [`Entity`]. use crate::{component::Component, entity::Entity, query::QueryData}; use alloc::{ borrow::{Cow, ToOwned}, string::String, }; use bevy_platform::hash::FixedHasher; use core::{ hash::{BuildHasher, Hash, Hasher}, ops::Deref, }; #[cfg(feature = "serialize")] use { alloc::string::ToString, serde::{ de::{Error, Visitor}, Deserialize, Deserializer, Serialize, Serializer, }, }; #[cfg(feature = "bevy_reflect")] use { crate::reflect::ReflectComponent, bevy_reflect::{std_traits::ReflectDefault, Reflect}, }; #[cfg(all(feature = "serialize", feature = "bevy_reflect"))] use bevy_reflect::{ReflectDeserialize, ReflectSerialize}; /// Component used to identify an entity. Stores a hash for faster comparisons. /// /// The hash is eagerly re-computed upon each update to the name. /// /// [`Name`] should not be treated as a globally unique identifier for entities, /// as multiple entities can have the same name. [`Entity`] should be /// used instead as the default unique identifier. #[derive(Component, Clone)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Component, Default, Debug, Clone, Hash, PartialEq) )] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Deserialize, Serialize) )] pub struct Name { hash: u64, // Won't be serialized name: Cow<'static, str>, } impl Default for Name { fn default() -> Self { Name::new("") } } impl Name { /// Creates a new [`Name`] from any string-like type. /// /// The internal hash will be computed immediately. pub fn new(name: impl Into<Cow<'static, str>>) -> Self { let name = name.into(); let mut name = Name { name, hash: 0 }; name.update_hash(); name } /// Sets the entity's name. /// /// The internal hash will be re-computed. #[inline(always)] pub fn set(&mut self, name: impl Into<Cow<'static, str>>) { *self = Name::new(name); } /// Updates the name of the entity in place. /// /// This will allocate a new string if the name was previously /// created from a borrow. #[inline(always)] pub fn mutate<F: FnOnce(&mut String)>(&mut self, f: F) { f(self.name.to_mut()); self.update_hash(); } /// Gets the name of the entity as a `&str`. #[inline(always)] pub fn as_str(&self) -> &str { &self.name } fn update_hash(&mut self) { self.hash = FixedHasher.hash_one(&self.name); } } impl core::fmt::Display for Name { #[inline(always)] fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { core::fmt::Display::fmt(&self.name, f) } } impl core::fmt::Debug for Name { #[inline(always)] fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { core::fmt::Debug::fmt(&self.name, f) } } /// Convenient query for giving a human friendly name to an entity. /// /// ``` /// # use bevy_ecs::prelude::*; /// # #[derive(Component)] pub struct Score(f32); /// fn increment_score(mut scores: Query<(NameOrEntity, &mut Score)>) { /// for (name, mut score) in &mut scores { /// score.0 += 1.0; /// if score.0.is_nan() { /// log::error!("Score for {name} is invalid"); /// } /// } /// } /// # bevy_ecs::system::assert_is_system(increment_score); /// ``` /// /// # Implementation /// /// The `Display` impl for `NameOrEntity` returns the `Name` where there is one /// or {index}v{generation} for entities without one. #[derive(QueryData)] #[query_data(derive(Debug))] pub struct NameOrEntity { /// A [`Name`] that the entity might have that is displayed if available. pub name: Option<&'static Name>, /// The unique identifier of the entity as a fallback. pub entity: Entity, } impl<'w, 's> core::fmt::Display for NameOrEntityItem<'w, 's> { #[inline(always)] fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { match self.name { Some(name) => core::fmt::Display::fmt(name, f), None => core::fmt::Display::fmt(&self.entity, f), } } } // Conversions from strings impl From<&str> for Name { #[inline(always)] fn from(name: &str) -> Self { Name::new(name.to_owned()) } } impl From<String> for Name { #[inline(always)] fn from(name: String) -> Self { Name::new(name) } } // Conversions to strings impl AsRef<str> for Name { #[inline(always)] fn as_ref(&self) -> &str { &self.name } } impl From<&Name> for String { #[inline(always)] fn from(val: &Name) -> String { val.as_str().to_owned() } } impl From<Name> for String { #[inline(always)] fn from(val: Name) -> String { val.name.into_owned() } } impl Hash for Name { fn hash<H: Hasher>(&self, state: &mut H) { self.name.hash(state); } } impl PartialEq for Name { fn eq(&self, other: &Self) -> bool { if self.hash != other.hash { // Makes the common case of two strings not been equal very fast return false; } self.name.eq(&other.name) } } impl Eq for Name {} impl PartialOrd for Name { fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for Name { fn cmp(&self, other: &Self) -> core::cmp::Ordering { self.name.cmp(&other.name) } } impl Deref for Name { type Target = str; fn deref(&self) -> &Self::Target { self.name.as_ref() } } #[cfg(feature = "serialize")] impl Serialize for Name { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { serializer.serialize_str(self.as_str()) } } #[cfg(feature = "serialize")] impl<'de> Deserialize<'de> for Name { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { deserializer.deserialize_str(NameVisitor) } } #[cfg(feature = "serialize")] struct NameVisitor; #[cfg(feature = "serialize")] impl<'de> Visitor<'de> for NameVisitor { type Value = Name; fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result { formatter.write_str(core::any::type_name::<Name>()) } fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> { Ok(Name::new(v.to_string())) } fn visit_string<E: Error>(self, v: String) -> Result<Self::Value, E> { Ok(Name::new(v)) } } #[cfg(test)] mod tests { use super::*; use crate::world::World; use alloc::string::ToString; #[test] fn test_display_of_debug_name() { let mut world = World::new(); let e1 = world.spawn_empty().id(); let name = Name::new("MyName"); let e2 = world.spawn(name.clone()).id(); let mut query = world.query::<NameOrEntity>(); let d1 = query.get(&world, e1).unwrap(); // NameOrEntity Display for entities without a Name should be {index}v{generation} assert_eq!(d1.to_string(), "0v0"); let d2 = query.get(&world, e2).unwrap(); // NameOrEntity Display for entities with a Name should be the Name assert_eq!(d2.to_string(), "MyName"); } } #[cfg(all(test, feature = "serialize"))] mod serde_tests { use super::Name; use serde_test::{assert_tokens, Token}; #[test] fn test_serde_name() { let name = Name::new("MyComponent"); assert_tokens(&name, &[Token::String("MyComponent")]); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/intern.rs
crates/bevy_ecs/src/intern.rs
//! Provides types used to statically intern immutable values. //! //! Interning is a pattern used to save memory by deduplicating identical values, //! speed up code by shrinking the stack size of large types, //! and make comparisons for any type as fast as integers. use alloc::{borrow::ToOwned, boxed::Box}; use bevy_platform::{ collections::HashSet, hash::FixedHasher, sync::{PoisonError, RwLock}, }; use core::{fmt::Debug, hash::Hash, ops::Deref}; /// An interned value. Will stay valid until the end of the program and will not drop. /// /// For details on interning, see [the module level docs](self). /// /// # Comparisons /// /// Interned values use reference equality, meaning they implement [`Eq`] /// and [`Hash`] regardless of whether `T` implements these traits. /// Two interned values are only guaranteed to compare equal if they were interned using /// the same [`Interner`] instance. // NOTE: This type must NEVER implement Borrow since it does not obey that trait's invariants. /// ``` /// # use bevy_ecs::intern::*; /// #[derive(PartialEq, Eq, Hash, Debug)] /// struct Value(i32); /// impl Internable for Value { /// // ... /// # fn leak(&self) -> &'static Self { Box::leak(Box::new(Value(self.0))) } /// # fn ref_eq(&self, other: &Self) -> bool { std::ptr::eq(self, other ) } /// # fn ref_hash<H: std::hash::Hasher>(&self, state: &mut H) { std::ptr::hash(self, state); } /// } /// let interner_1 = Interner::new(); /// let interner_2 = Interner::new(); /// // Even though both values are identical, their interned forms do not /// // compare equal as they use different interner instances. /// assert_ne!(interner_1.intern(&Value(42)), interner_2.intern(&Value(42))); /// ``` pub struct Interned<T: ?Sized + 'static>(pub &'static T); impl<T: ?Sized> Deref for Interned<T> { type Target = T; fn deref(&self) -> &Self::Target { self.0 } } impl<T: ?Sized> Clone for Interned<T> { fn clone(&self) -> Self { *self } } impl<T: ?Sized> Copy for Interned<T> {} // Two Interned<T> should only be equal if they are clones from the same instance. // Therefore, we only use the pointer to determine equality. impl<T: ?Sized + Internable> PartialEq for Interned<T> { fn eq(&self, other: &Self) -> bool { self.0.ref_eq(other.0) } } impl<T: ?Sized + Internable> Eq for Interned<T> {} // Important: This must be kept in sync with the PartialEq/Eq implementation impl<T: ?Sized + Internable> Hash for Interned<T> { fn hash<H: core::hash::Hasher>(&self, state: &mut H) { self.0.ref_hash(state); } } impl<T: ?Sized + Debug> Debug for Interned<T> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.0.fmt(f) } } impl<T> From<&Interned<T>> for Interned<T> { fn from(value: &Interned<T>) -> Self { *value } } /// A trait for internable values. /// /// This is used by [`Interner<T>`] to create static references for values that are interned. pub trait Internable: Hash + Eq { /// Creates a static reference to `self`, possibly leaking memory. fn leak(&self) -> &'static Self; /// Returns `true` if the two references point to the same value. fn ref_eq(&self, other: &Self) -> bool; /// Feeds the reference to the hasher. fn ref_hash<H: core::hash::Hasher>(&self, state: &mut H); } impl Internable for str { fn leak(&self) -> &'static Self { let str = self.to_owned().into_boxed_str(); Box::leak(str) } fn ref_eq(&self, other: &Self) -> bool { self.as_ptr() == other.as_ptr() && self.len() == other.len() } fn ref_hash<H: core::hash::Hasher>(&self, state: &mut H) { self.len().hash(state); self.as_ptr().hash(state); } } /// A thread-safe interner which can be used to create [`Interned<T>`] from `&T` /// /// For details on interning, see [the module level docs](self). /// /// The implementation ensures that two equal values return two equal [`Interned<T>`] values. /// /// To use an [`Interner<T>`], `T` must implement [`Internable`]. pub struct Interner<T: ?Sized + 'static>(RwLock<HashSet<&'static T>>); impl<T: ?Sized> Interner<T> { /// Creates a new empty interner pub const fn new() -> Self { Self(RwLock::new(HashSet::with_hasher(FixedHasher))) } } impl<T: Internable + ?Sized> Interner<T> { /// Return the [`Interned<T>`] corresponding to `value`. /// /// If it is called the first time for `value`, it will possibly leak the value and return an /// [`Interned<T>`] using the obtained static reference. Subsequent calls for the same `value` /// will return [`Interned<T>`] using the same static reference. pub fn intern(&self, value: &T) -> Interned<T> { { let set = self.0.read().unwrap_or_else(PoisonError::into_inner); if let Some(value) = set.get(value) { return Interned(*value); } } { let mut set = self.0.write().unwrap_or_else(PoisonError::into_inner); if let Some(value) = set.get(value) { Interned(*value) } else { let leaked = value.leak(); set.insert(leaked); Interned(leaked) } } } } impl<T: ?Sized> Default for Interner<T> { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use alloc::{boxed::Box, string::ToString}; use bevy_platform::hash::FixedHasher; use core::hash::{BuildHasher, Hash, Hasher}; use crate::intern::{Internable, Interned, Interner}; #[test] fn zero_sized_type() { #[derive(PartialEq, Eq, Hash, Debug)] pub struct A; impl Internable for A { fn leak(&self) -> &'static Self { &A } fn ref_eq(&self, other: &Self) -> bool { core::ptr::eq(self, other) } fn ref_hash<H: Hasher>(&self, state: &mut H) { core::ptr::hash(self, state); } } let interner = Interner::default(); let x = interner.intern(&A); let y = interner.intern(&A); assert_eq!(x, y); } #[test] fn fieldless_enum() { #[derive(PartialEq, Eq, Hash, Debug, Clone)] pub enum A { X, Y, } impl Internable for A { fn leak(&self) -> &'static Self { match self { A::X => &A::X, A::Y => &A::Y, } } fn ref_eq(&self, other: &Self) -> bool { core::ptr::eq(self, other) } fn ref_hash<H: Hasher>(&self, state: &mut H) { core::ptr::hash(self, state); } } let interner = Interner::default(); let x = interner.intern(&A::X); let y = interner.intern(&A::Y); assert_ne!(x, y); } #[test] fn static_sub_strings() { let str = "ABC ABC"; let a = &str[0..3]; let b = &str[4..7]; // Same contents assert_eq!(a, b); let x = Interned(a); let y = Interned(b); // Different pointers assert_ne!(x, y); let interner = Interner::default(); let x = interner.intern(a); let y = interner.intern(b); // Same pointers returned by interner assert_eq!(x, y); } #[test] fn same_interned_instance() { let a = Interned("A"); let b = a; assert_eq!(a, b); let hash_a = FixedHasher.hash_one(a); let hash_b = FixedHasher.hash_one(b); assert_eq!(hash_a, hash_b); } #[test] fn same_interned_content() { let a = Interned::<str>(Box::leak(Box::new("A".to_string()))); let b = Interned::<str>(Box::leak(Box::new("A".to_string()))); assert_ne!(a, b); } #[test] fn different_interned_content() { let a = Interned::<str>("A"); let b = Interned::<str>("B"); assert_ne!(a, b); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/traversal.rs
crates/bevy_ecs/src/traversal.rs
//! A trait for components that let you traverse the ECS. use crate::{ entity::Entity, query::{ReadOnlyQueryData, ReleaseStateQueryData}, relationship::Relationship, }; /// A component that can point to another entity, and which can be used to define a path through the ECS. /// /// Traversals are used to [specify the direction] of [event propagation] in [`EntityEvent`] [observers]. /// The default query is `()`. /// /// Infinite loops are possible, and are not checked for. While looping can be desirable in some contexts /// (for example, an observer that triggers itself multiple times before stopping), following an infinite /// traversal loop without an eventual exit will cause your application to hang. Each implementer of `Traversal` /// is responsible for documenting possible looping behavior, and consumers of those implementations are responsible for /// avoiding infinite loops in their code. /// /// Traversals may be parameterized with additional data. For example, in observer event propagation, the /// parameter `D` is the event type given in `On<E>`. This allows traversal to differ depending on event /// data. /// /// [specify the direction]: crate::event::PropagateEntityTrigger /// [event propagation]: crate::observer::On::propagate /// [observers]: crate::observer::Observer /// [`EntityEvent`]: crate::event::EntityEvent pub trait Traversal<D: ?Sized>: ReadOnlyQueryData + ReleaseStateQueryData { /// Returns the next entity to visit. fn traverse(item: Self::Item<'_, '_>, data: &D) -> Option<Entity>; } impl<D> Traversal<D> for () { fn traverse(_: Self::Item<'_, '_>, _data: &D) -> Option<Entity> { None } } /// This provides generalized hierarchy traversal for use in [event propagation]. /// /// # Warning /// /// Traversing in a loop could result in infinite loops for relationship graphs with loops. /// /// [event propagation]: crate::observer::On::propagate impl<R: Relationship, D> Traversal<D> for &R { fn traverse(item: Self::Item<'_, '_>, _data: &D) -> Option<Entity> { Some(item.get()) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/label.rs
crates/bevy_ecs/src/label.rs
//! Traits used by label implementations use core::{ any::Any, hash::{Hash, Hasher}, }; // Re-exported for use within `define_label!` #[doc(hidden)] pub use alloc::boxed::Box; /// An object safe version of [`Eq`]. This trait is automatically implemented /// for any `'static` type that implements `Eq`. pub trait DynEq: Any { /// This method tests for `self` and `other` values to be equal. /// /// Implementers should avoid returning `true` when the underlying types are /// not the same. fn dyn_eq(&self, other: &dyn DynEq) -> bool; } // Tests that this trait is dyn-compatible const _: Option<Box<dyn DynEq>> = None; impl<T> DynEq for T where T: Any + Eq, { fn dyn_eq(&self, other: &dyn DynEq) -> bool { if let Some(other) = (other as &dyn Any).downcast_ref::<T>() { return self == other; } false } } /// An object safe version of [`Hash`]. This trait is automatically implemented /// for any `'static` type that implements `Hash`. pub trait DynHash: DynEq { /// Feeds this value into the given [`Hasher`]. fn dyn_hash(&self, state: &mut dyn Hasher); } // Tests that this trait is dyn-compatible const _: Option<Box<dyn DynHash>> = None; impl<T> DynHash for T where T: DynEq + Hash, { fn dyn_hash(&self, mut state: &mut dyn Hasher) { T::hash(self, &mut state); self.type_id().hash(&mut state); } } /// Macro to define a new label trait /// /// # Example /// /// ``` /// # use bevy_ecs::define_label; /// define_label!( /// /// Documentation of label trait /// MyNewLabelTrait, /// MY_NEW_LABEL_TRAIT_INTERNER /// ); /// /// define_label!( /// /// Documentation of another label trait /// MyNewExtendedLabelTrait, /// MY_NEW_EXTENDED_LABEL_TRAIT_INTERNER, /// extra_methods: { /// // Extra methods for the trait can be defined here /// fn additional_method(&self) -> i32; /// }, /// extra_methods_impl: { /// // Implementation of the extra methods for Interned<dyn MyNewExtendedLabelTrait> /// fn additional_method(&self) -> i32 { /// 0 /// } /// } /// ); /// ``` #[macro_export] macro_rules! define_label { ( $(#[$label_attr:meta])* $label_trait_name:ident, $interner_name:ident ) => { $crate::define_label!( $(#[$label_attr])* $label_trait_name, $interner_name, extra_methods: {}, extra_methods_impl: {} ); }; ( $(#[$label_attr:meta])* $label_trait_name:ident, $interner_name:ident, extra_methods: { $($trait_extra_methods:tt)* }, extra_methods_impl: { $($interned_extra_methods_impl:tt)* } ) => { $(#[$label_attr])* pub trait $label_trait_name: Send + Sync + ::core::fmt::Debug + $crate::label::DynEq + $crate::label::DynHash { $($trait_extra_methods)* /// Clones this ` #[doc = stringify!($label_trait_name)] ///`. fn dyn_clone(&self) -> $crate::label::Box<dyn $label_trait_name>; /// Returns an [`Interned`] value corresponding to `self`. fn intern(&self) -> $crate::intern::Interned<dyn $label_trait_name> where Self: Sized { $interner_name.intern(self) } } #[diagnostic::do_not_recommend] impl $label_trait_name for $crate::intern::Interned<dyn $label_trait_name> { $($interned_extra_methods_impl)* fn dyn_clone(&self) -> $crate::label::Box<dyn $label_trait_name> { (**self).dyn_clone() } fn intern(&self) -> Self { *self } } impl PartialEq for dyn $label_trait_name { fn eq(&self, other: &Self) -> bool { self.dyn_eq(other) } } impl Eq for dyn $label_trait_name {} impl ::core::hash::Hash for dyn $label_trait_name { fn hash<H: ::core::hash::Hasher>(&self, state: &mut H) { self.dyn_hash(state); } } impl $crate::intern::Internable for dyn $label_trait_name { fn leak(&self) -> &'static Self { $crate::label::Box::leak(self.dyn_clone()) } fn ref_eq(&self, other: &Self) -> bool { use ::core::ptr; // Test that both the type id and pointer address are equivalent. self.type_id() == other.type_id() && ptr::addr_eq(ptr::from_ref::<Self>(self), ptr::from_ref::<Self>(other)) } fn ref_hash<H: ::core::hash::Hasher>(&self, state: &mut H) { use ::core::{hash::Hash, ptr}; // Hash the type id... self.type_id().hash(state); // ...and the pointer address. // Cast to a unit `()` first to discard any pointer metadata. ptr::from_ref::<Self>(self).cast::<()>().hash(state); } } static $interner_name: $crate::intern::Interner<dyn $label_trait_name> = $crate::intern::Interner::new(); }; }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/storage/resource.rs
crates/bevy_ecs/src/storage/resource.rs
use crate::{ change_detection::{ CheckChangeTicks, ComponentTickCells, ComponentTicks, ComponentTicksMut, MaybeLocation, MutUntyped, Tick, }, component::{ComponentId, Components}, storage::{blob_array::BlobArray, SparseSet}, }; use bevy_ptr::{OwningPtr, Ptr, UnsafeCellDeref}; use bevy_utils::prelude::DebugName; use core::{cell::UnsafeCell, panic::Location}; #[cfg(feature = "std")] use std::thread::ThreadId; /// The type-erased backing storage and metadata for a single resource within a [`World`]. /// /// If `SEND` is false, values of this type will panic if dropped from a different thread. /// /// [`World`]: crate::world::World pub struct ResourceData<const SEND: bool> { /// Capacity is 1, length is 1 if `is_present` and 0 otherwise. data: BlobArray, is_present: bool, added_ticks: UnsafeCell<Tick>, changed_ticks: UnsafeCell<Tick>, #[cfg_attr( not(feature = "std"), expect(dead_code, reason = "currently only used with the std feature") )] type_name: DebugName, #[cfg(feature = "std")] origin_thread_id: Option<ThreadId>, changed_by: MaybeLocation<UnsafeCell<&'static Location<'static>>>, } impl<const SEND: bool> Drop for ResourceData<SEND> { fn drop(&mut self) { // For Non Send resources we need to validate that correct thread // is dropping the resource. This validation is not needed in case // of SEND resources. Or if there is no data. if !SEND && self.is_present() { // If this thread is already panicking, panicking again will cause // the entire process to abort. In this case we choose to avoid // dropping or checking this altogether and just leak the column. #[cfg(feature = "std")] if std::thread::panicking() { return; } self.validate_access(); } // SAFETY: Drop is only called once upon dropping the ResourceData // and is inaccessible after this as the parent ResourceData has // been dropped. The validate_access call above will check that the // data is dropped on the thread it was inserted from. unsafe { self.data.drop(1, self.is_present().into()); } } } impl<const SEND: bool> ResourceData<SEND> { /// The only row in the underlying `BlobArray`. const ROW: usize = 0; /// Validates the access to `!Send` resources is only done on the thread they were created from. /// /// # Panics /// If `SEND` is false, this will panic if called from a different thread than the one it was inserted from. #[inline] fn validate_access(&self) { if !SEND { #[cfg(feature = "std")] if self.origin_thread_id != Some(std::thread::current().id()) { // Panic in tests, as testing for aborting is nearly impossible panic!( "Attempted to access or drop non-send resource {} from thread {:?} on a thread {:?}. This is not allowed. Aborting.", self.type_name, self.origin_thread_id, std::thread::current().id() ); } // TODO: Handle no_std non-send. // Currently, no_std is single-threaded only, so this is safe to ignore. // To support no_std multithreading, an alternative will be required. // Remove the #[expect] attribute above when this is addressed. } } /// Returns true if the resource is populated. #[inline] pub fn is_present(&self) -> bool { self.is_present } /// Returns a reference to the resource, if it exists. /// /// # Panics /// If `SEND` is false, this will panic if a value is present and is not accessed from the /// original thread it was inserted from. #[inline] pub fn get_data(&self) -> Option<Ptr<'_>> { self.is_present().then(|| { self.validate_access(); // SAFETY: We've already checked if a value is present, and there should only be one. unsafe { self.data.get_unchecked(Self::ROW) } }) } /// Returns a reference to the resource's change ticks, if it exists. #[inline] pub fn get_ticks(&self) -> Option<ComponentTicks> { // SAFETY: This is being fetched through a read-only reference to Self, so no other mutable references // to the ticks can exist. unsafe { self.is_present().then(|| ComponentTicks { added: self.added_ticks.read(), changed: self.changed_ticks.read(), }) } } /// Returns references to the resource and its change ticks, if it exists. /// /// # Panics /// If `SEND` is false, this will panic if a value is present and is not accessed from the /// original thread it was inserted in. #[inline] pub(crate) fn get_with_ticks(&self) -> Option<(Ptr<'_>, ComponentTickCells<'_>)> { self.is_present().then(|| { self.validate_access(); ( // SAFETY: We've already checked if a value is present, and there should only be one. unsafe { self.data.get_unchecked(Self::ROW) }, ComponentTickCells { added: &self.added_ticks, changed: &self.changed_ticks, changed_by: self.changed_by.as_ref(), }, ) }) } /// Returns a mutable reference to the resource, if it exists. /// /// # Panics /// If `SEND` is false, this will panic if a value is present and is not accessed from the /// original thread it was inserted in. pub(crate) fn get_mut(&mut self, last_run: Tick, this_run: Tick) -> Option<MutUntyped<'_>> { let (ptr, ticks) = self.get_with_ticks()?; Some(MutUntyped { // SAFETY: We have exclusive access to the underlying storage. value: unsafe { ptr.assert_unique() }, // SAFETY: We have exclusive access to the underlying storage. ticks: unsafe { ComponentTicksMut::from_tick_cells(ticks, last_run, this_run) }, }) } /// Inserts a value into the resource. If a value is already present /// it will be replaced. /// /// # Panics /// If `SEND` is false, this will panic if a value is present and is not replaced from /// the original thread it was inserted in. /// /// # Safety /// - `value` must be valid for the underlying type for the resource. #[inline] pub(crate) unsafe fn insert( &mut self, value: OwningPtr<'_>, change_tick: Tick, caller: MaybeLocation, ) { if self.is_present() { self.validate_access(); // SAFETY: The caller ensures that the provided value is valid for the underlying type and // is properly initialized. We've ensured that a value is already present and previously // initialized. unsafe { self.data.replace_unchecked(Self::ROW, value) }; } else { #[cfg(feature = "std")] if !SEND { self.origin_thread_id = Some(std::thread::current().id()); } // SAFETY: // - There is only one element, and it's always allocated. // - The caller guarantees must be valid for the underlying type and thus its // layout must be identical. // - The value was previously not present and thus must not have been initialized. unsafe { self.data.initialize_unchecked(Self::ROW, value) }; *self.added_ticks.deref_mut() = change_tick; self.is_present = true; } *self.changed_ticks.deref_mut() = change_tick; self.changed_by .as_ref() .map(|changed_by| changed_by.deref_mut()) .assign(caller); } /// Inserts a value into the resource with a pre-existing change tick. If a /// value is already present it will be replaced. /// /// # Panics /// If `SEND` is false, this will panic if a value is present and is not replaced from /// the original thread it was inserted in. /// /// # Safety /// - `value` must be valid for the underlying type for the resource. #[inline] pub(crate) unsafe fn insert_with_ticks( &mut self, value: OwningPtr<'_>, change_ticks: ComponentTicks, caller: MaybeLocation, ) { if self.is_present() { self.validate_access(); // SAFETY: The caller ensures that the provided value is valid for the underlying type and // is properly initialized. We've ensured that a value is already present and previously // initialized. unsafe { self.data.replace_unchecked(Self::ROW, value) }; } else { #[cfg(feature = "std")] if !SEND { self.origin_thread_id = Some(std::thread::current().id()); } // SAFETY: // - There is only one element, and it's always allocated. // - The caller guarantees must be valid for the underlying type and thus its // layout must be identical. // - The value was previously not present and thus must not have been initialized. unsafe { self.data.initialize_unchecked(Self::ROW, value) }; self.is_present = true; } *self.added_ticks.deref_mut() = change_ticks.added; *self.changed_ticks.deref_mut() = change_ticks.changed; self.changed_by .as_ref() .map(|changed_by| changed_by.deref_mut()) .assign(caller); } /// Removes a value from the resource, if present. /// /// # Panics /// If `SEND` is false, this will panic if a value is present and is not removed from the /// original thread it was inserted from. #[inline] #[must_use = "The returned pointer to the removed component should be used or dropped"] pub(crate) fn remove(&mut self) -> Option<(OwningPtr<'_>, ComponentTicks, MaybeLocation)> { if !self.is_present() { return None; } if !SEND { self.validate_access(); } self.is_present = false; // SAFETY: // - There is always only one row in the `BlobArray` created during initialization. // - This function has validated that the row is present with the check of `self.is_present`. // - The caller is to take ownership of the value, returned as a `OwningPtr`. let res = unsafe { self.data.get_unchecked_mut(Self::ROW).promote() }; let caller = self .changed_by .as_ref() // SAFETY: This function is being called through an exclusive mutable reference to Self .map(|changed_by| unsafe { *changed_by.deref_mut() }); // SAFETY: This function is being called through an exclusive mutable reference to Self, which // makes it sound to read these ticks. unsafe { Some(( res, ComponentTicks { added: self.added_ticks.read(), changed: self.changed_ticks.read(), }, caller, )) } } /// Removes a value from the resource, if present, and drops it. /// /// # Panics /// If `SEND` is false, this will panic if a value is present and is not /// accessed from the original thread it was inserted in. #[inline] pub(crate) fn remove_and_drop(&mut self) { if self.is_present() { self.validate_access(); // SAFETY: There is only one element, and it's always allocated. unsafe { self.data.drop_last_element(Self::ROW) }; self.is_present = false; } } pub(crate) fn check_change_ticks(&mut self, check: CheckChangeTicks) { self.added_ticks.get_mut().check_tick(check); self.changed_ticks.get_mut().check_tick(check); } } /// The backing store for all [`Resource`]s stored in the [`World`]. /// /// [`Resource`]: crate::resource::Resource /// [`World`]: crate::world::World #[derive(Default)] pub struct Resources<const SEND: bool> { resources: SparseSet<ComponentId, ResourceData<SEND>>, } impl<const SEND: bool> Resources<SEND> { /// The total number of resources stored in the [`World`] /// /// [`World`]: crate::world::World #[inline] pub fn len(&self) -> usize { self.resources.len() } /// Iterate over all resources that have been initialized, i.e. given a [`ComponentId`] pub fn iter(&self) -> impl Iterator<Item = (ComponentId, &ResourceData<SEND>)> { self.resources.iter().map(|(id, data)| (*id, data)) } /// Returns true if there are no resources stored in the [`World`], /// false otherwise. /// /// [`World`]: crate::world::World #[inline] pub fn is_empty(&self) -> bool { self.resources.is_empty() } /// Gets read-only access to a resource, if it exists. #[inline] pub fn get(&self, component_id: ComponentId) -> Option<&ResourceData<SEND>> { self.resources.get(component_id) } /// Clears all resources. #[inline] pub fn clear(&mut self) { self.resources.clear(); } /// Gets mutable access to a resource, if it exists. #[inline] pub(crate) fn get_mut(&mut self, component_id: ComponentId) -> Option<&mut ResourceData<SEND>> { self.resources.get_mut(component_id) } /// Fetches or initializes a new resource and returns back its underlying column. /// /// # Panics /// Will panic if `component_id` is not valid for the provided `components` /// If `SEND` is true, this will panic if `component_id`'s `ComponentInfo` is not registered as being `Send` + `Sync`. pub(crate) fn initialize_with( &mut self, component_id: ComponentId, components: &Components, ) -> &mut ResourceData<SEND> { self.resources.get_or_insert_with(component_id, || { let component_info = components.get_info(component_id).unwrap(); if SEND { assert!( component_info.is_send_and_sync(), "Send + Sync resource {} initialized as non_send. It may have been inserted via World::insert_non_send_resource by accident. Try using World::insert_resource instead.", component_info.name(), ); } // SAFETY: component_info.drop() is valid for the types that will be inserted. let data = unsafe { BlobArray::with_capacity( component_info.layout(), component_info.drop(), 1 ) }; ResourceData { data, is_present: false, added_ticks: UnsafeCell::new(Tick::new(0)), changed_ticks: UnsafeCell::new(Tick::new(0)), type_name: component_info.name(), #[cfg(feature = "std")] origin_thread_id: None, changed_by: MaybeLocation::caller().map(UnsafeCell::new), } }) } pub(crate) fn check_change_ticks(&mut self, check: CheckChangeTicks) { for info in self.resources.values_mut() { info.check_change_ticks(check); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/storage/sparse_set.rs
crates/bevy_ecs/src/storage/sparse_set.rs
use crate::{ change_detection::{CheckChangeTicks, ComponentTickCells, ComponentTicks, MaybeLocation, Tick}, component::{ComponentId, ComponentInfo}, entity::{Entity, EntityIndex}, query::DebugCheckedUnwrap, storage::{AbortOnPanic, Column, TableRow, VecExtensions}, }; use alloc::{boxed::Box, vec::Vec}; use bevy_ptr::{OwningPtr, Ptr}; use core::{cell::UnsafeCell, hash::Hash, marker::PhantomData, num::NonZero, panic::Location}; use nonmax::{NonMaxU32, NonMaxUsize}; #[derive(Debug)] pub(crate) struct SparseArray<I, V = I> { values: Vec<Option<V>>, marker: PhantomData<I>, } /// A space-optimized version of [`SparseArray`] that cannot be changed /// after construction. #[derive(Debug)] pub(crate) struct ImmutableSparseArray<I, V = I> { values: Box<[Option<V>]>, marker: PhantomData<I>, } impl<I: SparseSetIndex, V> Default for SparseArray<I, V> { fn default() -> Self { Self::new() } } impl<I, V> SparseArray<I, V> { #[inline] pub const fn new() -> Self { Self { values: Vec::new(), marker: PhantomData, } } } macro_rules! impl_sparse_array { ($ty:ident) => { impl<I: SparseSetIndex, V> $ty<I, V> { /// Returns `true` if the collection contains a value for the specified `index`. #[inline] pub fn contains(&self, index: I) -> bool { let index = index.sparse_set_index(); self.values.get(index).is_some_and(Option::is_some) } /// Returns a reference to the value at `index`. /// /// Returns `None` if `index` does not have a value or if `index` is out of bounds. #[inline] pub fn get(&self, index: I) -> Option<&V> { let index = index.sparse_set_index(); self.values.get(index).and_then(Option::as_ref) } } }; } impl_sparse_array!(SparseArray); impl_sparse_array!(ImmutableSparseArray); impl<I: SparseSetIndex, V> SparseArray<I, V> { /// Inserts `value` at `index` in the array. /// /// # Panics /// - Panics if the insertion forces a reallocation, and any of the new capacity overflows `isize::MAX` bytes. /// - Panics if the insertion forces a reallocation, and any of the new the reallocations causes an out-of-memory error. /// /// If `index` is out-of-bounds, this will enlarge the buffer to accommodate it. #[inline] pub fn insert(&mut self, index: I, value: V) { let index = index.sparse_set_index(); if index >= self.values.len() { self.values.resize_with(index + 1, || None); } self.values[index] = Some(value); } /// Returns a mutable reference to the value at `index`. /// /// Returns `None` if `index` does not have a value or if `index` is out of bounds. #[inline] pub fn get_mut(&mut self, index: I) -> Option<&mut V> { let index = index.sparse_set_index(); self.values.get_mut(index).and_then(Option::as_mut) } /// Removes and returns the value stored at `index`. /// /// Returns `None` if `index` did not have a value or if `index` is out of bounds. #[inline] pub fn remove(&mut self, index: I) -> Option<V> { let index = index.sparse_set_index(); self.values.get_mut(index).and_then(Option::take) } /// Removes all of the values stored within. pub fn clear(&mut self) { self.values.clear(); } /// Converts the [`SparseArray`] into an immutable variant. pub(crate) fn into_immutable(self) -> ImmutableSparseArray<I, V> { ImmutableSparseArray { values: self.values.into_boxed_slice(), marker: PhantomData, } } } /// A sparse data structure of [`Component`](crate::component::Component)s. /// /// Designed for relatively fast insertions and deletions. #[derive(Debug)] pub struct ComponentSparseSet { /// Capacity and length match those of `entities`. dense: Column, // Internally this only relies on the Entity index to keep track of where the component data is // stored for entities that are alive. The generation is not required, but is stored // in debug builds to validate that access is correct. #[cfg(not(debug_assertions))] entities: Vec<EntityIndex>, #[cfg(debug_assertions)] entities: Vec<Entity>, sparse: SparseArray<EntityIndex, TableRow>, } impl ComponentSparseSet { /// Creates a new [`ComponentSparseSet`] with a given component type layout and /// initial `capacity`. pub(crate) fn new(component_info: &ComponentInfo, capacity: usize) -> Self { let entities = Vec::with_capacity(capacity); Self { dense: Column::with_capacity(component_info, entities.capacity()), entities, sparse: Default::default(), } } /// Removes all of the values stored within. pub(crate) fn clear(&mut self) { // SAFETY: This is using the size of the ComponentSparseSet. unsafe { self.dense.clear(self.len()) }; self.entities.clear(); self.sparse.clear(); } /// Returns the number of component values in the sparse set. #[inline] pub fn len(&self) -> usize { self.entities.len() } /// Returns `true` if the sparse set contains no component values. #[inline] pub fn is_empty(&self) -> bool { self.entities.is_empty() } /// Inserts the `entity` key and component `value` pair into this sparse /// set. /// /// # Aborts /// - Aborts the process if the insertion forces a reallocation, and any of the new capacity overflows `isize::MAX` bytes. /// - Aborts the process if the insertion forces a reallocation, and any of the new the reallocations causes an out-of-memory error. /// /// # Safety /// The `value` pointer must point to a valid address that matches the [`Layout`](std::alloc::Layout) /// inside the [`ComponentInfo`] given when constructing this sparse set. pub(crate) unsafe fn insert( &mut self, entity: Entity, value: OwningPtr<'_>, change_tick: Tick, caller: MaybeLocation, ) { if let Some(&dense_index) = self.sparse.get(entity.index()) { #[cfg(debug_assertions)] assert_eq!(entity, self.entities[dense_index.index()]); self.dense.replace(dense_index, value, change_tick, caller); } else { let dense_index = self.entities.len(); let capacity = self.entities.capacity(); #[cfg(not(debug_assertions))] self.entities.push(entity.index()); #[cfg(debug_assertions)] self.entities.push(entity); // If any of the following operations panic due to an allocation error, the state // of the `ComponentSparseSet` will be left in an invalid state and potentially cause UB. // We create an AbortOnPanic guard to force panics to terminate the process if this occurs. let _guard = AbortOnPanic; if capacity != self.entities.capacity() { // SAFETY: An entity was just pushed onto `entities`, its capacity cannot be zero. let new_capacity = unsafe { NonZero::new_unchecked(self.entities.capacity()) }; if let Some(capacity) = NonZero::new(capacity) { // SAFETY: This is using the capacity of the previous allocation. unsafe { self.dense.realloc(capacity, new_capacity) }; } else { self.dense.alloc(new_capacity); } } // SAFETY: This entity index does not exist here yet, so there are no duplicates, // and the entity index is `NonMaxU32` so the length must not be max either. let table_row = unsafe { TableRow::new(NonMaxU32::new_unchecked(dense_index as u32)) }; self.dense.initialize(table_row, value, change_tick, caller); self.sparse.insert(entity.index(), table_row); core::mem::forget(_guard); } } /// Returns `true` if the sparse set has a component value for the provided `entity`. #[inline] pub fn contains(&self, entity: Entity) -> bool { #[cfg(debug_assertions)] { if let Some(&dense_index) = self.sparse.get(entity.index()) { #[cfg(debug_assertions)] assert_eq!(entity, self.entities[dense_index.index()]); true } else { false } } #[cfg(not(debug_assertions))] self.sparse.contains(entity.index()) } /// Returns a reference to the entity's component value. /// /// Returns `None` if `entity` does not have a component in the sparse set. #[inline] pub fn get(&self, entity: Entity) -> Option<Ptr<'_>> { self.sparse.get(entity.index()).map(|&dense_index| { #[cfg(debug_assertions)] assert_eq!(entity, self.entities[dense_index.index()]); // SAFETY: if the sparse index points to something in the dense vec, it exists unsafe { self.dense.get_data_unchecked(dense_index) } }) } /// Returns references to the entity's component value and its added and changed ticks. /// /// Returns `None` if `entity` does not have a component in the sparse set. #[inline] pub fn get_with_ticks(&self, entity: Entity) -> Option<(Ptr<'_>, ComponentTickCells<'_>)> { let dense_index = *self.sparse.get(entity.index())?; #[cfg(debug_assertions)] assert_eq!(entity, self.entities[dense_index.index()]); // SAFETY: if the sparse index points to something in the dense vec, it exists unsafe { Some(( self.dense.get_data_unchecked(dense_index), ComponentTickCells { added: self.dense.get_added_tick_unchecked(dense_index), changed: self.dense.get_changed_tick_unchecked(dense_index), changed_by: self.dense.get_changed_by_unchecked(dense_index), }, )) } } /// Returns a reference to the "added" tick of the entity's component value. /// /// Returns `None` if `entity` does not have a component in the sparse set. #[inline] pub fn get_added_tick(&self, entity: Entity) -> Option<&UnsafeCell<Tick>> { let dense_index = *self.sparse.get(entity.index())?; #[cfg(debug_assertions)] assert_eq!(entity, self.entities[dense_index.index()]); // SAFETY: if the sparse index points to something in the dense vec, it exists unsafe { Some(self.dense.get_added_tick_unchecked(dense_index)) } } /// Returns a reference to the "changed" tick of the entity's component value. /// /// Returns `None` if `entity` does not have a component in the sparse set. #[inline] pub fn get_changed_tick(&self, entity: Entity) -> Option<&UnsafeCell<Tick>> { let dense_index = *self.sparse.get(entity.index())?; #[cfg(debug_assertions)] assert_eq!(entity, self.entities[dense_index.index()]); // SAFETY: if the sparse index points to something in the dense vec, it exists unsafe { Some(self.dense.get_changed_tick_unchecked(dense_index)) } } /// Returns a reference to the "added" and "changed" ticks of the entity's component value. /// /// Returns `None` if `entity` does not have a component in the sparse set. #[inline] pub fn get_ticks(&self, entity: Entity) -> Option<ComponentTicks> { let dense_index = *self.sparse.get(entity.index())?; #[cfg(debug_assertions)] assert_eq!(entity, self.entities[dense_index.index()]); // SAFETY: if the sparse index points to something in the dense vec, it exists unsafe { Some(self.dense.get_ticks_unchecked(dense_index)) } } /// Returns a reference to the calling location that last changed the entity's component value. /// /// Returns `None` if `entity` does not have a component in the sparse set. #[inline] pub fn get_changed_by( &self, entity: Entity, ) -> MaybeLocation<Option<&UnsafeCell<&'static Location<'static>>>> { MaybeLocation::new_with_flattened(|| { let dense_index = *self.sparse.get(entity.index())?; #[cfg(debug_assertions)] assert_eq!(entity, self.entities[dense_index.index()]); // SAFETY: if the sparse index points to something in the dense vec, it exists unsafe { Some(self.dense.get_changed_by_unchecked(dense_index)) } }) } /// Returns the drop function for the component type stored in the sparse set, /// or `None` if it doesn't need to be dropped. #[inline] pub fn get_drop(&self) -> Option<unsafe fn(OwningPtr<'_>)> { self.dense.get_drop() } /// Removes the `entity` from this sparse set and returns a pointer to the associated value (if /// it exists). #[must_use = "The returned pointer must be used to drop the removed component."] pub(crate) fn remove_and_forget(&mut self, entity: Entity) -> Option<OwningPtr<'_>> { self.sparse.remove(entity.index()).map(|dense_index| { #[cfg(debug_assertions)] assert_eq!(entity, self.entities[dense_index.index()]); let last = self.entities.len() - 1; if dense_index.index() >= last { #[cfg(debug_assertions)] assert_eq!(dense_index.index(), last); // SAFETY: This is strictly decreasing the length, so it cannot outgrow // it also cannot underflow as an item was just removed from the sparse array. unsafe { self.entities.set_len(last) }; // SAFETY: `last` is guaranteed to be the last element in `dense` as the length is synced with // the `entities` store. unsafe { self.dense .get_data_unchecked(dense_index) .assert_unique() .promote() } } else { // SAFETY: The above check ensures that `dense_index` and the last element are not // overlapping, and thus also within bounds. unsafe { self.entities .swap_remove_nonoverlapping_unchecked(dense_index.index()); }; // SAFETY: The above check ensures that `dense_index` is in bounds. let swapped_entity = unsafe { self.entities.get_unchecked(dense_index.index()) }; #[cfg(not(debug_assertions))] let index = *swapped_entity; #[cfg(debug_assertions)] let index = swapped_entity.index(); // SAFETY: The swapped entity was just fetched from the entity Vec, it must have already // been inserted and in bounds. unsafe { *self.sparse.get_mut(index).debug_checked_unwrap() = dense_index; } // SAFETY: The above check ensures that `dense_index` and the last element are not // overlapping, and thus also within bounds. unsafe { self.dense .swap_remove_and_forget_unchecked_nonoverlapping(last, dense_index) } } }) } /// Removes (and drops) the entity's component value from the sparse set. /// /// Returns `true` if `entity` had a component value in the sparse set. pub(crate) fn remove(&mut self, entity: Entity) -> bool { self.sparse .remove(entity.index()) .map(|dense_index| { #[cfg(debug_assertions)] assert_eq!(entity, self.entities[dense_index.index()]); let last = self.entities.len() - 1; if dense_index.index() >= last { #[cfg(debug_assertions)] assert_eq!(dense_index.index(), last); // SAFETY: This is strictly decreasing the length, so it cannot outgrow // it also cannot underflow as an item was just removed from the sparse array. unsafe { self.entities.set_len(last) }; // SAFETY: `last` is guaranteed to be the last element in `dense` as the length is synced with // the `entities` store. unsafe { self.dense.drop_last_component(last) }; } else { // SAFETY: The above check ensures that `dense_index` and the last element are not // overlapping, and thus also within bounds. unsafe { self.entities .swap_remove_nonoverlapping_unchecked(dense_index.index()); }; let swapped_entity = // SAFETY: The above check ensures that `dense_index` is in bounds. unsafe { self.entities.get_unchecked(dense_index.index()) }; #[cfg(not(debug_assertions))] let index = *swapped_entity; #[cfg(debug_assertions)] let index = swapped_entity.index(); // SAFETY: The swapped entity was just fetched from the entity Vec, it must have already // been inserted and in bounds. unsafe { *self.sparse.get_mut(index).debug_checked_unwrap() = dense_index; } // SAFETY: The above check ensures that `dense_index` and the last element are not // overlapping, and thus also within bounds. unsafe { self.dense .swap_remove_and_drop_unchecked_nonoverlapping(last, dense_index); } } }) .is_some() } pub(crate) fn check_change_ticks(&mut self, check: CheckChangeTicks) { // SAFETY: This is using the valid size of the column. unsafe { self.dense.check_change_ticks(self.len(), check) }; } } impl Drop for ComponentSparseSet { fn drop(&mut self) { let len = self.entities.len(); self.entities.clear(); // SAFETY: `cap` and `len` are correct. `dense` is never accessed again after this call. unsafe { self.dense.drop(self.entities.capacity(), len); } } } /// A data structure that blends dense and sparse storage /// /// `I` is the type of the indices, while `V` is the type of data stored in the dense storage. #[derive(Debug)] pub struct SparseSet<I, V: 'static> { dense: Vec<V>, indices: Vec<I>, sparse: SparseArray<I, NonMaxUsize>, } /// A space-optimized version of [`SparseSet`] that cannot be changed /// after construction. #[derive(Debug)] pub(crate) struct ImmutableSparseSet<I, V: 'static> { dense: Box<[V]>, indices: Box<[I]>, sparse: ImmutableSparseArray<I, NonMaxUsize>, } macro_rules! impl_sparse_set { ($ty:ident) => { impl<I: SparseSetIndex, V> $ty<I, V> { /// Returns the number of elements in the sparse set. #[inline] pub fn len(&self) -> usize { self.dense.len() } /// Returns `true` if the sparse set contains a value for `index`. #[inline] pub fn contains(&self, index: I) -> bool { self.sparse.contains(index) } /// Returns a reference to the value for `index`. /// /// Returns `None` if `index` does not have a value in the sparse set. pub fn get(&self, index: I) -> Option<&V> { self.sparse.get(index).map(|dense_index| { // SAFETY: if the sparse index points to something in the dense vec, it exists unsafe { self.dense.get_unchecked(dense_index.get()) } }) } /// Returns a mutable reference to the value for `index`. /// /// Returns `None` if `index` does not have a value in the sparse set. pub fn get_mut(&mut self, index: I) -> Option<&mut V> { let dense = &mut self.dense; self.sparse.get(index).map(move |dense_index| { // SAFETY: if the sparse index points to something in the dense vec, it exists unsafe { dense.get_unchecked_mut(dense_index.get()) } }) } /// Returns an iterator visiting all keys (indices) in arbitrary order. pub fn indices(&self) -> &[I] { &self.indices } /// Returns an iterator visiting all values in arbitrary order. pub fn values(&self) -> impl Iterator<Item = &V> { self.dense.iter() } /// Returns an iterator visiting all values mutably in arbitrary order. pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> { self.dense.iter_mut() } /// Returns an iterator visiting all key-value pairs in arbitrary order, with references to the values. pub fn iter(&self) -> impl Iterator<Item = (&I, &V)> { self.indices.iter().zip(self.dense.iter()) } /// Returns an iterator visiting all key-value pairs in arbitrary order, with mutable references to the values. pub fn iter_mut(&mut self) -> impl Iterator<Item = (&I, &mut V)> { self.indices.iter().zip(self.dense.iter_mut()) } } }; } impl_sparse_set!(SparseSet); impl_sparse_set!(ImmutableSparseSet); impl<I: SparseSetIndex, V> Default for SparseSet<I, V> { fn default() -> Self { Self::new() } } impl<I, V> SparseSet<I, V> { /// Creates a new [`SparseSet`]. pub const fn new() -> Self { Self { dense: Vec::new(), indices: Vec::new(), sparse: SparseArray::new(), } } } impl<I: SparseSetIndex, V> SparseSet<I, V> { /// Creates a new [`SparseSet`] with a specified initial capacity. /// /// # Panics /// - Panics if the new capacity of the allocation overflows `isize::MAX` bytes. /// - Panics if the new allocation causes an out-of-memory error. pub fn with_capacity(capacity: usize) -> Self { Self { dense: Vec::with_capacity(capacity), indices: Vec::with_capacity(capacity), sparse: Default::default(), } } /// Returns the total number of elements the [`SparseSet`] can hold without needing to reallocate. #[inline] pub fn capacity(&self) -> usize { self.dense.capacity() } /// Inserts `value` at `index`. /// /// If a value was already present at `index`, it will be overwritten. /// /// # Panics /// - Panics if the insertion forces an reallocation and the new capacity overflows `isize::MAX` bytes. /// - Panics if the insertion forces an reallocation and causes an out-of-memory error. pub fn insert(&mut self, index: I, value: V) { if let Some(dense_index) = self.sparse.get(index.clone()).cloned() { // SAFETY: dense indices stored in self.sparse always exist unsafe { *self.dense.get_unchecked_mut(dense_index.get()) = value; } } else { self.sparse .insert(index.clone(), NonMaxUsize::new(self.dense.len()).unwrap()); self.indices.push(index); self.dense.push(value); } } /// Returns a reference to the value for `index`, inserting one computed from `func` /// if not already present. /// /// # Panics /// - Panics if the insertion forces an reallocation and the new capacity overflows `isize::MAX` bytes. /// - Panics if the insertion forces an reallocation and causes an out-of-memory error. pub fn get_or_insert_with(&mut self, index: I, func: impl FnOnce() -> V) -> &mut V { if let Some(dense_index) = self.sparse.get(index.clone()).cloned() { // SAFETY: dense indices stored in self.sparse always exist unsafe { self.dense.get_unchecked_mut(dense_index.get()) } } else { let value = func(); let dense_index = self.dense.len(); self.sparse .insert(index.clone(), NonMaxUsize::new(dense_index).unwrap()); self.indices.push(index); self.dense.push(value); // SAFETY: dense index was just populated above unsafe { self.dense.get_unchecked_mut(dense_index) } } } /// Returns `true` if the sparse set contains no elements. #[inline] pub fn is_empty(&self) -> bool { self.dense.len() == 0 } /// Removes and returns the value for `index`. /// /// Returns `None` if `index` does not have a value in the sparse set. pub fn remove(&mut self, index: I) -> Option<V> { self.sparse.remove(index).map(|dense_index| { let index = dense_index.get(); let is_last = index == self.dense.len() - 1; let value = self.dense.swap_remove(index); self.indices.swap_remove(index); if !is_last { let swapped_index = self.indices[index].clone(); *self.sparse.get_mut(swapped_index).unwrap() = dense_index; } value }) } /// Clears all of the elements from the sparse set. /// /// # Panics /// - Panics if any of the keys or values implements [`Drop`] and any of those panic. pub fn clear(&mut self) { self.dense.clear(); self.indices.clear(); self.sparse.clear(); } /// Converts the sparse set into its immutable variant. pub(crate) fn into_immutable(self) -> ImmutableSparseSet<I, V> { ImmutableSparseSet { dense: self.dense.into_boxed_slice(), indices: self.indices.into_boxed_slice(), sparse: self.sparse.into_immutable(), } } } /// Represents something that can be stored in a [`SparseSet`] as an integer. /// /// Ideally, the `usize` values should be very small (ie: incremented starting from /// zero), as the number of bits needed to represent a `SparseSetIndex` in a `FixedBitSet` /// is proportional to the **value** of those `usize`. pub trait SparseSetIndex: Clone + PartialEq + Eq + Hash { /// Gets the sparse set index corresponding to this instance. fn sparse_set_index(&self) -> usize; /// Creates a new instance of this type with the specified index. fn get_sparse_set_index(value: usize) -> Self; } macro_rules! impl_sparse_set_index { ($($ty:ty),+) => { $(impl SparseSetIndex for $ty { #[inline] fn sparse_set_index(&self) -> usize { *self as usize } #[inline] fn get_sparse_set_index(value: usize) -> Self { value as $ty } })* }; } impl_sparse_set_index!(u8, u16, u32, u64, usize); /// A collection of [`ComponentSparseSet`] storages, indexed by [`ComponentId`] /// /// Can be accessed via [`Storages`](crate::storage::Storages) #[derive(Default)] pub struct SparseSets { sets: SparseSet<ComponentId, ComponentSparseSet>, } impl SparseSets { /// Returns the number of [`ComponentSparseSet`]s this collection contains. #[inline] pub fn len(&self) -> usize { self.sets.len() } /// Returns true if this collection contains no [`ComponentSparseSet`]s. #[inline] pub fn is_empty(&self) -> bool { self.sets.is_empty() } /// An Iterator visiting all ([`ComponentId`], [`ComponentSparseSet`]) pairs. /// NOTE: Order is not guaranteed. pub fn iter(&self) -> impl Iterator<Item = (ComponentId, &ComponentSparseSet)> { self.sets.iter().map(|(id, data)| (*id, data)) } /// Gets a reference to the [`ComponentSparseSet`] of a [`ComponentId`]. This may be `None` if the component has never been spawned. #[inline] pub fn get(&self, component_id: ComponentId) -> Option<&ComponentSparseSet> { self.sets.get(component_id) } /// Gets a mutable reference of [`ComponentSparseSet`] of a [`ComponentInfo`]. /// Create a new [`ComponentSparseSet`] if not exists. /// /// # Panics /// - Panics if the insertion forces an reallocation and the new capacity overflows `isize::MAX` bytes. /// - Panics if the insertion forces an reallocation and causes an out-of-memory error. pub(crate) fn get_or_insert( &mut self, component_info: &ComponentInfo, ) -> &mut ComponentSparseSet { if !self.sets.contains(component_info.id()) { self.sets.insert( component_info.id(), ComponentSparseSet::new(component_info, 64), ); } self.sets.get_mut(component_info.id()).unwrap() } /// Gets a mutable reference to the [`ComponentSparseSet`] of a [`ComponentId`]. This may be `None` if the component has never been spawned. pub(crate) fn get_mut(&mut self, component_id: ComponentId) -> Option<&mut ComponentSparseSet> { self.sets.get_mut(component_id) } /// Clear entities stored in each [`ComponentSparseSet`] /// /// # Panics /// - Panics if any of the components stored within implement [`Drop`] and any of them panic. pub(crate) fn clear_entities(&mut self) { for set in self.sets.values_mut() { set.clear(); } } pub(crate) fn check_change_ticks(&mut self, check: CheckChangeTicks) { for set in self.sets.values_mut() { set.check_change_ticks(check); } } } #[cfg(test)] mod tests { use super::SparseSets; use crate::{ component::{Component, ComponentDescriptor, ComponentId, ComponentInfo}, entity::{Entity, EntityIndex}, storage::SparseSet, }; use alloc::{vec, vec::Vec}; #[derive(Debug, Eq, PartialEq)] struct Foo(usize); #[test] fn sparse_set() { let mut set = SparseSet::<Entity, Foo>::default(); let e0 = Entity::from_index(EntityIndex::from_raw_u32(0).unwrap()); let e1 = Entity::from_index(EntityIndex::from_raw_u32(1).unwrap()); let e2 = Entity::from_index(EntityIndex::from_raw_u32(2).unwrap()); let e3 = Entity::from_index(EntityIndex::from_raw_u32(3).unwrap()); let e4 = Entity::from_index(EntityIndex::from_raw_u32(4).unwrap()); set.insert(e1, Foo(1)); set.insert(e2, Foo(2)); set.insert(e3, Foo(3)); assert_eq!(set.get(e0), None); assert_eq!(set.get(e1), Some(&Foo(1))); assert_eq!(set.get(e2), Some(&Foo(2))); assert_eq!(set.get(e3), Some(&Foo(3))); assert_eq!(set.get(e4), None); { let iter_results = set.values().collect::<Vec<_>>(); assert_eq!(iter_results, vec![&Foo(1), &Foo(2), &Foo(3)]); } assert_eq!(set.remove(e2), Some(Foo(2))); assert_eq!(set.remove(e2), None); assert_eq!(set.get(e0), None); assert_eq!(set.get(e1), Some(&Foo(1))); assert_eq!(set.get(e2), None); assert_eq!(set.get(e3), Some(&Foo(3))); assert_eq!(set.get(e4), None); assert_eq!(set.remove(e1), Some(Foo(1))); assert_eq!(set.get(e0), None); assert_eq!(set.get(e1), None); assert_eq!(set.get(e2), None); assert_eq!(set.get(e3), Some(&Foo(3))); assert_eq!(set.get(e4), None); set.insert(e1, Foo(10)); assert_eq!(set.get(e1), Some(&Foo(10))); *set.get_mut(e1).unwrap() = Foo(11); assert_eq!(set.get(e1), Some(&Foo(11))); } #[test] fn sparse_sets() { let mut sets = SparseSets::default(); #[derive(Component, Default, Debug)] struct TestComponent1; #[derive(Component, Default, Debug)] struct TestComponent2; assert_eq!(sets.len(), 0); assert!(sets.is_empty()); register_component::<TestComponent1>(&mut sets, 1); assert_eq!(sets.len(), 1); register_component::<TestComponent2>(&mut sets, 2); assert_eq!(sets.len(), 2);
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/storage/blob_array.rs
crates/bevy_ecs/src/storage/blob_array.rs
use alloc::alloc::handle_alloc_error; use bevy_ptr::{OwningPtr, Ptr, PtrMut}; use bevy_utils::OnDrop; use core::{alloc::Layout, cell::UnsafeCell, num::NonZeroUsize, ptr::NonNull}; /// A flat, type-erased data storage type. /// /// Used to densely store homogeneous ECS data. A blob is usually just an arbitrary block of contiguous memory without any identity, and /// could be used to represent any arbitrary data (i.e. string, arrays, etc). This type only stores meta-data about the blob that it stores, /// and a pointer to the location of the start of the array, similar to a C-style `void*` array. /// /// This type is reliant on its owning type to store the capacity and length information. #[derive(Debug)] pub(super) struct BlobArray { item_layout: Layout, // the `data` ptr's layout is always `array_layout(item_layout, capacity)` data: NonNull<u8>, // None if the underlying type doesn't need to be dropped pub drop: Option<unsafe fn(OwningPtr<'_>)>, #[cfg(debug_assertions)] capacity: usize, } impl BlobArray { /// Create a new [`BlobArray`] with a specified `capacity`. /// If `capacity` is 0, no allocations will be made. /// /// `drop` is an optional function pointer that is meant to be invoked when any element in the [`BlobArray`] /// should be dropped. For all Rust-based types, this should match 1:1 with the implementation of [`Drop`] /// if present, and should be `None` if `T: !Drop`. For non-Rust based types, this should match any cleanup /// processes typically associated with the stored element. /// /// # Safety /// `drop` should be safe to call with an [`OwningPtr`] pointing to any item that's been placed into this [`BlobArray`]. /// If `drop` is `None`, the items will be leaked. This should generally be set as None based on [`needs_drop`]. /// /// [`needs_drop`]: std::mem::needs_drop pub unsafe fn with_capacity( item_layout: Layout, drop_fn: Option<unsafe fn(OwningPtr<'_>)>, capacity: usize, ) -> Self { if capacity == 0 { let align = NonZeroUsize::new(item_layout.align()).expect("alignment must be > 0"); // Create a dangling pointer with the given alignment. let data = NonNull::without_provenance(align); Self { item_layout, drop: drop_fn, data, #[cfg(debug_assertions)] capacity, } } else { // SAFETY: Upheld by caller let mut arr = unsafe { Self::with_capacity(item_layout, drop_fn, 0) }; // SAFETY: `capacity` > 0 unsafe { arr.alloc(NonZeroUsize::new_unchecked(capacity)) } arr } } /// Returns the [`Layout`] of the element type stored in the vector. #[inline] pub fn layout(&self) -> Layout { self.item_layout } /// Return `true` if this [`BlobArray`] stores `ZSTs`. pub fn is_zst(&self) -> bool { self.item_layout.size() == 0 } /// Returns the drop function for values stored in the vector, /// or `None` if they don't need to be dropped. #[inline] pub fn get_drop(&self) -> Option<unsafe fn(OwningPtr<'_>)> { self.drop } /// Returns a reference to the element at `index`, without doing bounds checking. /// /// *`len` refers to the length of the array, the number of elements that have been initialized, and are safe to read. /// Just like [`Vec::len`].* /// /// # Safety /// - The element at index `index` is safe to access. /// (If the safety requirements of every method that has been used on `Self` have been fulfilled, the caller just needs to ensure that `index` < `len`) /// /// [`Vec::len`]: alloc::vec::Vec::len #[inline] pub unsafe fn get_unchecked(&self, index: usize) -> Ptr<'_> { #[cfg(debug_assertions)] debug_assert!(index < self.capacity); let size = self.item_layout.size(); // SAFETY: // - The caller ensures that `index` fits in this array, // so this operation will not overflow the original allocation. // - `size` is a multiple of the erased type's alignment, // so adding a multiple of `size` will preserve alignment. unsafe { self.get_ptr().byte_add(index * size) } } /// Returns a mutable reference to the element at `index`, without doing bounds checking. /// /// *`len` refers to the length of the array, the number of elements that have been initialized, and are safe to read. /// Just like [`Vec::len`].* /// /// # Safety /// - The element with at index `index` is safe to access. /// (If the safety requirements of every method that has been used on `Self` have been fulfilled, the caller just needs to ensure that `index` < `len`) /// /// [`Vec::len`]: alloc::vec::Vec::len #[inline] pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> PtrMut<'_> { #[cfg(debug_assertions)] debug_assert!(index < self.capacity); let size = self.item_layout.size(); // SAFETY: // - The caller ensures that `index` fits in this vector, // so this operation will not overflow the original allocation. // - `size` is a multiple of the erased type's alignment, // so adding a multiple of `size` will preserve alignment. unsafe { self.get_ptr_mut().byte_add(index * size) } } /// Gets a [`Ptr`] to the start of the array #[inline] pub fn get_ptr(&self) -> Ptr<'_> { // SAFETY: the inner data will remain valid for as long as 'self. unsafe { Ptr::new(self.data) } } /// Gets a [`PtrMut`] to the start of the array #[inline] pub fn get_ptr_mut(&mut self) -> PtrMut<'_> { // SAFETY: the inner data will remain valid for as long as 'self. unsafe { PtrMut::new(self.data) } } /// Get a slice of the first `slice_len` elements in [`BlobArray`] as if it were an array with elements of type `T` /// To get a slice to the entire array, the caller must plug `len` in `slice_len`. /// /// *`len` refers to the length of the array, the number of elements that have been initialized, and are safe to read. /// Just like [`Vec::len`].* /// /// # Safety /// - The type `T` must be the type of the items in this [`BlobArray`]. /// - `slice_len` <= `len` /// /// [`Vec::len`]: alloc::vec::Vec::len pub unsafe fn get_sub_slice<T>(&self, slice_len: usize) -> &[UnsafeCell<T>] { #[cfg(debug_assertions)] debug_assert!(slice_len <= self.capacity); // SAFETY: the inner data will remain valid for as long as 'self. unsafe { core::slice::from_raw_parts(self.data.as_ptr() as *const UnsafeCell<T>, slice_len) } } /// Clears the array, i.e. removing (and dropping) all of the elements. /// Note that this method has no effect on the allocated capacity of the vector. /// /// Note that this method will behave exactly the same as [`Vec::clear`]. /// /// # Safety /// - For every element with index `i`, if `i` < `len`: It must be safe to call [`Self::get_unchecked_mut`] with `i`. /// (If the safety requirements of every method that has been used on `Self` have been fulfilled, the caller just needs to ensure that `len` is correct.) /// /// [`Vec::clear`]: alloc::vec::Vec::clear pub unsafe fn clear(&mut self, len: usize) { #[cfg(debug_assertions)] debug_assert!(self.capacity >= len); if let Some(drop) = self.drop { // We set `self.drop` to `None` before dropping elements for unwind safety. This ensures we don't // accidentally drop elements twice in the event of a drop impl panicking. self.drop = None; let size = self.item_layout.size(); for i in 0..len { // SAFETY: // * 0 <= `i` < `len`, so `i * size` must be in bounds for the allocation. // * `size` is a multiple of the erased type's alignment, // so adding a multiple of `size` will preserve alignment. // * The item is left unreachable so it can be safely promoted to an `OwningPtr`. let item = unsafe { self.get_ptr_mut().byte_add(i * size).promote() }; // SAFETY: `item` was obtained from this `BlobArray`, so its underlying type must match `drop`. unsafe { drop(item) }; } self.drop = Some(drop); } } /// Because this method needs parameters, it can't be the implementation of the `Drop` trait. /// The owner of this [`BlobArray`] must call this method with the correct information. /// /// # Safety /// - `cap` and `len` are indeed the capacity and length of this [`BlobArray`] /// - This [`BlobArray`] mustn't be used after calling this method. pub unsafe fn drop(&mut self, cap: usize, len: usize) { #[cfg(debug_assertions)] debug_assert_eq!(self.capacity, cap); if cap != 0 { self.clear(len); if !self.is_zst() { let layout = array_layout(&self.item_layout, cap).expect("array layout should be valid"); alloc::alloc::dealloc(self.data.as_ptr().cast(), layout); } #[cfg(debug_assertions)] { self.capacity = 0; } } } /// Drops the last element in this [`BlobArray`]. /// /// # Safety // - `last_element_index` must correspond to the last element in the array. // - After this method is called, the last element must not be used // unless [`Self::initialize_unchecked`] is called to set the value of the last element. pub unsafe fn drop_last_element(&mut self, last_element_index: usize) { #[cfg(debug_assertions)] debug_assert!(self.capacity > last_element_index); if let Some(drop) = self.drop { // We set `self.drop` to `None` before dropping elements for unwind safety. This ensures we don't // accidentally drop elements twice in the event of a drop impl panicking. self.drop = None; // SAFETY: let item = self.get_unchecked_mut(last_element_index).promote(); // SAFETY: unsafe { drop(item) }; self.drop = Some(drop); } } /// Allocate a block of memory for the array. This should be used to initialize the array, do not use this /// method if there are already elements stored in the array - use [`Self::realloc`] instead. /// /// # Panics /// - Panics if the new capacity overflows `isize::MAX` bytes. /// - Panics if the allocation causes an out-of-memory error. pub(super) fn alloc(&mut self, capacity: NonZeroUsize) { #[cfg(debug_assertions)] debug_assert_eq!(self.capacity, 0); if !self.is_zst() { let new_layout = array_layout(&self.item_layout, capacity.get()) .expect("array layout should be valid"); // SAFETY: layout has non-zero size because capacity > 0, and the blob isn't ZST (`self.is_zst` == false) let new_data = unsafe { alloc::alloc::alloc(new_layout) }; self.data = NonNull::new(new_data).unwrap_or_else(|| handle_alloc_error(new_layout)); } #[cfg(debug_assertions)] { self.capacity = capacity.into(); } } /// Reallocate memory for this array. /// For example, if the length (number of stored elements) reached the capacity (number of elements the current allocation can store), /// you might want to use this method to increase the allocation, so more data can be stored in the array. /// /// # Panics /// - Panics if the new capacity overflows `isize::MAX` bytes. /// - Panics if the allocation causes an out-of-memory error. /// /// # Safety /// - `current_capacity` is indeed the current capacity of this array. /// - After calling this method, the caller must update their saved capacity to reflect the change. pub(super) unsafe fn realloc( &mut self, current_capacity: NonZeroUsize, new_capacity: NonZeroUsize, ) { #[cfg(debug_assertions)] debug_assert_eq!(self.capacity, current_capacity.get()); if !self.is_zst() { let new_layout = array_layout(&self.item_layout, new_capacity.get()) .expect("array layout should be valid"); // SAFETY: // - ptr was be allocated via this allocator // - the layout used to previously allocate this array is equivalent to `array_layout(&self.item_layout, current_capacity.get())` // - `item_layout.size() > 0` (`self.is_zst`==false) and `new_capacity > 0`, so the layout size is non-zero // - "new_size, when rounded up to the nearest multiple of layout.align(), must not overflow (i.e., the rounded value must be less than usize::MAX)", // since the item size is always a multiple of its align, the rounding cannot happen // here and the overflow is handled in `array_layout` let new_data = unsafe { alloc::alloc::realloc( self.get_ptr_mut().as_ptr(), // SAFETY: This is the Layout of the current array, it must be valid, if it hadn't have been, there would have been a panic on a previous allocation array_layout_unchecked(&self.item_layout, current_capacity.get()), new_layout.size(), ) }; self.data = NonNull::new(new_data).unwrap_or_else(|| handle_alloc_error(new_layout)); } #[cfg(debug_assertions)] { self.capacity = new_capacity.into(); } } /// Initializes the value at `index` to `value`. This function does not do any bounds checking. /// /// # Safety /// - `index` must be in bounds (`index` < capacity) /// - The [`Layout`] of the value must match the layout of the blobs stored in this array, /// and it must be safe to use the `drop` function of this [`BlobArray`] to drop `value`. /// - `value` must not point to the same value that is being initialized. #[inline] pub unsafe fn initialize_unchecked(&mut self, index: usize, value: OwningPtr<'_>) { #[cfg(debug_assertions)] debug_assert!(self.capacity > index); let size = self.item_layout.size(); let dst = self.get_unchecked_mut(index); core::ptr::copy::<u8>(value.as_ptr(), dst.as_ptr(), size); } /// Replaces the value at `index` with `value`. This function does not do any bounds checking. /// /// # Safety /// - Index must be in-bounds (`index` < `len`) /// - `value`'s [`Layout`] must match this [`BlobArray`]'s `item_layout`, /// and it must be safe to use the `drop` function of this [`BlobArray`] to drop `value`. /// - `value` must not point to the same value that is being replaced. pub unsafe fn replace_unchecked(&mut self, index: usize, value: OwningPtr<'_>) { #[cfg(debug_assertions)] debug_assert!(self.capacity > index); // Pointer to the value in the vector that will get replaced. // SAFETY: The caller ensures that `index` fits in this vector. let destination = NonNull::from(unsafe { self.get_unchecked_mut(index) }); let source = value.as_ptr(); if let Some(drop) = self.drop { // We set `self.drop` to `None` before dropping elements for unwind safety. This ensures we don't // accidentally drop elements twice in the event of a drop impl panicking. self.drop = None; // Transfer ownership of the old value out of the vector, so it can be dropped. // SAFETY: // - `destination` was obtained from a `PtrMut` in this vector, which ensures it is non-null, // well-aligned for the underlying type, and has proper provenance. // - The storage location will get overwritten with `value` later, which ensures // that the element will not get observed or double dropped later. // - If a panic occurs, `self.len` will remain `0`, which ensures a double-drop // does not occur. Instead, all elements will be forgotten. let old_value = unsafe { OwningPtr::new(destination) }; // This closure will run in case `drop()` panics, // which ensures that `value` does not get forgotten. let on_unwind = OnDrop::new(|| drop(value)); drop(old_value); // If the above code does not panic, make sure that `value` doesn't get dropped. core::mem::forget(on_unwind); self.drop = Some(drop); } // Copy the new value into the vector, overwriting the previous value. // SAFETY: // - `source` and `destination` were obtained from `OwningPtr`s, which ensures they are // valid for both reads and writes. // - The value behind `source` will only be dropped if the above branch panics, // so it must still be initialized and it is safe to transfer ownership into the vector. // - `source` and `destination` were obtained from different memory locations, // both of which we have exclusive access to, so they are guaranteed not to overlap. unsafe { core::ptr::copy_nonoverlapping::<u8>( source, destination.as_ptr(), self.item_layout.size(), ); } } /// This method will swap two elements in the array, and return the one at `index_to_remove`. /// It is the caller's responsibility to drop the returned pointer, if that is desirable. /// /// # Safety /// - `index_to_keep` must be safe to access (within the bounds of the length of the array). /// - `index_to_remove` must be safe to access (within the bounds of the length of the array). /// - `index_to_remove` != `index_to_keep` /// - The caller should address the inconsistent state of the array that has occurred after the swap, either: /// 1) initialize a different value in `index_to_keep` /// 2) update the saved length of the array if `index_to_keep` was the last element. #[inline] #[must_use = "The returned pointer should be used to drop the removed element"] pub unsafe fn swap_remove_unchecked( &mut self, index_to_remove: usize, index_to_keep: usize, ) -> OwningPtr<'_> { #[cfg(debug_assertions)] { debug_assert!(self.capacity > index_to_keep); debug_assert!(self.capacity > index_to_remove); } if index_to_remove != index_to_keep { return self.swap_remove_unchecked_nonoverlapping(index_to_remove, index_to_keep); } // Now the element that used to be in index `index_to_remove` is now in index `index_to_keep` (after swap) // If we are storing ZSTs than the index doesn't actually matter because the size is 0. self.get_unchecked_mut(index_to_keep).promote() } /// The same as [`Self::swap_remove_unchecked`] but the two elements must non-overlapping. /// /// # Safety /// - `index_to_keep` must be safe to access (within the bounds of the length of the array). /// - `index_to_remove` must be safe to access (within the bounds of the length of the array). /// - `index_to_remove` != `index_to_keep` /// - The caller should address the inconsistent state of the array that has occurred after the swap, either: /// 1) initialize a different value in `index_to_keep` /// 2) update the saved length of the array if `index_to_keep` was the last element. #[inline] pub unsafe fn swap_remove_unchecked_nonoverlapping( &mut self, index_to_remove: usize, index_to_keep: usize, ) -> OwningPtr<'_> { #[cfg(debug_assertions)] { debug_assert!(self.capacity > index_to_keep); debug_assert!(self.capacity > index_to_remove); debug_assert_ne!(index_to_keep, index_to_remove); } debug_assert_ne!(index_to_keep, index_to_remove); core::ptr::swap_nonoverlapping::<u8>( self.get_unchecked_mut(index_to_keep).as_ptr(), self.get_unchecked_mut(index_to_remove).as_ptr(), self.item_layout.size(), ); // Now the element that used to be in index `index_to_remove` is now in index `index_to_keep` (after swap) // If we are storing ZSTs than the index doesn't actually matter because the size is 0. self.get_unchecked_mut(index_to_keep).promote() } /// This method will call [`Self::swap_remove_unchecked`] and drop the result. /// /// # Safety /// - `index_to_keep` must be safe to access (within the bounds of the length of the array). /// - `index_to_remove` must be safe to access (within the bounds of the length of the array). /// - `index_to_remove` != `index_to_keep` /// - The caller should address the inconsistent state of the array that has occurred after the swap, either: /// 1) initialize a different value in `index_to_keep` /// 2) update the saved length of the array if `index_to_keep` was the last element. #[inline] pub unsafe fn swap_remove_and_drop_unchecked( &mut self, index_to_remove: usize, index_to_keep: usize, ) { #[cfg(debug_assertions)] { debug_assert!(self.capacity > index_to_keep); debug_assert!(self.capacity > index_to_remove); } let drop = self.drop; let value = self.swap_remove_unchecked(index_to_remove, index_to_keep); if let Some(drop) = drop { drop(value); } } /// The same as [`Self::swap_remove_and_drop_unchecked`] but the two elements must non-overlapping. /// /// # Safety /// - `index_to_keep` must be safe to access (within the bounds of the length of the array). /// - `index_to_remove` must be safe to access (within the bounds of the length of the array). /// - `index_to_remove` != `index_to_keep` /// - The caller should address the inconsistent state of the array that has occurred after the swap, either: /// 1) initialize a different value in `index_to_keep` /// 2) update the saved length of the array if `index_to_keep` was the last element. #[inline] pub unsafe fn swap_remove_and_drop_unchecked_nonoverlapping( &mut self, index_to_remove: usize, index_to_keep: usize, ) { #[cfg(debug_assertions)] { debug_assert!(self.capacity > index_to_keep); debug_assert!(self.capacity > index_to_remove); debug_assert_ne!(index_to_keep, index_to_remove); } let drop = self.drop; let value = self.swap_remove_unchecked_nonoverlapping(index_to_remove, index_to_keep); if let Some(drop) = drop { drop(value); } } } /// From <https://doc.rust-lang.org/beta/src/core/alloc/layout.rs.html> pub(super) fn array_layout(layout: &Layout, n: usize) -> Option<Layout> { let (array_layout, offset) = repeat_layout(layout, n)?; debug_assert_eq!(layout.size(), offset); Some(array_layout) } // TODO: replace with `Layout::repeat` if/when it stabilizes /// From <https://doc.rust-lang.org/beta/src/core/alloc/layout.rs.html> fn repeat_layout(layout: &Layout, n: usize) -> Option<(Layout, usize)> { // This cannot overflow. Quoting from the invariant of Layout: // > `size`, when rounded up to the nearest multiple of `align`, // > must not overflow (i.e., the rounded value must be less than // > `usize::MAX`) let padded_size = layout.size() + padding_needed_for(layout, layout.align()); let alloc_size = padded_size.checked_mul(n)?; // SAFETY: self.align is already known to be valid and alloc_size has been // padded already. unsafe { Some(( Layout::from_size_align_unchecked(alloc_size, layout.align()), padded_size, )) } } /// From <https://doc.rust-lang.org/beta/src/core/alloc/layout.rs.html> /// # Safety /// The caller must ensure that: /// - The resulting [`Layout`] is valid, by ensuring that `(layout.size() + padding_needed_for(layout, layout.align())) * n` doesn't overflow. pub(super) unsafe fn array_layout_unchecked(layout: &Layout, n: usize) -> Layout { let (array_layout, offset) = repeat_layout_unchecked(layout, n); debug_assert_eq!(layout.size(), offset); array_layout } // TODO: replace with `Layout::repeat` if/when it stabilizes /// From <https://doc.rust-lang.org/beta/src/core/alloc/layout.rs.html> /// # Safety /// The caller must ensure that: /// - The resulting [`Layout`] is valid, by ensuring that `(layout.size() + padding_needed_for(layout, layout.align())) * n` doesn't overflow. unsafe fn repeat_layout_unchecked(layout: &Layout, n: usize) -> (Layout, usize) { // This cannot overflow. Quoting from the invariant of Layout: // > `size`, when rounded up to the nearest multiple of `align`, // > must not overflow (i.e., the rounded value must be less than // > `usize::MAX`) let padded_size = layout.size() + padding_needed_for(layout, layout.align()); // This may overflow in release builds, that's why this function is unsafe. let alloc_size = padded_size * n; // SAFETY: self.align is already known to be valid and alloc_size has been // padded already. unsafe { ( Layout::from_size_align_unchecked(alloc_size, layout.align()), padded_size, ) } } /// From <https://doc.rust-lang.org/beta/src/core/alloc/layout.rs.html> const fn padding_needed_for(layout: &Layout, align: usize) -> usize { let len = layout.size(); // Rounded up value is: // len_rounded_up = (len + align - 1) & !(align - 1); // and then we return the padding difference: `len_rounded_up - len`. // // We use modular arithmetic throughout: // // 1. align is guaranteed to be > 0, so align - 1 is always // valid. // // 2. `len + align - 1` can overflow by at most `align - 1`, // so the &-mask with `!(align - 1)` will ensure that in the // case of overflow, `len_rounded_up` will itself be 0. // Thus the returned padding, when added to `len`, yields 0, // which trivially satisfies the alignment `align`. // // (Of course, attempts to allocate blocks of memory whose // size and padding overflow in the above manner should cause // the allocator to yield an error anyway.) let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1); len_rounded_up.wrapping_sub(len) } #[cfg(test)] mod tests { use bevy_ecs::prelude::*; #[derive(Component)] struct PanicOnDrop; impl Drop for PanicOnDrop { fn drop(&mut self) { panic!("PanicOnDrop is being Dropped"); } } #[test] #[should_panic(expected = "PanicOnDrop is being Dropped")] fn make_sure_zst_components_get_dropped() { let mut world = World::new(); world.spawn(PanicOnDrop); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/storage/thin_array_ptr.rs
crates/bevy_ecs/src/storage/thin_array_ptr.rs
use crate::query::DebugCheckedUnwrap; use alloc::alloc::{alloc, handle_alloc_error, realloc}; use core::{ alloc::Layout, mem::{needs_drop, size_of}, num::NonZeroUsize, ptr::{self, NonNull}, }; /// Similar to [`Vec<T>`], but with the capacity and length cut out for performance reasons. /// /// This type can be treated as a `ManuallyDrop<Box<[T]>>` without a built in length. To avoid /// memory leaks, [`drop`](Self::drop) must be called when no longer in use. /// /// [`Vec<T>`]: alloc::vec::Vec #[derive(Debug)] pub struct ThinArrayPtr<T> { data: NonNull<T>, #[cfg(debug_assertions)] capacity: usize, } impl<T> ThinArrayPtr<T> { fn empty() -> Self { Self { data: NonNull::dangling(), #[cfg(debug_assertions)] capacity: 0, } } #[inline(always)] fn set_capacity(&mut self, _capacity: usize) { #[cfg(debug_assertions)] { self.capacity = _capacity; } } /// Create a new [`ThinArrayPtr`] with a given capacity. If the `capacity` is 0, this will no allocate any memory. /// /// # Panics /// - Panics if the new capacity overflows `isize::MAX` bytes. /// - Panics if the allocation causes an out-of-memory error. #[inline] pub fn with_capacity(capacity: usize) -> Self { let mut arr = Self::empty(); if capacity > 0 { // SAFETY: // - The `current_capacity` is 0 because it was just created unsafe { arr.alloc(NonZeroUsize::new_unchecked(capacity)) }; } arr } /// Allocate memory for the array, this should only be used if not previous allocation has been made (capacity = 0) /// The caller should update their saved `capacity` value to reflect the fact that it was changed /// /// # Panics /// - Panics if the new capacity overflows `isize::MAX` bytes. /// - Panics if the allocation causes an out-of-memory error. /// /// # Panics /// - Panics if the new capacity overflows `usize` pub fn alloc(&mut self, capacity: NonZeroUsize) { self.set_capacity(capacity.get()); if size_of::<T>() != 0 { let new_layout = Layout::array::<T>(capacity.get()) .expect("layout should be valid (arithmetic overflow)"); // SAFETY: // - layout has non-zero size, `capacity` > 0, `size` > 0 (`size_of::<T>() != 0`) self.data = NonNull::new(unsafe { alloc(new_layout) }) .unwrap_or_else(|| handle_alloc_error(new_layout)) .cast(); } } /// Reallocate memory for the array, this should only be used if a previous allocation for this array has been made (capacity > 0). /// /// # Panics /// - Panics if the new capacity overflows `isize::MAX` bytes /// - Panics if the allocation causes an out-of-memory error. /// /// # Safety /// - The current capacity is indeed greater than 0 /// - The caller should update their saved `capacity` value to reflect the fact that it was changed pub unsafe fn realloc(&mut self, current_capacity: NonZeroUsize, new_capacity: NonZeroUsize) { #[cfg(debug_assertions)] assert_eq!(self.capacity, current_capacity.get()); self.set_capacity(new_capacity.get()); if size_of::<T>() != 0 { let new_layout = Layout::array::<T>(new_capacity.get()).expect("overflow while allocating memory"); // SAFETY: // - ptr was be allocated via this allocator // - the layout of the array is the same as `Layout::array::<T>(current_capacity)` // - the size of `T` is non 0, and `new_capacity` > 0 // - "new_size, when rounded up to the nearest multiple of layout.align(), must not overflow (i.e., the rounded value must be less than usize::MAX)", // since the item size is always a multiple of its align, the rounding cannot happen // here and the overflow is handled in `Layout::array` self.data = NonNull::new(unsafe { realloc( self.data.cast().as_ptr(), // We can use `unwrap_unchecked` because this is the Layout of the current allocation, it must be valid Layout::array::<T>(current_capacity.get()).debug_checked_unwrap(), new_layout.size(), ) }) .unwrap_or_else(|| handle_alloc_error(new_layout)) .cast(); } } /// Initializes the value at `index` to `value`. This function does not do any bounds checking. /// /// # Safety /// `index` must be in bounds i.e. within the `capacity`. /// if `index` = `len` the caller should update their saved `len` value to reflect the fact that it was changed #[inline] pub unsafe fn initialize_unchecked(&mut self, index: usize, value: T) { // SAFETY: // - `self.data` and the resulting pointer are in the same allocated object // - the memory address of the last element doesn't overflow `isize`, so if `index` is in bounds, it won't overflow either let ptr = unsafe { self.data.as_ptr().add(index) }; // SAFETY: `index` is in bounds, therefore the pointer to that location in the array is valid, and aligned. unsafe { ptr::write(ptr, value) }; } /// Get a reference to the element at `index`. This method doesn't do any bounds checking. /// /// # Safety /// - `index` must be safe to read. #[inline] pub unsafe fn get_unchecked(&self, index: usize) -> &'_ T { // SAFETY: // - `self.data` and the resulting pointer are in the same allocated object // - the memory address of the last element doesn't overflow `isize`, so if `index` is in bounds, it won't overflow either let ptr = unsafe { self.data.as_ptr().add(index) }; // SAFETY: // - The pointer is properly aligned // - It is dereferenceable (all in the same allocation) // - `index` < `len` and the element is safe to write to, so its valid // - We have a reference to self, so no other mutable accesses to the element can occur unsafe { ptr.as_ref() // SAFETY: We can use `unwarp_unchecked` because the pointer isn't null) .debug_checked_unwrap() } } /// Get a mutable reference to the element at `index`. This method doesn't do any bounds checking. /// /// # Safety /// - `index` must be safe to write to. #[inline] pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &'_ mut T { // SAFETY: // - `self.data` and the resulting pointer are in the same allocated object // - the memory address of the last element doesn't overflow `isize`, so if `index` is in bounds, it won't overflow either let ptr = unsafe { self.data.as_ptr().add(index) }; // SAFETY: // - The pointer is properly aligned // - It is dereferenceable (all in the same allocation) // - `index` < `len` and the element is safe to write to, so its valid // - We have a mutable reference to `self` unsafe { ptr.as_mut() // SAFETY: We can use `unwarp_unchecked` because the pointer isn't null) .unwrap_unchecked() } } /// Perform a [`swap-remove`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.swap_remove) and return the removed value. /// /// # Safety /// - `index_to_keep` must be safe to access (within the bounds of the length of the array). /// - `index_to_remove` must be safe to access (within the bounds of the length of the array). /// - `index_to_remove` != `index_to_keep` /// - The caller should address the inconsistent state of the array that has occurred after the swap, either: /// 1) initialize a different value in `index_to_keep` /// 2) update the saved length of the array if `index_to_keep` was the last element. #[inline] pub unsafe fn swap_remove_unchecked_nonoverlapping( &mut self, index_to_remove: usize, index_to_keep: usize, ) -> T { #[cfg(debug_assertions)] { debug_assert!(self.capacity > index_to_keep); debug_assert!(self.capacity > index_to_remove); debug_assert_ne!(index_to_keep, index_to_remove); } let base_ptr = self.data.as_ptr(); let value = ptr::read(base_ptr.add(index_to_remove)); ptr::copy_nonoverlapping( base_ptr.add(index_to_keep), base_ptr.add(index_to_remove), 1, ); value } /// Perform a [`swap-remove`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.swap_remove) and return the removed value. /// /// # Safety /// - `index_to_keep` must be safe to access (within the bounds of the length of the array). /// - `index_to_remove` must be safe to access (within the bounds of the length of the array). /// - `index_to_remove` != `index_to_keep` /// - The caller should address the inconsistent state of the array that has occurred after the swap, either: /// 1) initialize a different value in `index_to_keep` /// 2) update the saved length of the array if `index_to_keep` was the last element. #[inline] pub unsafe fn swap_remove_unchecked( &mut self, index_to_remove: usize, index_to_keep: usize, ) -> T { if index_to_remove != index_to_keep { return self.swap_remove_unchecked_nonoverlapping(index_to_remove, index_to_keep); } ptr::read(self.data.as_ptr().add(index_to_remove)) } /// Get a raw pointer to the last element of the array, return `None` if the length is 0 /// /// # Safety /// - ensure that `current_len` is indeed the len of the array #[inline] unsafe fn last_element(&mut self, current_len: usize) -> Option<*mut T> { (current_len != 0).then_some(self.data.as_ptr().add(current_len - 1)) } /// Clears the array, removing (and dropping) Note that this method has no effect on the allocated capacity of the vector. /// /// # Safety /// - `current_len` is indeed the length of the array /// - The caller should update their saved length value pub unsafe fn clear_elements(&mut self, mut current_len: usize) { if needs_drop::<T>() { while let Some(to_drop) = self.last_element(current_len) { ptr::drop_in_place(to_drop); current_len -= 1; } } } /// Drop the entire array and all its elements. /// /// # Safety /// - `current_len` is indeed the length of the array /// - `current_capacity` is indeed the capacity of the array /// - The caller must not use this `ThinArrayPtr` in any way after calling this function pub unsafe fn drop(&mut self, current_capacity: usize, current_len: usize) { #[cfg(debug_assertions)] assert_eq!(self.capacity, current_capacity); if current_capacity != 0 { self.clear_elements(current_len); let layout = Layout::array::<T>(current_capacity).expect("layout should be valid"); alloc::alloc::dealloc(self.data.as_ptr().cast(), layout); } self.set_capacity(0); } /// Get the [`ThinArrayPtr`] as a slice with a given length. /// /// # Safety /// - `slice_len` must match the actual length of the array #[inline] pub unsafe fn as_slice(&self, slice_len: usize) -> &[T] { // SAFETY: // - the data is valid - allocated with the same allocator // - non-null and well-aligned // - we have a shared reference to self - the data will not be mutated during 'a unsafe { core::slice::from_raw_parts(self.data.as_ptr(), slice_len) } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/storage/mod.rs
crates/bevy_ecs/src/storage/mod.rs
#![expect( unsafe_op_in_unsafe_fn, reason = "See #11590. To be removed once all applicable unsafe code has an unsafe block with a safety comment." )] //! Storage layouts for ECS data. //! //! This module implements the low-level collections that store data in a [`World`]. These all offer minimal and often //! unsafe APIs, and have been made `pub` primarily for debugging and monitoring purposes. //! //! # Fetching Storages //! Each of the below data stores can be fetched via [`Storages`], which can be fetched from a //! [`World`] via [`World::storages`]. It exposes a top level container for each class of storage within //! ECS: //! //! - [`Tables`] - columnar contiguous blocks of memory, optimized for fast iteration. //! - [`SparseSets`] - sparse `HashMap`-like mappings from entities to components, optimized for random //! lookup and regular insertion/removal of components. //! - [`Resources`] - singleton storage for the resources in the world //! //! # Safety //! To avoid trivially unsound use of the APIs in this module, it is explicitly impossible to get a mutable //! reference to [`Storages`] from [`World`], and none of the types publicly expose a mutable interface. //! //! [`World`]: crate::world::World //! [`World::storages`]: crate::world::World::storages mod blob_array; mod resource; mod sparse_set; mod table; mod thin_array_ptr; pub use resource::*; pub use sparse_set::*; pub use table::*; use crate::component::{ComponentInfo, StorageType}; use alloc::vec::Vec; /// The raw data stores of a [`World`](crate::world::World) #[derive(Default)] pub struct Storages { /// Backing storage for [`SparseSet`] components. /// Note that sparse sets are only present for components that have been spawned or have had a relevant bundle registered. pub sparse_sets: SparseSets, /// Backing storage for [`Table`] components. pub tables: Tables, /// Backing storage for resources. pub resources: Resources<true>, /// Backing storage for `!Send` resources. pub non_send_resources: Resources<false>, } impl Storages { /// ensures that the component has its necessary storage initialize. pub fn prepare_component(&mut self, component: &ComponentInfo) { match component.storage_type() { StorageType::Table => { // table needs no preparation } StorageType::SparseSet => { self.sparse_sets.get_or_insert(component); } } } } struct AbortOnPanic; impl Drop for AbortOnPanic { fn drop(&mut self) { // Panicking while unwinding will force an abort. panic!("Aborting due to allocator error"); } } /// Unsafe extension functions for `Vec<T>` trait VecExtensions<T> { /// Removes an element from the vector and returns it. /// /// The removed element is replaced by the last element of the vector. /// /// This does not preserve ordering of the remaining elements, but is O(1). If you need to preserve the element order, use [`remove`] instead. /// /// /// # Safety /// /// All of the following must be true: /// - `self.len() > 1` /// - `index < self.len() - 1` /// /// [`remove`]: alloc::vec::Vec::remove /// [`swap_remove`]: alloc::vec::Vec::swap_remove unsafe fn swap_remove_nonoverlapping_unchecked(&mut self, index: usize) -> T; } impl<T> VecExtensions<T> for Vec<T> { #[inline] unsafe fn swap_remove_nonoverlapping_unchecked(&mut self, index: usize) -> T { // SAFETY: The caller must ensure that the element at `index` must be valid. // This function, and then the caller takes ownership of the value, and it cannot be // accessed due to the length being decremented immediately after this. let value = unsafe { self.as_mut_ptr().add(index).read() }; let len = self.len(); let base_ptr = self.as_mut_ptr(); // SAFETY: We replace self[index] with the last element. The caller must ensure that // both the last element and `index` must be valid and cannot point to the same place. unsafe { core::ptr::copy_nonoverlapping(base_ptr.add(len - 1), base_ptr.add(index), 1) }; // SAFETY: Upheld by caller unsafe { self.set_len(len - 1) }; value } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/storage/table/column.rs
crates/bevy_ecs/src/storage/table/column.rs
use super::*; use crate::{ change_detection::MaybeLocation, storage::{blob_array::BlobArray, thin_array_ptr::ThinArrayPtr}, }; use core::{mem::needs_drop, panic::Location}; /// A type-erased contiguous container for data of a homogeneous type. /// /// Conceptually, a `Column` is very similar to a type-erased `Box<[T]>`. /// It also stores the change detection ticks for its components, kept in two separate /// contiguous buffers internally. An element shares its data across these buffers by using the /// same index (i.e. the entity at row 3 has it's data at index 3 and its change detection ticks at index 3). /// /// Like many other low-level storage types, `Column` has a limited and highly unsafe /// interface. It's highly advised to use higher level types and their safe abstractions /// instead of working directly with `Column`. /// /// For performance reasons, `Column` does not does not store it's capacity and length. /// This type is used by [`Table`] and [`ComponentSparseSet`], where the corresponding capacity /// and length can be found. /// /// [`ComponentSparseSet`]: crate::storage::ComponentSparseSet #[derive(Debug)] pub struct Column { pub(super) data: BlobArray, pub(super) added_ticks: ThinArrayPtr<UnsafeCell<Tick>>, pub(super) changed_ticks: ThinArrayPtr<UnsafeCell<Tick>>, pub(super) changed_by: MaybeLocation<ThinArrayPtr<UnsafeCell<&'static Location<'static>>>>, } impl Column { /// Create a new [`Column`] with the given `capacity`. pub fn with_capacity(component_info: &ComponentInfo, capacity: usize) -> Self { Self { // SAFETY: The components stored in this columns will match the information in `component_info` data: unsafe { BlobArray::with_capacity(component_info.layout(), component_info.drop(), capacity) }, added_ticks: ThinArrayPtr::with_capacity(capacity), changed_ticks: ThinArrayPtr::with_capacity(capacity), changed_by: MaybeLocation::new_with(|| ThinArrayPtr::with_capacity(capacity)), } } /// Swap-remove and drop the removed element, but the component at `row` must not be the last element. /// /// # Safety /// - `row.as_usize()` < `len` /// - `last_element_index` = `len - 1` /// - `last_element_index` != `row.as_usize()` /// - The caller should update the `len` to `len - 1`, or immediately initialize another element in the `last_element_index` pub(crate) unsafe fn swap_remove_and_drop_unchecked_nonoverlapping( &mut self, last_element_index: usize, row: TableRow, ) { self.data .swap_remove_and_drop_unchecked_nonoverlapping(row.index(), last_element_index); self.added_ticks .swap_remove_unchecked_nonoverlapping(row.index(), last_element_index); self.changed_ticks .swap_remove_unchecked_nonoverlapping(row.index(), last_element_index); self.changed_by.as_mut().map(|changed_by| { changed_by.swap_remove_unchecked_nonoverlapping(row.index(), last_element_index); }); } /// Swap-remove and drop the removed element. /// /// # Safety /// - `last_element_index` must be the index of the last element—stored in the highest place in memory. /// - `row.as_usize()` <= `last_element_index` /// - The caller should update their saved length to reflect the change (decrement it by 1). pub(crate) unsafe fn swap_remove_and_drop_unchecked( &mut self, last_element_index: usize, row: TableRow, ) { self.data .swap_remove_and_drop_unchecked(row.index(), last_element_index); self.added_ticks .swap_remove_unchecked(row.index(), last_element_index); self.changed_ticks .swap_remove_unchecked(row.index(), last_element_index); self.changed_by.as_mut().map(|changed_by| { changed_by.swap_remove_unchecked(row.index(), last_element_index); }); } /// Swap-remove and forgets the removed element, but the component at `row` must not be the last element. /// /// # Safety /// - `row.as_usize()` < `len` /// - `last_element_index` = `len - 1` /// - `last_element_index` != `row.as_usize()` /// - The caller should update the `len` to `len - 1`, or immediately initialize another element in the `last_element_index` pub(crate) unsafe fn swap_remove_and_forget_unchecked_nonoverlapping( &mut self, last_element_index: usize, row: TableRow, ) -> OwningPtr<'_> { let data = self .data .swap_remove_unchecked_nonoverlapping(row.index(), last_element_index); self.added_ticks .swap_remove_unchecked_nonoverlapping(row.index(), last_element_index); self.changed_ticks .swap_remove_unchecked_nonoverlapping(row.index(), last_element_index); self.changed_by.as_mut().map(|changed_by| { changed_by.swap_remove_unchecked_nonoverlapping(row.index(), last_element_index); }); data } /// Swap-remove and forget the removed element. /// /// # Safety /// - `last_element_index` must be the index of the last element—stored in the highest place in memory. /// - `row.as_usize()` <= `last_element_index` /// - The caller should update their saved length to reflect the change (decrement it by 1). pub(crate) unsafe fn swap_remove_and_forget_unchecked( &mut self, last_element_index: usize, row: TableRow, ) -> OwningPtr<'_> { let data = self .data .swap_remove_unchecked(row.index(), last_element_index); self.added_ticks .swap_remove_unchecked(row.index(), last_element_index); self.changed_ticks .swap_remove_unchecked(row.index(), last_element_index); self.changed_by .as_mut() .map(|changed_by| changed_by.swap_remove_unchecked(row.index(), last_element_index)); data } /// Call [`realloc`](std::alloc::realloc) to expand / shrink the memory allocation for this [`Column`] /// /// # Panics /// - Panics if the any of the new capacity overflows `isize::MAX` bytes. /// - Panics if the any of the reallocations causes an out-of-memory error. /// /// # Safety /// - `current_capacity` must be the current capacity of this column (the capacity of `self.data`, `self.added_ticks`, `self.changed_tick`) /// - The caller should make sure their saved `capacity` value is updated to `new_capacity` after this operation. pub(crate) unsafe fn realloc( &mut self, current_capacity: NonZeroUsize, new_capacity: NonZeroUsize, ) { self.data.realloc(current_capacity, new_capacity); self.added_ticks.realloc(current_capacity, new_capacity); self.changed_ticks.realloc(current_capacity, new_capacity); self.changed_by .as_mut() .map(|changed_by| changed_by.realloc(current_capacity, new_capacity)); } /// Call [`alloc`](std::alloc::alloc) to allocate memory for this [`Column`] /// The caller should make sure their saved `capacity` value is updated to `new_capacity` after this operation. /// /// # Panics /// - Panics if the any of the new capacity overflows `isize::MAX` bytes. /// - Panics if the any of the allocations causes an out-of-memory error. pub(crate) fn alloc(&mut self, new_capacity: NonZeroUsize) { self.data.alloc(new_capacity); self.added_ticks.alloc(new_capacity); self.changed_ticks.alloc(new_capacity); self.changed_by .as_mut() .map(|changed_by| changed_by.alloc(new_capacity)); } /// Writes component data to the column at the given row. /// Assumes the slot is uninitialized, drop is not called. /// To overwrite existing initialized value, use [`Self::replace`] instead. /// /// # Safety /// - `row.as_usize()` must be in bounds. /// - `comp_ptr` holds a component that matches the `component_id` #[inline] pub(crate) unsafe fn initialize( &mut self, row: TableRow, data: OwningPtr<'_>, tick: Tick, caller: MaybeLocation, ) { self.data.initialize_unchecked(row.index(), data); *self.added_ticks.get_unchecked_mut(row.index()).get_mut() = tick; *self.changed_ticks.get_unchecked_mut(row.index()).get_mut() = tick; self.changed_by .as_mut() .map(|changed_by| changed_by.get_unchecked_mut(row.index()).get_mut()) .assign(caller); } /// Overwrites component data to the column at given row. The previous value is dropped. /// /// # Safety /// - There must be a valid initialized value stored at `row`. /// - `row.as_usize()` must be in bounds. /// - `data` holds a component that matches the `component_id` #[inline] pub(crate) unsafe fn replace( &mut self, row: TableRow, data: OwningPtr<'_>, change_tick: Tick, caller: MaybeLocation, ) { self.data.replace_unchecked(row.index(), data); *self.changed_ticks.get_unchecked_mut(row.index()).get_mut() = change_tick; self.changed_by .as_mut() .map(|changed_by| changed_by.get_unchecked_mut(row.index()).get_mut()) .assign(caller); } /// Removes the element from `other` at `src_row` and inserts it /// into the current column to initialize the values at `dst_row`. /// Does not do any bounds checking. /// /// # Safety /// - `other` must have the same data layout as `self` /// - `src_row` must be in bounds for `other` /// - `dst_row` must be in bounds for `self` /// - `other[src_row]` must be initialized to a valid value. /// - `self[dst_row]` must not be initialized yet. #[inline] pub(crate) unsafe fn initialize_from_unchecked( &mut self, other: &mut Column, other_last_element_index: usize, src_row: TableRow, dst_row: TableRow, ) { debug_assert!(self.data.layout() == other.data.layout()); // Init the data let src_val = other .data .swap_remove_unchecked(src_row.index(), other_last_element_index); self.data.initialize_unchecked(dst_row.index(), src_val); // Init added_ticks let added_tick = other .added_ticks .swap_remove_unchecked(src_row.index(), other_last_element_index); self.added_ticks .initialize_unchecked(dst_row.index(), added_tick); // Init changed_ticks let changed_tick = other .changed_ticks .swap_remove_unchecked(src_row.index(), other_last_element_index); self.changed_ticks .initialize_unchecked(dst_row.index(), changed_tick); self.changed_by.as_mut().zip(other.changed_by.as_mut()).map( |(self_changed_by, other_changed_by)| { let changed_by = other_changed_by .swap_remove_unchecked(src_row.index(), other_last_element_index); self_changed_by.initialize_unchecked(dst_row.index(), changed_by); }, ); } /// Call [`Tick::check_tick`] on all of the ticks stored in this column. /// /// # Safety /// `len` is the actual length of this column #[inline] pub(crate) unsafe fn check_change_ticks(&mut self, len: usize, check: CheckChangeTicks) { for i in 0..len { // SAFETY: // - `i` < `len` // we have a mutable reference to `self` unsafe { self.added_ticks.get_unchecked_mut(i) } .get_mut() .check_tick(check); // SAFETY: // - `i` < `len` // we have a mutable reference to `self` unsafe { self.changed_ticks.get_unchecked_mut(i) } .get_mut() .check_tick(check); } } /// Clear all the components from this column. /// /// # Safety /// - `len` must match the actual length of the column /// - The caller must not use the elements this column's data until [`initializing`](Self::initialize) it again (set `len` to 0). pub(crate) unsafe fn clear(&mut self, len: usize) { self.added_ticks.clear_elements(len); self.changed_ticks.clear_elements(len); self.data.clear(len); self.changed_by .as_mut() .map(|changed_by| changed_by.clear_elements(len)); } /// Because this method needs parameters, it can't be the implementation of the `Drop` trait. /// The owner of this [`Column`] must call this method with the correct information. /// /// # Safety /// - `len` is indeed the length of the column /// - `cap` is indeed the capacity of the column /// - the data stored in `self` will never be used again pub(crate) unsafe fn drop(&mut self, cap: usize, len: usize) { self.added_ticks.drop(cap, len); self.changed_ticks.drop(cap, len); self.data.drop(cap, len); self.changed_by .as_mut() .map(|changed_by| changed_by.drop(cap, len)); } /// Drops the last component in this column. /// /// # Safety /// - `last_element_index` is indeed the index of the last element /// - the data stored in `last_element_index` will never be used unless properly initialized again. pub(crate) unsafe fn drop_last_component(&mut self, last_element_index: usize) { const { assert!(!needs_drop::<UnsafeCell<Tick>>()); assert!(!needs_drop::<UnsafeCell<&'static Location<'static>>>()); } self.data.drop_last_element(last_element_index); } /// Get a slice to the data stored in this [`Column`]. /// /// # Safety /// - `T` must match the type of data that's stored in this [`Column`] /// - `len` must match the actual length of this column (number of elements stored) pub unsafe fn get_data_slice<T>(&self, len: usize) -> &[UnsafeCell<T>] { // SAFETY: Upheld by caller unsafe { self.data.get_sub_slice(len) } } /// Get a slice to the added [`ticks`](Tick) in this [`Column`]. /// /// # Safety /// - `len` must match the actual length of this column (number of elements stored) pub unsafe fn get_added_ticks_slice(&self, len: usize) -> &[UnsafeCell<Tick>] { // SAFETY: Upheld by caller unsafe { self.added_ticks.as_slice(len) } } /// Get a slice to the changed [`ticks`](Tick) in this [`Column`]. /// /// # Safety /// - `len` must match the actual length of this column (number of elements stored) pub unsafe fn get_changed_ticks_slice(&self, len: usize) -> &[UnsafeCell<Tick>] { // SAFETY: Upheld by caller unsafe { self.changed_ticks.as_slice(len) } } /// Get a slice to the calling locations that last changed each value in this [`Column`] /// /// # Safety /// - `len` must match the actual length of this column (number of elements stored) pub unsafe fn get_changed_by_slice( &self, len: usize, ) -> MaybeLocation<&[UnsafeCell<&'static Location<'static>>]> { self.changed_by .as_ref() .map(|changed_by| changed_by.as_slice(len)) } /// Fetches a read-only reference to the data at `row`. This does not /// do any bounds checking. /// /// # Safety /// - `row` must be within the range `[0, self.len())`. /// - no other mutable reference to the data of the same row can exist at the same time #[inline] pub unsafe fn get_data_unchecked(&self, row: TableRow) -> Ptr<'_> { self.data.get_unchecked(row.index()) } /// Fetches the calling location that last changed the value at `row`. /// /// This function does not do any bounds checking. /// /// # Safety /// `row` must be within the range `[0, self.len())`. #[inline] pub unsafe fn get_changed_by_unchecked( &self, row: TableRow, ) -> MaybeLocation<&UnsafeCell<&'static Location<'static>>> { self.changed_by .as_ref() .map(|changed_by| changed_by.get_unchecked(row.index())) } /// Fetches the "added" change detection tick for the value at `row`. /// This function does not do any bounds checking. /// /// # Safety /// `row` must be within the range `[0, self.len())`. #[inline] pub unsafe fn get_added_tick_unchecked(&self, row: TableRow) -> &UnsafeCell<Tick> { // SAFETY: Upheld by caller unsafe { self.added_ticks.get_unchecked(row.index()) } } /// Fetches the "changed" change detection tick for the value at `row` /// This function does not do any bounds checking. /// /// # Safety /// `row` must be within the range `[0, self.len())`. #[inline] pub unsafe fn get_changed_tick_unchecked(&self, row: TableRow) -> &UnsafeCell<Tick> { // SAFETY: Upheld by caller unsafe { self.changed_ticks.get_unchecked(row.index()) } } /// Fetches the change detection ticks for the value at `row`. /// This function does not do any bounds checking. /// /// # Safety /// `row` must be within the range `[0, self.len())`. #[inline] pub unsafe fn get_ticks_unchecked(&self, row: TableRow) -> ComponentTicks { ComponentTicks { added: self.added_ticks.get_unchecked(row.index()).read(), changed: self.changed_ticks.get_unchecked(row.index()).read(), } } /// Returns the drop function for elements of the column, /// or `None` if they don't need to be dropped. #[inline] pub fn get_drop(&self) -> Option<unsafe fn(OwningPtr<'_>)> { self.data.get_drop() } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/storage/table/mod.rs
crates/bevy_ecs/src/storage/table/mod.rs
use crate::{ change_detection::{CheckChangeTicks, ComponentTicks, MaybeLocation, Tick}, component::{ComponentId, ComponentInfo, Components}, entity::Entity, query::DebugCheckedUnwrap, storage::{AbortOnPanic, ImmutableSparseSet, SparseSet}, }; use alloc::{boxed::Box, vec, vec::Vec}; use bevy_platform::collections::HashMap; use bevy_ptr::{OwningPtr, Ptr, UnsafeCellDeref}; pub use column::*; use core::{ cell::UnsafeCell, num::NonZeroUsize, ops::{Index, IndexMut}, panic::Location, }; use nonmax::NonMaxU32; mod column; /// An opaque unique ID for a [`Table`] within a [`World`]. /// /// Can be used with [`Tables::get`] to fetch the corresponding /// table. /// /// Each [`Archetype`] always points to a table via [`Archetype::table_id`]. /// Multiple archetypes can point to the same table so long as the components /// stored in the table are identical, but do not share the same sparse set /// components. /// /// [`World`]: crate::world::World /// [`Archetype`]: crate::archetype::Archetype /// [`Archetype::table_id`]: crate::archetype::Archetype::table_id #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct TableId(u32); impl TableId { /// Creates a new [`TableId`]. /// /// `index` *must* be retrieved from calling [`TableId::as_u32`] on a `TableId` you got /// from a table of a given [`World`] or the created ID may be invalid. /// /// [`World`]: crate::world::World #[inline] pub const fn from_u32(index: u32) -> Self { Self(index) } /// Creates a new [`TableId`]. /// /// `index` *must* be retrieved from calling [`TableId::as_usize`] on a `TableId` you got /// from a table of a given [`World`] or the created ID may be invalid. /// /// [`World`]: crate::world::World /// /// # Panics /// /// Will panic if the provided value does not fit within a [`u32`]. #[inline] pub const fn from_usize(index: usize) -> Self { debug_assert!(index as u32 as usize == index); Self(index as u32) } /// Gets the underlying table index from the ID. #[inline] pub const fn as_u32(self) -> u32 { self.0 } /// Gets the underlying table index from the ID. #[inline] pub const fn as_usize(self) -> usize { // usize is at least u32 in Bevy self.0 as usize } /// The [`TableId`] of the [`Table`] without any components. #[inline] pub const fn empty() -> Self { Self(0) } } /// An opaque newtype for rows in [`Table`]s. Specifies a single row in a specific table. /// /// Values of this type are retrievable from [`Archetype::entity_table_row`] and can be /// used alongside [`Archetype::table_id`] to fetch the exact table and row where an /// [`Entity`]'s components are stored. /// /// Values of this type are only valid so long as entities have not moved around. /// Adding and removing components from an entity, or despawning it will invalidate /// potentially any table row in the table the entity was previously stored in. Users /// should *always* fetch the appropriate row from the entity's [`Archetype`] before /// fetching the entity's components. /// /// [`Archetype`]: crate::archetype::Archetype /// [`Archetype::entity_table_row`]: crate::archetype::Archetype::entity_table_row /// [`Archetype::table_id`]: crate::archetype::Archetype::table_id #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(transparent)] pub struct TableRow(NonMaxU32); impl TableRow { /// Creates a [`TableRow`]. #[inline] pub const fn new(index: NonMaxU32) -> Self { Self(index) } /// Gets the index of the row as a [`usize`]. #[inline] pub const fn index(self) -> usize { // usize is at least u32 in Bevy self.0.get() as usize } /// Gets the index of the row as a [`usize`]. #[inline] pub const fn index_u32(self) -> u32 { self.0.get() } } /// A builder type for constructing [`Table`]s. /// /// - Use [`with_capacity`] to initialize the builder. /// - Repeatedly call [`add_column`] to add columns for components. /// - Finalize with [`build`] to get the constructed [`Table`]. /// /// [`with_capacity`]: Self::with_capacity /// [`add_column`]: Self::add_column /// [`build`]: Self::build // // # Safety // The capacity of all columns is determined by that of the `entities` Vec. This means that // it must be the correct capacity to allocate, reallocate, and deallocate all columns. This // means the safety invariant must be enforced even in `TableBuilder`. pub(crate) struct TableBuilder { columns: SparseSet<ComponentId, Column>, entities: Vec<Entity>, } impl TableBuilder { /// Start building a new [`Table`] with a specified `column_capacity` (How many components per column?) and a `capacity` (How many columns?) pub fn with_capacity(capacity: usize, column_capacity: usize) -> Self { Self { columns: SparseSet::with_capacity(column_capacity), entities: Vec::with_capacity(capacity), } } /// Add a new column to the [`Table`]. Specify the component which will be stored in the [`column`](Column) using its [`ComponentId`] #[must_use] pub fn add_column(mut self, component_info: &ComponentInfo) -> Self { self.columns.insert( component_info.id(), Column::with_capacity(component_info, self.entities.capacity()), ); self } /// Build the [`Table`], after this operation the caller wouldn't be able to add more columns. The [`Table`] will be ready to use. #[must_use] pub fn build(self) -> Table { Table { columns: self.columns.into_immutable(), entities: self.entities, } } } /// A column-oriented [structure-of-arrays] based storage for [`Component`]s of entities /// in a [`World`]. /// /// Conceptually, a `Table` can be thought of as a `HashMap<ComponentId, Column>`, where /// each [`Column`] is a type-erased `Vec<T: Component>`. Each row corresponds to a single entity /// (i.e. index 3 in Column A and index 3 in Column B point to different components on the same /// entity). Fetching components from a table involves fetching the associated column for a /// component type (via its [`ComponentId`]), then fetching the entity's row within that column. /// /// [structure-of-arrays]: https://en.wikipedia.org/wiki/AoS_and_SoA#Structure_of_arrays /// [`Component`]: crate::component::Component /// [`World`]: crate::world::World // // # Safety // The capacity of all columns is determined by that of the `entities` Vec. This means that // it must be the correct capacity to allocate, reallocate, and deallocate all columns. This // means the safety invariant must be enforced even in `TableBuilder`. pub struct Table { columns: ImmutableSparseSet<ComponentId, Column>, entities: Vec<Entity>, } impl Table { /// Fetches a read-only slice of the entities stored within the [`Table`]. #[inline] pub fn entities(&self) -> &[Entity] { &self.entities } /// Get the capacity of this table, in entities. /// Note that if an allocation is in process, this might not match the actual capacity of the columns, but it should once the allocation ends. #[inline] pub fn capacity(&self) -> usize { self.entities.capacity() } /// Removes the entity at the given row and returns the entity swapped in to replace it (if an /// entity was swapped in) /// /// # Safety /// `row` must be in-bounds (`row.as_usize()` < `self.len()`) pub(crate) unsafe fn swap_remove_unchecked(&mut self, row: TableRow) -> Option<Entity> { debug_assert!(row.index_u32() < self.entity_count()); let last_element_index = self.entity_count() - 1; if row.index_u32() != last_element_index { // Instead of checking this condition on every `swap_remove` call, we // check it here and use `swap_remove_nonoverlapping`. for col in self.columns.values_mut() { // SAFETY: // - `row` < `len` // - `last_element_index` = `len` - 1 // - `row` != `last_element_index` // - the `len` is kept within `self.entities`, it will update accordingly. unsafe { col.swap_remove_and_drop_unchecked_nonoverlapping( last_element_index as usize, row, ); }; } } else { // If `row.as_usize()` == `last_element_index` than there's no point in removing the component // at `row`, but we still need to drop it. for col in self.columns.values_mut() { col.drop_last_component(last_element_index as usize); } } let is_last = row.index_u32() == last_element_index; self.entities.swap_remove(row.index()); if is_last { None } else { // SAFETY: This was swap removed and was not last, so it must be in bounds. unsafe { Some(*self.entities.get_unchecked(row.index())) } } } /// Moves the `row` column values to `new_table`, for the columns shared between both tables. /// Returns the index of the new row in `new_table` and the entity in this table swapped in /// to replace it (if an entity was swapped in). missing columns will be "forgotten". It is /// the caller's responsibility to drop them. Failure to do so may result in resources not /// being released (i.e. files handles not being released, memory leaks, etc.) /// /// # Panics /// - Panics if the move forces a reallocation, and any of the new capacity overflows `isize::MAX` bytes. /// - Panics if the move forces a reallocation, and any of the new the reallocations causes an out-of-memory error. /// /// # Safety /// - `row` must be in-bounds pub(crate) unsafe fn move_to_and_forget_missing_unchecked( &mut self, row: TableRow, new_table: &mut Table, ) -> TableMoveResult { debug_assert!(row.index_u32() < self.entity_count()); let last_element_index = self.entity_count() - 1; let is_last = row.index_u32() == last_element_index; let new_row = new_table.allocate(self.entities.swap_remove(row.index())); for (component_id, column) in self.columns.iter_mut() { if let Some(new_column) = new_table.get_column_mut(*component_id) { new_column.initialize_from_unchecked( column, last_element_index as usize, row, new_row, ); } else { // It's the caller's responsibility to drop these cases. column.swap_remove_and_forget_unchecked(last_element_index as usize, row); } } TableMoveResult { new_row, swapped_entity: if is_last { None } else { // SAFETY: This was swap removed and was not last, so it must be in bounds. unsafe { Some(*self.entities.get_unchecked(row.index())) } }, } } /// Moves the `row` column values to `new_table`, for the columns shared between both tables. /// Returns the index of the new row in `new_table` and the entity in this table swapped in /// to replace it (if an entity was swapped in). /// /// # Panics /// - Panics if the move forces a reallocation, and any of the new capacity overflows `isize::MAX` bytes. /// - Panics if the move forces a reallocation, and any of the new the reallocations causes an out-of-memory error. /// /// # Safety /// row must be in-bounds pub(crate) unsafe fn move_to_and_drop_missing_unchecked( &mut self, row: TableRow, new_table: &mut Table, ) -> TableMoveResult { debug_assert!(row.index_u32() < self.entity_count()); let last_element_index = self.entity_count() - 1; let is_last = row.index_u32() == last_element_index; let new_row = new_table.allocate(self.entities.swap_remove(row.index())); for (component_id, column) in self.columns.iter_mut() { if let Some(new_column) = new_table.get_column_mut(*component_id) { new_column.initialize_from_unchecked( column, last_element_index as usize, row, new_row, ); } else { column.swap_remove_and_drop_unchecked(last_element_index as usize, row); } } TableMoveResult { new_row, swapped_entity: if is_last { None } else { // SAFETY: This was swap removed and was not last, so it must be in bounds. unsafe { Some(*self.entities.get_unchecked(row.index())) } }, } } /// Moves the `row` column values to `new_table`, for the columns shared between both tables. /// Returns the index of the new row in `new_table` and the entity in this table swapped in /// to replace it (if an entity was swapped in). /// /// # Panics /// - Panics if the move forces a reallocation, and any of the new capacity overflows `isize::MAX` bytes. /// - Panics if the move forces a reallocation, and any of the new the reallocations causes an out-of-memory error. /// /// # Safety /// - `row` must be in-bounds /// - `new_table` must contain every component this table has pub(crate) unsafe fn move_to_superset_unchecked( &mut self, row: TableRow, new_table: &mut Table, ) -> TableMoveResult { debug_assert!(row.index_u32() < self.entity_count()); let last_element_index = self.entity_count() - 1; let is_last = row.index_u32() == last_element_index; let new_row = new_table.allocate(self.entities.swap_remove(row.index())); for (component_id, column) in self.columns.iter_mut() { new_table .get_column_mut(*component_id) .debug_checked_unwrap() .initialize_from_unchecked(column, last_element_index as usize, row, new_row); } TableMoveResult { new_row, swapped_entity: if is_last { None } else { // SAFETY: This was swap removed and was not last, so it must be in bounds. unsafe { Some(*self.entities.get_unchecked(row.index())) } }, } } /// Get the data of the column matching `component_id` as a slice. /// /// # Safety /// `row.as_usize()` < `self.len()` /// - `T` must match the `component_id` pub unsafe fn get_data_slice_for<T>( &self, component_id: ComponentId, ) -> Option<&[UnsafeCell<T>]> { self.get_column(component_id) .map(|col| col.get_data_slice(self.entity_count() as usize)) } /// Get the added ticks of the column matching `component_id` as a slice. pub fn get_added_ticks_slice_for( &self, component_id: ComponentId, ) -> Option<&[UnsafeCell<Tick>]> { self.get_column(component_id) // SAFETY: `self.len()` is guaranteed to be the len of the ticks array .map(|col| unsafe { col.get_added_ticks_slice(self.entity_count() as usize) }) } /// Get the changed ticks of the column matching `component_id` as a slice. pub fn get_changed_ticks_slice_for( &self, component_id: ComponentId, ) -> Option<&[UnsafeCell<Tick>]> { self.get_column(component_id) // SAFETY: `self.len()` is guaranteed to be the len of the ticks array .map(|col| unsafe { col.get_changed_ticks_slice(self.entity_count() as usize) }) } /// Fetches the calling locations that last changed the each component pub fn get_changed_by_slice_for( &self, component_id: ComponentId, ) -> MaybeLocation<Option<&[UnsafeCell<&'static Location<'static>>]>> { MaybeLocation::new_with_flattened(|| { self.get_column(component_id) // SAFETY: `self.len()` is guaranteed to be the len of the locations array .map(|col| unsafe { col.get_changed_by_slice(self.entity_count() as usize) }) }) } /// Get the specific [`change tick`](Tick) of the component matching `component_id` in `row`. pub fn get_changed_tick( &self, component_id: ComponentId, row: TableRow, ) -> Option<&UnsafeCell<Tick>> { (row.index_u32() < self.entity_count()).then_some( // SAFETY: `row.as_usize()` < `len` unsafe { self.get_column(component_id)? .changed_ticks .get_unchecked(row.index()) }, ) } /// Get the specific [`added tick`](Tick) of the component matching `component_id` in `row`. pub fn get_added_tick( &self, component_id: ComponentId, row: TableRow, ) -> Option<&UnsafeCell<Tick>> { (row.index_u32() < self.entity_count()).then_some( // SAFETY: `row.as_usize()` < `len` unsafe { self.get_column(component_id)? .added_ticks .get_unchecked(row.index()) }, ) } /// Get the specific calling location that changed the component matching `component_id` in `row` pub fn get_changed_by( &self, component_id: ComponentId, row: TableRow, ) -> MaybeLocation<Option<&UnsafeCell<&'static Location<'static>>>> { MaybeLocation::new_with_flattened(|| { (row.index_u32() < self.entity_count()).then_some( // SAFETY: `row.as_usize()` < `len` unsafe { self.get_column(component_id)? .changed_by .as_ref() .map(|changed_by| changed_by.get_unchecked(row.index())) }, ) }) } /// Get the [`ComponentTicks`] of the component matching `component_id` in `row`. /// /// # Safety /// - `row.as_usize()` < `self.len()` pub unsafe fn get_ticks_unchecked( &self, component_id: ComponentId, row: TableRow, ) -> Option<ComponentTicks> { self.get_column(component_id).map(|col| ComponentTicks { added: col.added_ticks.get_unchecked(row.index()).read(), changed: col.changed_ticks.get_unchecked(row.index()).read(), }) } /// Fetches a read-only reference to the [`Column`] for a given [`Component`] within the table. /// /// Returns `None` if the corresponding component does not belong to the table. /// /// [`Component`]: crate::component::Component #[inline] pub fn get_column(&self, component_id: ComponentId) -> Option<&Column> { self.columns.get(component_id) } /// Fetches a mutable reference to the [`Column`] for a given [`Component`] within the /// table. /// /// Returns `None` if the corresponding component does not belong to the table. /// /// [`Component`]: crate::component::Component #[inline] pub(crate) fn get_column_mut(&mut self, component_id: ComponentId) -> Option<&mut Column> { self.columns.get_mut(component_id) } /// Checks if the table contains a [`Column`] for a given [`Component`]. /// /// Returns `true` if the column is present, `false` otherwise. /// /// [`Component`]: crate::component::Component #[inline] pub fn has_column(&self, component_id: ComponentId) -> bool { self.columns.contains(component_id) } /// Reserves `additional` elements worth of capacity within the table. pub(crate) fn reserve(&mut self, additional: usize) { if (self.capacity() - self.entity_count() as usize) < additional { let column_cap = self.capacity(); self.entities.reserve(additional); // use entities vector capacity as driving capacity for all related allocations let new_capacity = self.entities.capacity(); if column_cap == 0 { // SAFETY: the current capacity is 0 unsafe { self.alloc_columns(NonZeroUsize::new_unchecked(new_capacity)) }; } else { // SAFETY: // - `column_cap` is indeed the columns' capacity unsafe { self.realloc_columns( NonZeroUsize::new_unchecked(column_cap), NonZeroUsize::new_unchecked(new_capacity), ); }; } } } /// Allocate memory for the columns in the [`Table`] /// /// # Panics /// - Panics if any of the new capacity overflows `isize::MAX` bytes. /// - Panics if any of the new allocations causes an out-of-memory error. /// /// The current capacity of the columns should be 0, if it's not 0, then the previous data will be overwritten and leaked. /// /// # Safety /// The capacity of all columns is determined by that of the `entities` Vec. This means that /// it must be the correct capacity to allocate, reallocate, and deallocate all columns. This /// means the safety invariant must be enforced even in `TableBuilder`. fn alloc_columns(&mut self, new_capacity: NonZeroUsize) { // If any of these allocations trigger an unwind, the wrong capacity will be used while dropping this table - UB. // To avoid this, we use `AbortOnPanic`. If the allocation triggered a panic, the `AbortOnPanic`'s Drop impl will be // called, and abort the program. let _guard = AbortOnPanic; for col in self.columns.values_mut() { col.alloc(new_capacity); } core::mem::forget(_guard); // The allocation was successful, so we don't drop the guard. } /// Reallocate memory for the columns in the [`Table`] /// /// # Panics /// - Panics if any of the new capacities overflows `isize::MAX` bytes. /// - Panics if any of the new reallocations causes an out-of-memory error. /// /// # Safety /// - `current_column_capacity` is indeed the capacity of the columns /// /// The capacity of all columns is determined by that of the `entities` Vec. This means that /// it must be the correct capacity to allocate, reallocate, and deallocate all columns. This /// means the safety invariant must be enforced even in `TableBuilder`. unsafe fn realloc_columns( &mut self, current_column_capacity: NonZeroUsize, new_capacity: NonZeroUsize, ) { // If any of these allocations trigger an unwind, the wrong capacity will be used while dropping this table - UB. // To avoid this, we use `AbortOnPanic`. If the allocation triggered a panic, the `AbortOnPanic`'s Drop impl will be // called, and abort the program. let _guard = AbortOnPanic; // SAFETY: // - There's no overflow // - `current_capacity` is indeed the capacity - safety requirement // - current capacity > 0 for col in self.columns.values_mut() { col.realloc(current_column_capacity, new_capacity); } core::mem::forget(_guard); // The allocation was successful, so we don't drop the guard. } /// Allocates space for a new entity /// /// # Panics /// - Panics if the allocation forces a reallocation and the new capacities overflows `isize::MAX` bytes. /// - Panics if the allocation forces a reallocation and causes an out-of-memory error. /// /// # Safety /// /// The allocated row must be written to immediately with valid values in each column pub(crate) unsafe fn allocate(&mut self, entity: Entity) -> TableRow { self.reserve(1); let len = self.entity_count(); // SAFETY: No entity index may be in more than one table row at once, so there are no duplicates, // and there can not be an entity index of u32::MAX. Therefore, this can not be max either. let row = unsafe { TableRow::new(NonMaxU32::new_unchecked(len)) }; let len = len as usize; self.entities.push(entity); for col in self.columns.values_mut() { col.added_ticks .initialize_unchecked(len, UnsafeCell::new(Tick::new(0))); col.changed_ticks .initialize_unchecked(len, UnsafeCell::new(Tick::new(0))); col.changed_by .as_mut() .zip(MaybeLocation::caller()) .map(|(changed_by, caller)| { changed_by.initialize_unchecked(len, UnsafeCell::new(caller)); }); } row } /// Gets the number of entities currently being stored in the table. #[inline] pub fn entity_count(&self) -> u32 { // No entity may have more than one table row, so there are no duplicates, // and there may only ever be u32::MAX entities, so the length never exceeds u32's capacity. self.entities.len() as u32 } /// Get the drop function for some component that is stored in this table. #[inline] pub fn get_drop_for(&self, component_id: ComponentId) -> Option<unsafe fn(OwningPtr<'_>)> { self.get_column(component_id)?.data.drop } /// Gets the number of components being stored in the table. #[inline] pub fn component_count(&self) -> usize { self.columns.len() } /// Gets the maximum number of entities the table can currently store /// without reallocating the underlying memory. #[inline] pub fn entity_capacity(&self) -> usize { self.entities.capacity() } /// Checks if the [`Table`] is empty or not. /// /// Returns `true` if the table contains no entities, `false` otherwise. #[inline] pub fn is_empty(&self) -> bool { self.entities.is_empty() } /// Call [`Tick::check_tick`] on all of the ticks in the [`Table`] pub(crate) fn check_change_ticks(&mut self, check: CheckChangeTicks) { let len = self.entity_count() as usize; for col in self.columns.values_mut() { // SAFETY: `len` is the actual length of the column unsafe { col.check_change_ticks(len, check) }; } } /// Iterates over the [`Column`]s of the [`Table`]. pub fn iter_columns(&self) -> impl Iterator<Item = &Column> { self.columns.values() } /// Clears all of the stored components in the [`Table`]. /// /// # Panics /// - Panics if any of the components in any of the columns panics while being dropped. pub(crate) fn clear(&mut self) { let len = self.entity_count() as usize; // We must clear the entities first, because in the drop function causes a panic, it will result in a double free of the columns. self.entities.clear(); for column in self.columns.values_mut() { // SAFETY: we defer `self.entities.clear()` until after clearing the columns, // so `self.len()` should match the columns' len unsafe { column.clear(len) }; } } /// Moves component data out of the [`Table`]. /// /// This function leaves the underlying memory unchanged, but the component behind /// returned pointer is semantically owned by the caller and will not be dropped in its original location. /// Caller is responsible to drop component data behind returned pointer. /// /// # Safety /// - This table must hold the component matching `component_id` /// - `row` must be in bounds /// - The row's inconsistent state that happens after taking the component must be resolved—either initialize a new component or remove the row. pub(crate) unsafe fn take_component( &mut self, component_id: ComponentId, row: TableRow, ) -> OwningPtr<'_> { self.get_column_mut(component_id) .debug_checked_unwrap() .data .get_unchecked_mut(row.index()) .promote() } /// Get the component at a given `row`, if the [`Table`] stores components with the given `component_id` /// /// # Safety /// `row.as_usize()` < `self.len()` pub unsafe fn get_component( &self, component_id: ComponentId, row: TableRow, ) -> Option<Ptr<'_>> { self.get_column(component_id) .map(|col| col.data.get_unchecked(row.index())) } } /// A collection of [`Table`] storages, indexed by [`TableId`] /// /// Can be accessed via [`Storages`](crate::storage::Storages) pub struct Tables { tables: Vec<Table>, table_ids: HashMap<Box<[ComponentId]>, TableId>, } impl Default for Tables { fn default() -> Self { let empty_table = TableBuilder::with_capacity(0, 0).build(); Tables { tables: vec![empty_table], table_ids: HashMap::default(), } } } pub(crate) struct TableMoveResult { pub swapped_entity: Option<Entity>, pub new_row: TableRow, } impl Tables { /// Returns the number of [`Table`]s this collection contains #[inline] pub fn len(&self) -> usize { self.tables.len() } /// Returns true if this collection contains no [`Table`]s #[inline] pub fn is_empty(&self) -> bool { self.tables.is_empty() } /// Fetches a [`Table`] by its [`TableId`]. /// /// Returns `None` if `id` is invalid. #[inline] pub fn get(&self, id: TableId) -> Option<&Table> { self.tables.get(id.as_usize()) } /// Fetches mutable references to two different [`Table`]s. /// /// # Panics /// /// Panics if `a` and `b` are equal. #[inline] pub(crate) fn get_2_mut(&mut self, a: TableId, b: TableId) -> (&mut Table, &mut Table) { if a.as_usize() > b.as_usize() { let (b_slice, a_slice) = self.tables.split_at_mut(a.as_usize()); (&mut a_slice[0], &mut b_slice[b.as_usize()]) } else { let (a_slice, b_slice) = self.tables.split_at_mut(b.as_usize()); (&mut a_slice[a.as_usize()], &mut b_slice[0]) } } /// Attempts to fetch a table based on the provided components, /// creating and returning a new [`Table`] if one did not already exist. /// /// # Safety /// `component_ids` must contain components that exist in `components` pub(crate) unsafe fn get_id_or_insert( &mut self, component_ids: &[ComponentId], components: &Components, ) -> TableId { if component_ids.is_empty() { return TableId::empty(); } let tables = &mut self.tables; let (_key, value) = self .table_ids .raw_entry_mut() .from_key(component_ids) .or_insert_with(|| { let mut table = TableBuilder::with_capacity(0, component_ids.len()); for component_id in component_ids { table = table.add_column(components.get_info_unchecked(*component_id)); } tables.push(table.build()); (component_ids.into(), TableId::from_usize(tables.len() - 1)) }); *value } /// Iterates through all of the tables stored within in [`TableId`] order. pub fn iter(&self) -> core::slice::Iter<'_, Table> { self.tables.iter() } /// Clears all data from all [`Table`]s stored within. pub(crate) fn clear(&mut self) { for table in &mut self.tables { table.clear(); } } pub(crate) fn check_change_ticks(&mut self, check: CheckChangeTicks) { for table in &mut self.tables { table.check_change_ticks(check); } } } impl Index<TableId> for Tables { type Output = Table; #[inline] fn index(&self, index: TableId) -> &Self::Output { &self.tables[index.as_usize()] } } impl IndexMut<TableId> for Tables { #[inline] fn index_mut(&mut self, index: TableId) -> &mut Self::Output { &mut self.tables[index.as_usize()] } } impl Drop for Table { fn drop(&mut self) { let len = self.entity_count() as usize; let cap = self.capacity(); self.entities.clear();
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/exclusive_system_param.rs
crates/bevy_ecs/src/system/exclusive_system_param.rs
use crate::{ prelude::{FromWorld, QueryState}, query::{QueryData, QueryFilter}, system::{Local, SystemMeta, SystemParam, SystemState}, world::World, }; use bevy_platform::cell::SyncCell; use core::marker::PhantomData; use variadics_please::all_tuples; /// A parameter that can be used in an exclusive system (a system with an `&mut World` parameter). /// Any parameters implementing this trait must come after the `&mut World` parameter. #[diagnostic::on_unimplemented( message = "`{Self}` can not be used as a parameter for an exclusive system", label = "invalid system parameter" )] pub trait ExclusiveSystemParam: Sized { /// Used to store data which persists across invocations of a system. type State: Send + Sync + 'static; /// The item type returned when constructing this system param. /// See [`SystemParam::Item`]. type Item<'s>: ExclusiveSystemParam<State = Self::State>; /// Creates a new instance of this param's [`State`](Self::State). fn init(world: &mut World, system_meta: &mut SystemMeta) -> Self::State; /// Creates a parameter to be passed into an [`ExclusiveSystemParamFunction`]. /// /// [`ExclusiveSystemParamFunction`]: super::ExclusiveSystemParamFunction fn get_param<'s>(state: &'s mut Self::State, system_meta: &SystemMeta) -> Self::Item<'s>; } /// Shorthand way of accessing the associated type [`ExclusiveSystemParam::Item`] /// for a given [`ExclusiveSystemParam`]. pub type ExclusiveSystemParamItem<'s, P> = <P as ExclusiveSystemParam>::Item<'s>; impl<'a, D: QueryData + 'static, F: QueryFilter + 'static> ExclusiveSystemParam for &'a mut QueryState<D, F> { type State = QueryState<D, F>; type Item<'s> = &'s mut QueryState<D, F>; fn init(world: &mut World, _system_meta: &mut SystemMeta) -> Self::State { QueryState::new(world) } fn get_param<'s>(state: &'s mut Self::State, _system_meta: &SystemMeta) -> Self::Item<'s> { state } } impl<'a, P: SystemParam + 'static> ExclusiveSystemParam for &'a mut SystemState<P> { type State = SystemState<P>; type Item<'s> = &'s mut SystemState<P>; fn init(world: &mut World, _system_meta: &mut SystemMeta) -> Self::State { SystemState::new(world) } fn get_param<'s>(state: &'s mut Self::State, _system_meta: &SystemMeta) -> Self::Item<'s> { state } } impl<'_s, T: FromWorld + Send + 'static> ExclusiveSystemParam for Local<'_s, T> { type State = SyncCell<T>; type Item<'s> = Local<'s, T>; fn init(world: &mut World, _system_meta: &mut SystemMeta) -> Self::State { SyncCell::new(T::from_world(world)) } fn get_param<'s>(state: &'s mut Self::State, _system_meta: &SystemMeta) -> Self::Item<'s> { Local(state.get()) } } impl<S: ?Sized> ExclusiveSystemParam for PhantomData<S> { type State = (); type Item<'s> = PhantomData<S>; fn init(_world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {} fn get_param<'s>(_state: &'s mut Self::State, _system_meta: &SystemMeta) -> Self::Item<'s> { PhantomData } } macro_rules! impl_exclusive_system_param_tuple { ($(#[$meta:meta])* $($param: ident),*) => { #[expect( clippy::allow_attributes, reason = "This is within a macro, and as such, the below lints may not always apply." )] #[allow( non_snake_case, reason = "Certain variable names are provided by the caller, not by us." )] #[allow( unused_variables, reason = "Zero-length tuples won't use any of the parameters." )] #[allow(clippy::unused_unit, reason = "Zero length tuple is unit.")] $(#[$meta])* impl<$($param: ExclusiveSystemParam),*> ExclusiveSystemParam for ($($param,)*) { type State = ($($param::State,)*); type Item<'s> = ($($param::Item<'s>,)*); #[inline] fn init(world: &mut World, system_meta: &mut SystemMeta) -> Self::State { ($($param::init(world, system_meta),)*) } #[inline] fn get_param<'s>( state: &'s mut Self::State, system_meta: &SystemMeta, ) -> Self::Item<'s> { let ($($param,)*) = state; #[allow( clippy::unused_unit, reason = "Zero-length tuples won't have any params to get." )] ($($param::get_param($param, system_meta),)*) } } }; } all_tuples!( #[doc(fake_variadic)] impl_exclusive_system_param_tuple, 0, 16, P ); #[cfg(test)] mod tests { use crate::{schedule::Schedule, system::Local, world::World}; use alloc::vec::Vec; use bevy_ecs_macros::Resource; use core::marker::PhantomData; #[test] fn test_exclusive_system_params() { #[derive(Resource, Default)] struct Res { test_value: u32, } fn my_system(world: &mut World, mut local: Local<u32>, _phantom: PhantomData<Vec<u32>>) { assert_eq!(world.resource::<Res>().test_value, *local); *local += 1; world.resource_mut::<Res>().test_value += 1; } let mut schedule = Schedule::default(); schedule.add_systems(my_system); let mut world = World::default(); world.init_resource::<Res>(); schedule.run(&mut world); schedule.run(&mut world); assert_eq!(2, world.get_resource::<Res>().unwrap().test_value); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/builder.rs
crates/bevy_ecs/src/system/builder.rs
use alloc::{boxed::Box, vec::Vec}; use bevy_platform::cell::SyncCell; use variadics_please::all_tuples; use crate::{ prelude::QueryBuilder, query::{QueryData, QueryFilter, QueryState}, resource::Resource, system::{ DynSystemParam, DynSystemParamState, If, Local, ParamSet, Query, SystemParam, SystemParamValidationError, }, world::{ FilteredResources, FilteredResourcesBuilder, FilteredResourcesMut, FilteredResourcesMutBuilder, FromWorld, World, }, }; use core::fmt::Debug; use super::{Res, ResMut, SystemState}; /// A builder that can create a [`SystemParam`]. /// /// ``` /// # use bevy_ecs::{ /// # prelude::*, /// # system::{SystemParam, ParamBuilder}, /// # }; /// # #[derive(Resource)] /// # struct R; /// # /// # #[derive(SystemParam)] /// # struct MyParam; /// # /// fn some_system(param: MyParam) {} /// /// fn build_system(builder: impl SystemParamBuilder<MyParam>) { /// let mut world = World::new(); /// // To build a system, create a tuple of `SystemParamBuilder`s /// // with a builder for each parameter. /// // Note that the builder for a system must be a tuple, /// // even if there is only one parameter. /// (builder,) /// .build_state(&mut world) /// .build_system(some_system); /// } /// /// fn build_closure_system_infer(builder: impl SystemParamBuilder<MyParam>) { /// let mut world = World::new(); /// // Closures can be used in addition to named functions. /// // If a closure is used, the parameter types must all be inferred /// // from the builders, so you cannot use plain `ParamBuilder`. /// (builder, ParamBuilder::resource()) /// .build_state(&mut world) /// .build_system(|param, res| { /// let param: MyParam = param; /// let res: Res<R> = res; /// }); /// } /// /// fn build_closure_system_explicit(builder: impl SystemParamBuilder<MyParam>) { /// let mut world = World::new(); /// // Alternately, you can provide all types in the closure /// // parameter list and call `build_any_system()`. /// (builder, ParamBuilder) /// .build_state(&mut world) /// .build_any_system(|param: MyParam, res: Res<R>| {}); /// } /// ``` /// /// See the documentation for individual builders for more examples. /// /// # List of Builders /// /// [`ParamBuilder`] can be used for parameters that don't require any special building. /// Using a `ParamBuilder` will build the system parameter the same way it would be initialized in an ordinary system. /// /// `ParamBuilder` also provides factory methods that return a `ParamBuilder` typed as `impl SystemParamBuilder<P>` /// for common system parameters that can be used to guide closure parameter inference. /// /// [`QueryParamBuilder`] can build a [`Query`] to add additional filters, /// or to configure the components available to [`FilteredEntityRef`](crate::world::FilteredEntityRef) or [`FilteredEntityMut`](crate::world::FilteredEntityMut). /// You can also use a [`QueryState`] to build a [`Query`]. /// /// [`LocalBuilder`] can build a [`Local`] to supply the initial value for the `Local`. /// /// [`FilteredResourcesParamBuilder`] can build a [`FilteredResources`], /// and [`FilteredResourcesMutParamBuilder`] can build a [`FilteredResourcesMut`], /// to configure the resources that can be accessed. /// /// [`DynParamBuilder`] can build a [`DynSystemParam`] to determine the type of the inner parameter, /// and to supply any `SystemParamBuilder` it needs. /// /// Tuples of builders can build tuples of parameters, one builder for each element. /// Note that since systems require a tuple as a parameter, the outer builder for a system will always be a tuple. /// /// A [`Vec`] of builders can build a `Vec` of parameters, one builder for each element. /// /// A [`ParamSetBuilder`] can build a [`ParamSet`]. /// This can wrap either a tuple or a `Vec`, one builder for each element. /// /// A custom system param created with `#[derive(SystemParam)]` can be buildable if it includes a `#[system_param(builder)]` attribute. /// See [the documentation for `SystemParam` derives](SystemParam#builders). /// /// # Safety /// /// The implementor must ensure that the state returned /// from [`SystemParamBuilder::build`] is valid for `P`. /// Note that the exact safety requirements depend on the implementation of [`SystemParam`], /// so if `Self` is not a local type then you must call [`SystemParam::init_state`] /// or another [`SystemParamBuilder::build`]. pub unsafe trait SystemParamBuilder<P: SystemParam>: Sized { /// Registers any [`World`] access used by this [`SystemParam`] /// and creates a new instance of this param's [`State`](SystemParam::State). fn build(self, world: &mut World) -> P::State; /// Create a [`SystemState`] from a [`SystemParamBuilder`]. /// To create a system, call [`SystemState::build_system`] on the result. fn build_state(self, world: &mut World) -> SystemState<P> { SystemState::from_builder(world, self) } } /// A [`SystemParamBuilder`] for any [`SystemParam`] that uses its default initialization. /// /// ## Example /// /// ``` /// # use bevy_ecs::{ /// # prelude::*, /// # system::{SystemParam, ParamBuilder}, /// # }; /// # /// # #[derive(Component)] /// # struct A; /// # /// # #[derive(Resource)] /// # struct R; /// # /// # #[derive(SystemParam)] /// # struct MyParam; /// # /// # let mut world = World::new(); /// # world.insert_resource(R); /// # /// fn my_system(res: Res<R>, param: MyParam, query: Query<&A>) { /// // ... /// } /// /// let system = ( /// // A plain ParamBuilder can build any parameter type. /// ParamBuilder, /// // The `of::<P>()` method returns a `ParamBuilder` /// // typed as `impl SystemParamBuilder<P>`. /// ParamBuilder::of::<MyParam>(), /// // The other factory methods return typed builders /// // for common parameter types. /// ParamBuilder::query::<&A>(), /// ) /// .build_state(&mut world) /// .build_system(my_system); /// ``` #[derive(Default, Debug, Clone)] pub struct ParamBuilder; // SAFETY: Calls `SystemParam::init_state` unsafe impl<P: SystemParam> SystemParamBuilder<P> for ParamBuilder { fn build(self, world: &mut World) -> P::State { P::init_state(world) } } impl ParamBuilder { /// Creates a [`SystemParamBuilder`] for any [`SystemParam`] that uses its default initialization. pub fn of<T: SystemParam>() -> impl SystemParamBuilder<T> { Self } /// Helper method for reading a [`Resource`] as a param, equivalent to `of::<Res<T>>()` pub fn resource<'w, T: Resource>() -> impl SystemParamBuilder<Res<'w, T>> { Self } /// Helper method for mutably accessing a [`Resource`] as a param, equivalent to `of::<ResMut<T>>()` pub fn resource_mut<'w, T: Resource>() -> impl SystemParamBuilder<ResMut<'w, T>> { Self } /// Helper method for adding a [`Local`] as a param, equivalent to `of::<Local<T>>()` pub fn local<'s, T: FromWorld + Send + 'static>() -> impl SystemParamBuilder<Local<'s, T>> { Self } /// Helper method for adding a [`Query`] as a param, equivalent to `of::<Query<D>>()` pub fn query<'w, 's, D: QueryData + 'static>() -> impl SystemParamBuilder<Query<'w, 's, D, ()>> { Self } /// Helper method for adding a filtered [`Query`] as a param, equivalent to `of::<Query<D, F>>()` pub fn query_filtered<'w, 's, D: QueryData + 'static, F: QueryFilter + 'static>( ) -> impl SystemParamBuilder<Query<'w, 's, D, F>> { Self } } // SAFETY: Any `QueryState<D, F>` for the correct world is valid for `Query::State`, // and we check the world during `build`. unsafe impl<'w, 's, D: QueryData + 'static, F: QueryFilter + 'static> SystemParamBuilder<Query<'w, 's, D, F>> for QueryState<D, F> { fn build(self, world: &mut World) -> QueryState<D, F> { self.validate_world(world.id()); self } } /// A [`SystemParamBuilder`] for a [`Query`]. /// This takes a closure accepting an `&mut` [`QueryBuilder`] and uses the builder to construct the query's state. /// This can be used to add additional filters, /// or to configure the components available to [`FilteredEntityRef`](crate::world::FilteredEntityRef) or [`FilteredEntityMut`](crate::world::FilteredEntityMut). /// /// ## Example /// /// ``` /// # use bevy_ecs::{ /// # prelude::*, /// # system::{SystemParam, QueryParamBuilder}, /// # }; /// # /// # #[derive(Component)] /// # struct Player; /// # /// # let mut world = World::new(); /// let system = (QueryParamBuilder::new(|builder| { /// builder.with::<Player>(); /// }),) /// .build_state(&mut world) /// .build_system(|query: Query<()>| { /// for _ in &query { /// // This only includes entities with a `Player` component. /// } /// }); /// /// // When collecting multiple builders into a `Vec`, /// // use `new_box()` to erase the closure type. /// let system = (vec![ /// QueryParamBuilder::new_box(|builder| { /// builder.with::<Player>(); /// }), /// QueryParamBuilder::new_box(|builder| { /// builder.without::<Player>(); /// }), /// ],) /// .build_state(&mut world) /// .build_system(|query: Vec<Query<()>>| {}); /// ``` #[derive(Clone)] pub struct QueryParamBuilder<T>(T); impl<T> QueryParamBuilder<T> { /// Creates a [`SystemParamBuilder`] for a [`Query`] that accepts a callback to configure the [`QueryBuilder`]. pub fn new<D: QueryData, F: QueryFilter>(f: T) -> Self where T: FnOnce(&mut QueryBuilder<D, F>), { Self(f) } } impl<'a, D: QueryData, F: QueryFilter> QueryParamBuilder<Box<dyn FnOnce(&mut QueryBuilder<D, F>) + 'a>> { /// Creates a [`SystemParamBuilder`] for a [`Query`] that accepts a callback to configure the [`QueryBuilder`]. /// This boxes the callback so that it has a common type and can be put in a `Vec`. pub fn new_box(f: impl FnOnce(&mut QueryBuilder<D, F>) + 'a) -> Self { Self(Box::new(f)) } } // SAFETY: Any `QueryState<D, F>` for the correct world is valid for `Query::State`, // and `QueryBuilder` produces one with the given `world`. unsafe impl< 'w, 's, D: QueryData + 'static, F: QueryFilter + 'static, T: FnOnce(&mut QueryBuilder<D, F>), > SystemParamBuilder<Query<'w, 's, D, F>> for QueryParamBuilder<T> { fn build(self, world: &mut World) -> QueryState<D, F> { let mut builder = QueryBuilder::new(world); (self.0)(&mut builder); builder.build() } } macro_rules! impl_system_param_builder_tuple { ($(#[$meta:meta])* $(($param: ident, $builder: ident)),*) => { #[expect( clippy::allow_attributes, reason = "This is in a macro; as such, the below lints may not always apply." )] #[allow( unused_variables, reason = "Zero-length tuples won't use any of the parameters." )] #[allow( non_snake_case, reason = "The variable names are provided by the macro caller, not by us." )] $(#[$meta])* // SAFETY: implementors of each `SystemParamBuilder` in the tuple have validated their impls unsafe impl<$($param: SystemParam,)* $($builder: SystemParamBuilder<$param>,)*> SystemParamBuilder<($($param,)*)> for ($($builder,)*) { fn build(self, world: &mut World) -> <($($param,)*) as SystemParam>::State { let ($($builder,)*) = self; #[allow( clippy::unused_unit, reason = "Zero-length tuples won't generate any calls to the system parameter builders." )] ($($builder.build(world),)*) } } }; } all_tuples!( #[doc(fake_variadic)] impl_system_param_builder_tuple, 0, 16, P, B ); // SAFETY: implementors of each `SystemParamBuilder` in the vec have validated their impls unsafe impl<P: SystemParam, B: SystemParamBuilder<P>> SystemParamBuilder<Vec<P>> for Vec<B> { fn build(self, world: &mut World) -> <Vec<P> as SystemParam>::State { self.into_iter() .map(|builder| builder.build(world)) .collect() } } /// A [`SystemParamBuilder`] for a [`ParamSet`]. /// /// To build a [`ParamSet`] with a tuple of system parameters, pass a tuple of matching [`SystemParamBuilder`]s. /// To build a [`ParamSet`] with a [`Vec`] of system parameters, pass a `Vec` of matching [`SystemParamBuilder`]s. /// /// # Examples /// /// ``` /// # use bevy_ecs::{prelude::*, system::*}; /// # /// # #[derive(Component)] /// # struct Health; /// # /// # #[derive(Component)] /// # struct Enemy; /// # /// # #[derive(Component)] /// # struct Ally; /// # /// # let mut world = World::new(); /// # /// let system = (ParamSetBuilder(( /// QueryParamBuilder::new(|builder| { /// builder.with::<Enemy>(); /// }), /// QueryParamBuilder::new(|builder| { /// builder.with::<Ally>(); /// }), /// ParamBuilder, /// )),) /// .build_state(&mut world) /// .build_system(buildable_system_with_tuple); /// # world.run_system_once(system); /// /// fn buildable_system_with_tuple( /// mut set: ParamSet<(Query<&mut Health>, Query<&mut Health>, &World)>, /// ) { /// // The first parameter is built from the first builder, /// // so this will iterate over enemies. /// for mut health in set.p0().iter_mut() {} /// // And the second parameter is built from the second builder, /// // so this will iterate over allies. /// for mut health in set.p1().iter_mut() {} /// // Parameters that don't need special building can use `ParamBuilder`. /// let entities = set.p2().entities(); /// } /// /// let system = (ParamSetBuilder(vec![ /// QueryParamBuilder::new_box(|builder| { /// builder.with::<Enemy>(); /// }), /// QueryParamBuilder::new_box(|builder| { /// builder.with::<Ally>(); /// }), /// ]),) /// .build_state(&mut world) /// .build_system(buildable_system_with_vec); /// # world.run_system_once(system); /// /// fn buildable_system_with_vec(mut set: ParamSet<Vec<Query<&mut Health>>>) { /// // As with tuples, the first parameter is built from the first builder, /// // so this will iterate over enemies. /// for mut health in set.get_mut(0).iter_mut() {} /// // And the second parameter is built from the second builder, /// // so this will iterate over allies. /// for mut health in set.get_mut(1).iter_mut() {} /// // You can iterate over the parameters either by index, /// // or using the `for_each` method. /// set.for_each(|mut query| for mut health in query.iter_mut() {}); /// } /// ``` #[derive(Debug, Default, Clone)] pub struct ParamSetBuilder<T>(pub T); macro_rules! impl_param_set_builder_tuple { ($(($param: ident, $builder: ident)),*) => { #[expect( clippy::allow_attributes, reason = "This is in a macro; as such, the below lints may not always apply." )] #[allow( unused_variables, reason = "Zero-length tuples won't use any of the parameters." )] #[allow( non_snake_case, reason = "The variable names are provided by the macro caller, not by us." )] // SAFETY: implementors of each `SystemParamBuilder` in the tuple have validated their impls unsafe impl<'w, 's, $($param: SystemParam,)* $($builder: SystemParamBuilder<$param>,)*> SystemParamBuilder<ParamSet<'w, 's, ($($param,)*)>> for ParamSetBuilder<($($builder,)*)> { fn build(self, world: &mut World) -> <($($param,)*) as SystemParam>::State { let ParamSetBuilder(($($builder,)*)) = self; ($($builder.build(world),)*) } } }; } all_tuples!(impl_param_set_builder_tuple, 1, 8, P, B); // SAFETY: implementors of each `SystemParamBuilder` in the vec have validated their impls unsafe impl<'w, 's, P: SystemParam, B: SystemParamBuilder<P>> SystemParamBuilder<ParamSet<'w, 's, Vec<P>>> for ParamSetBuilder<Vec<B>> { fn build(self, world: &mut World) -> <Vec<P> as SystemParam>::State { self.0 .into_iter() .map(|builder| builder.build(world)) .collect() } } /// A [`SystemParamBuilder`] for a [`DynSystemParam`]. /// See the [`DynSystemParam`] docs for examples. pub struct DynParamBuilder<'a>(Box<dyn FnOnce(&mut World) -> DynSystemParamState + 'a>); impl<'a> DynParamBuilder<'a> { /// Creates a new [`DynParamBuilder`] by wrapping a [`SystemParamBuilder`] of any type. /// The built [`DynSystemParam`] can be downcast to `T`. pub fn new<T: SystemParam + 'static>(builder: impl SystemParamBuilder<T> + 'a) -> Self { Self(Box::new(|world| { DynSystemParamState::new::<T>(builder.build(world)) })) } } // SAFETY: `DynSystemParam::get_param` will call `get_param` on the boxed `DynSystemParamState`, // and the boxed builder was a valid implementation of `SystemParamBuilder` for that type. // The resulting `DynSystemParam` can only perform access by downcasting to that param type. unsafe impl<'a, 'w, 's> SystemParamBuilder<DynSystemParam<'w, 's>> for DynParamBuilder<'a> { fn build(self, world: &mut World) -> <DynSystemParam<'w, 's> as SystemParam>::State { (self.0)(world) } } /// A [`SystemParamBuilder`] for a [`Local`]. /// The provided value will be used as the initial value of the `Local`. /// /// ## Example /// /// ``` /// # use bevy_ecs::{ /// # prelude::*, /// # system::{SystemParam, LocalBuilder, RunSystemOnce}, /// # }; /// # /// # let mut world = World::new(); /// let system = (LocalBuilder(100),) /// .build_state(&mut world) /// .build_system(|local: Local<usize>| { /// assert_eq!(*local, 100); /// }); /// # world.run_system_once(system); /// ``` #[derive(Default, Debug, Clone)] pub struct LocalBuilder<T>(pub T); // SAFETY: Any value of `T` is a valid state for `Local`. unsafe impl<'s, T: FromWorld + Send + 'static> SystemParamBuilder<Local<'s, T>> for LocalBuilder<T> { fn build(self, _world: &mut World) -> <Local<'s, T> as SystemParam>::State { SyncCell::new(self.0) } } /// A [`SystemParamBuilder`] for a [`FilteredResources`]. /// See the [`FilteredResources`] docs for examples. #[derive(Clone)] pub struct FilteredResourcesParamBuilder<T>(T); impl<T> FilteredResourcesParamBuilder<T> { /// Creates a [`SystemParamBuilder`] for a [`FilteredResources`] that accepts a callback to configure the [`FilteredResourcesBuilder`]. pub fn new(f: T) -> Self where T: FnOnce(&mut FilteredResourcesBuilder), { Self(f) } } impl<'a> FilteredResourcesParamBuilder<Box<dyn FnOnce(&mut FilteredResourcesBuilder) + 'a>> { /// Creates a [`SystemParamBuilder`] for a [`FilteredResources`] that accepts a callback to configure the [`FilteredResourcesBuilder`]. /// This boxes the callback so that it has a common type. pub fn new_box(f: impl FnOnce(&mut FilteredResourcesBuilder) + 'a) -> Self { Self(Box::new(f)) } } // SAFETY: Any `Access` is a valid state for `FilteredResources`. unsafe impl<'w, 's, T: FnOnce(&mut FilteredResourcesBuilder)> SystemParamBuilder<FilteredResources<'w, 's>> for FilteredResourcesParamBuilder<T> { fn build(self, world: &mut World) -> <FilteredResources<'w, 's> as SystemParam>::State { let mut builder = FilteredResourcesBuilder::new(world); (self.0)(&mut builder); builder.build() } } /// A [`SystemParamBuilder`] for a [`FilteredResourcesMut`]. /// See the [`FilteredResourcesMut`] docs for examples. #[derive(Clone)] pub struct FilteredResourcesMutParamBuilder<T>(T); impl<T> FilteredResourcesMutParamBuilder<T> { /// Creates a [`SystemParamBuilder`] for a [`FilteredResourcesMut`] that accepts a callback to configure the [`FilteredResourcesMutBuilder`]. pub fn new(f: T) -> Self where T: FnOnce(&mut FilteredResourcesMutBuilder), { Self(f) } } impl<'a> FilteredResourcesMutParamBuilder<Box<dyn FnOnce(&mut FilteredResourcesMutBuilder) + 'a>> { /// Creates a [`SystemParamBuilder`] for a [`FilteredResourcesMut`] that accepts a callback to configure the [`FilteredResourcesMutBuilder`]. /// This boxes the callback so that it has a common type. pub fn new_box(f: impl FnOnce(&mut FilteredResourcesMutBuilder) + 'a) -> Self { Self(Box::new(f)) } } // SAFETY: Any `Access` is a valid state for `FilteredResourcesMut`. unsafe impl<'w, 's, T: FnOnce(&mut FilteredResourcesMutBuilder)> SystemParamBuilder<FilteredResourcesMut<'w, 's>> for FilteredResourcesMutParamBuilder<T> { fn build(self, world: &mut World) -> <FilteredResourcesMut<'w, 's> as SystemParam>::State { let mut builder = FilteredResourcesMutBuilder::new(world); (self.0)(&mut builder); builder.build() } } /// A [`SystemParamBuilder`] for an [`Option`]. #[derive(Clone)] pub struct OptionBuilder<T>(T); // SAFETY: `OptionBuilder<B>` builds a state that is valid for `P`, and any state valid for `P` is valid for `Option<P>` unsafe impl<P: SystemParam, B: SystemParamBuilder<P>> SystemParamBuilder<Option<P>> for OptionBuilder<B> { fn build(self, world: &mut World) -> <Option<P> as SystemParam>::State { self.0.build(world) } } /// A [`SystemParamBuilder`] for a [`Result`] of [`SystemParamValidationError`]. #[derive(Clone)] pub struct ResultBuilder<T>(T); // SAFETY: `ResultBuilder<B>` builds a state that is valid for `P`, and any state valid for `P` is valid for `Result<P, SystemParamValidationError>` unsafe impl<P: SystemParam, B: SystemParamBuilder<P>> SystemParamBuilder<Result<P, SystemParamValidationError>> for ResultBuilder<B> { fn build( self, world: &mut World, ) -> <Result<P, SystemParamValidationError> as SystemParam>::State { self.0.build(world) } } /// A [`SystemParamBuilder`] for a [`If`]. #[derive(Clone)] pub struct IfBuilder<T>(T); // SAFETY: `IfBuilder<B>` builds a state that is valid for `P`, and any state valid for `P` is valid for `If<P>` unsafe impl<P: SystemParam, B: SystemParamBuilder<P>> SystemParamBuilder<If<P>> for IfBuilder<B> { fn build(self, world: &mut World) -> <If<P> as SystemParam>::State { self.0.build(world) } } #[cfg(test)] mod tests { use crate::{ entity::Entities, error::Result, prelude::{Component, Query}, reflect::ReflectResource, system::{Local, RunSystemOnce}, }; use alloc::vec; use bevy_reflect::{FromType, Reflect, ReflectRef}; use super::*; #[derive(Component)] struct A; #[derive(Component)] struct B; #[derive(Component)] struct C; #[derive(Resource, Default, Reflect)] #[reflect(Resource)] struct R { foo: usize, } fn local_system(local: Local<u64>) -> u64 { *local } fn query_system(query: Query<()>) -> usize { query.iter().count() } fn query_system_result(query: Query<()>) -> Result<usize> { Ok(query.iter().count()) } fn multi_param_system(a: Local<u64>, b: Local<u64>) -> u64 { *a + *b + 1 } #[test] fn local_builder() { let mut world = World::new(); let system = (LocalBuilder(10),) .build_state(&mut world) .build_system(local_system); let output = world.run_system_once(system).unwrap(); assert_eq!(output, 10); } #[test] fn query_builder() { let mut world = World::new(); world.spawn(A); world.spawn_empty(); let system = (QueryParamBuilder::new(|query| { query.with::<A>(); }),) .build_state(&mut world) .build_system(query_system); let output = world.run_system_once(system).unwrap(); assert_eq!(output, 1); } #[test] fn query_builder_result_fallible() { let mut world = World::new(); world.spawn(A); world.spawn_empty(); let system = (QueryParamBuilder::new(|query| { query.with::<A>(); }),) .build_state(&mut world) .build_system(query_system_result); // The type annotation here is necessary since the system // could also return `Result<usize>` let output: usize = world.run_system_once(system).unwrap(); assert_eq!(output, 1); } #[test] fn query_builder_result_infallible() { let mut world = World::new(); world.spawn(A); world.spawn_empty(); let system = (QueryParamBuilder::new(|query| { query.with::<A>(); }),) .build_state(&mut world) .build_system(query_system_result); // The type annotation here is necessary since the system // could also return `usize` let output: Result<usize> = world.run_system_once(system).unwrap(); assert_eq!(output.unwrap(), 1); } #[test] fn query_builder_state() { let mut world = World::new(); world.spawn(A); world.spawn_empty(); let state = QueryBuilder::new(&mut world).with::<A>().build(); let system = (state,).build_state(&mut world).build_system(query_system); let output = world.run_system_once(system).unwrap(); assert_eq!(output, 1); } #[test] fn multi_param_builder() { let mut world = World::new(); world.spawn(A); world.spawn_empty(); let system = (LocalBuilder(0), ParamBuilder) .build_state(&mut world) .build_system(multi_param_system); let output = world.run_system_once(system).unwrap(); assert_eq!(output, 1); } #[test] fn vec_builder() { let mut world = World::new(); world.spawn((A, B, C)); world.spawn((A, B)); world.spawn((A, C)); world.spawn((A, C)); world.spawn_empty(); let system = (vec![ QueryParamBuilder::new_box(|builder| { builder.with::<B>().without::<C>(); }), QueryParamBuilder::new_box(|builder| { builder.with::<C>().without::<B>(); }), ],) .build_state(&mut world) .build_system(|params: Vec<Query<&mut A>>| { let mut count: usize = 0; params .into_iter() .for_each(|mut query| count += query.iter_mut().count()); count }); let output = world.run_system_once(system).unwrap(); assert_eq!(output, 3); } #[test] fn multi_param_builder_inference() { let mut world = World::new(); world.spawn(A); world.spawn_empty(); let system = (LocalBuilder(0u64), ParamBuilder::local::<u64>()) .build_state(&mut world) .build_system(|a, b| *a + *b + 1); let output = world.run_system_once(system).unwrap(); assert_eq!(output, 1); } #[test] fn param_set_builder() { let mut world = World::new(); world.spawn((A, B, C)); world.spawn((A, B)); world.spawn((A, C)); world.spawn((A, C)); world.spawn_empty(); let system = (ParamSetBuilder(( QueryParamBuilder::new(|builder| { builder.with::<B>(); }), QueryParamBuilder::new(|builder| { builder.with::<C>(); }), )),) .build_state(&mut world) .build_system(|mut params: ParamSet<(Query<&mut A>, Query<&mut A>)>| { params.p0().iter().count() + params.p1().iter().count() }); let output = world.run_system_once(system).unwrap(); assert_eq!(output, 5); } #[test] fn param_set_vec_builder() { let mut world = World::new(); world.spawn((A, B, C)); world.spawn((A, B)); world.spawn((A, C)); world.spawn((A, C)); world.spawn_empty(); let system = (ParamSetBuilder(vec![ QueryParamBuilder::new_box(|builder| { builder.with::<B>(); }), QueryParamBuilder::new_box(|builder| { builder.with::<C>(); }), ]),) .build_state(&mut world) .build_system(|mut params: ParamSet<Vec<Query<&mut A>>>| { let mut count = 0; params.for_each(|mut query| count += query.iter_mut().count()); count }); let output = world.run_system_once(system).unwrap(); assert_eq!(output, 5); } #[test] fn dyn_builder() { let mut world = World::new(); world.spawn(A); world.spawn_empty(); let system = ( DynParamBuilder::new(LocalBuilder(3_usize)), DynParamBuilder::new::<Query<()>>(QueryParamBuilder::new(|builder| { builder.with::<A>(); })), DynParamBuilder::new::<&Entities>(ParamBuilder), ) .build_state(&mut world) .build_system( |mut p0: DynSystemParam, mut p1: DynSystemParam, mut p2: DynSystemParam| { let local = *p0.downcast_mut::<Local<usize>>().unwrap(); let query_count = p1.downcast_mut::<Query<()>>().unwrap().iter().count(); let _entities = p2.downcast_mut::<&Entities>().unwrap(); assert!(p0.downcast_mut::<Query<()>>().is_none()); local + query_count }, ); let output = world.run_system_once(system).unwrap(); assert_eq!(output, 4); } #[derive(SystemParam)] #[system_param(builder)] struct CustomParam<'w, 's> { query: Query<'w, 's, ()>, local: Local<'s, usize>, } #[test] fn custom_param_builder() { let mut world = World::new(); world.spawn(A); world.spawn_empty(); let system = (CustomParamBuilder { local: LocalBuilder(100), query: QueryParamBuilder::new(|builder| { builder.with::<A>(); }), },) .build_state(&mut world) .build_system(|param: CustomParam| *param.local + param.query.iter().count()); let output = world.run_system_once(system).unwrap(); assert_eq!(output, 101); } #[test] fn filtered_resource_conflicts_read_with_res() { let mut world = World::new(); ( ParamBuilder::resource(), FilteredResourcesParamBuilder::new(|builder| { builder.add_read::<R>(); }), ) .build_state(&mut world) .build_system(|_r: Res<R>, _fr: FilteredResources| {}); } #[test] #[should_panic] fn filtered_resource_conflicts_read_with_resmut() { let mut world = World::new(); ( ParamBuilder::resource_mut(), FilteredResourcesParamBuilder::new(|builder| { builder.add_read::<R>(); }), ) .build_state(&mut world) .build_system(|_r: ResMut<R>, _fr: FilteredResources| {}); } #[test] #[should_panic] fn filtered_resource_conflicts_read_all_with_resmut() { let mut world = World::new(); ( ParamBuilder::resource_mut(), FilteredResourcesParamBuilder::new(|builder| { builder.add_read_all(); }), ) .build_state(&mut world) .build_system(|_r: ResMut<R>, _fr: FilteredResources| {}); } #[test] fn filtered_resource_mut_conflicts_read_with_res() { let mut world = World::new(); ( ParamBuilder::resource(), FilteredResourcesMutParamBuilder::new(|builder| { builder.add_read::<R>(); }), ) .build_state(&mut world) .build_system(|_r: Res<R>, _fr: FilteredResourcesMut| {}); } #[test] #[should_panic] fn filtered_resource_mut_conflicts_read_with_resmut() { let mut world = World::new(); ( ParamBuilder::resource_mut(), FilteredResourcesMutParamBuilder::new(|builder| { builder.add_read::<R>(); }), )
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/observer_system.rs
crates/bevy_ecs/src/system/observer_system.rs
use crate::{ event::Event, prelude::{Bundle, On}, system::System, }; use super::IntoSystem; /// Implemented for [`System`]s that have [`On`] as the first argument. pub trait ObserverSystem<E: Event, B: Bundle, Out = ()>: System<In = On<'static, 'static, E, B>, Out = Out> + Send + 'static { } impl<E: Event, B: Bundle, Out, T> ObserverSystem<E, B, Out> for T where T: System<In = On<'static, 'static, E, B>, Out = Out> + Send + 'static { } /// Implemented for systems that convert into [`ObserverSystem`]. /// /// # Usage notes /// /// This trait should only be used as a bound for trait implementations or as an /// argument to a function. If an observer system needs to be returned from a /// function or stored somewhere, use [`ObserverSystem`] instead of this trait. #[diagnostic::on_unimplemented( message = "`{Self}` cannot become an `ObserverSystem`", label = "the trait `IntoObserverSystem` is not implemented", note = "for function `ObserverSystem`s, ensure the first argument is `On<T>` and any subsequent ones are `SystemParam`" )] pub trait IntoObserverSystem<E: Event, B: Bundle, M, Out = ()>: Send + 'static { /// The type of [`System`] that this instance converts into. type System: ObserverSystem<E, B, Out>; /// Turns this value into its corresponding [`System`]. fn into_system(this: Self) -> Self::System; } impl<E: Event, B, M, Out, S> IntoObserverSystem<E, B, M, Out> for S where S: IntoSystem<On<'static, 'static, E, B>, Out, M> + Send + 'static, S::System: ObserverSystem<E, B, Out>, E: 'static, B: Bundle, { type System = S::System; fn into_system(this: Self) -> Self::System { IntoSystem::into_system(this) } } #[cfg(test)] mod tests { use crate::{ event::Event, observer::On, system::{In, IntoSystem}, world::World, }; #[derive(Event)] struct TriggerEvent; #[test] fn test_piped_observer_systems_no_input() { fn a(_: On<TriggerEvent>) {} fn b() {} let mut world = World::new(); world.add_observer(a.pipe(b)); } #[test] fn test_piped_observer_systems_with_inputs() { fn a(_: On<TriggerEvent>) -> u32 { 3 } fn b(_: In<u32>) {} let mut world = World::new(); world.add_observer(a.pipe(b)); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/combinator.rs
crates/bevy_ecs/src/system/combinator.rs
use alloc::{format, vec::Vec}; use bevy_utils::prelude::DebugName; use core::marker::PhantomData; use crate::{ change_detection::{CheckChangeTicks, Tick}, error::ErrorContext, prelude::World, query::FilteredAccessSet, schedule::InternedSystemSet, system::{input::SystemInput, SystemIn, SystemParamValidationError}, world::unsafe_world_cell::UnsafeWorldCell, }; use super::{IntoSystem, ReadOnlySystem, RunSystemError, System}; /// Customizes the behavior of a [`CombinatorSystem`]. /// /// # Examples /// /// ``` /// use bevy_ecs::prelude::*; /// use bevy_ecs::system::{CombinatorSystem, Combine, RunSystemError}; /// /// // A system combinator that performs an exclusive-or (XOR) /// // operation on the output of two systems. /// pub type Xor<A, B> = CombinatorSystem<XorMarker, A, B>; /// /// // This struct is used to customize the behavior of our combinator. /// pub struct XorMarker; /// /// impl<A, B> Combine<A, B> for XorMarker /// where /// A: System<In = (), Out = bool>, /// B: System<In = (), Out = bool>, /// { /// type In = (); /// type Out = bool; /// /// fn combine<T>( /// _input: Self::In, /// data: &mut T, /// a: impl FnOnce(A::In, &mut T) -> Result<A::Out, RunSystemError>, /// b: impl FnOnce(B::In, &mut T) -> Result<B::Out, RunSystemError>, /// ) -> Result<Self::Out, RunSystemError> { /// Ok(a((), data)? ^ b((), data)?) /// } /// } /// /// # #[derive(Resource, PartialEq, Eq)] struct A(u32); /// # #[derive(Resource, PartialEq, Eq)] struct B(u32); /// # #[derive(Resource, Default)] struct RanFlag(bool); /// # let mut world = World::new(); /// # world.init_resource::<RanFlag>(); /// # /// # let mut app = Schedule::default(); /// app.add_systems(my_system.run_if(Xor::new( /// IntoSystem::into_system(resource_equals(A(1))), /// IntoSystem::into_system(resource_equals(B(1))), /// // The name of the combined system. /// "a ^ b".into(), /// ))); /// # fn my_system(mut flag: ResMut<RanFlag>) { flag.0 = true; } /// # /// # world.insert_resource(A(0)); /// # world.insert_resource(B(0)); /// # app.run(&mut world); /// # // Neither condition passes, so the system does not run. /// # assert!(!world.resource::<RanFlag>().0); /// # /// # world.insert_resource(A(1)); /// # app.run(&mut world); /// # // Only the first condition passes, so the system runs. /// # assert!(world.resource::<RanFlag>().0); /// # world.resource_mut::<RanFlag>().0 = false; /// # /// # world.insert_resource(B(1)); /// # app.run(&mut world); /// # // Both conditions pass, so the system does not run. /// # assert!(!world.resource::<RanFlag>().0); /// # /// # world.insert_resource(A(0)); /// # app.run(&mut world); /// # // Only the second condition passes, so the system runs. /// # assert!(world.resource::<RanFlag>().0); /// # world.resource_mut::<RanFlag>().0 = false; /// ``` #[diagnostic::on_unimplemented( message = "`{Self}` can not combine systems `{A}` and `{B}`", label = "invalid system combination", note = "the inputs and outputs of `{A}` and `{B}` are not compatible with this combiner" )] pub trait Combine<A: System, B: System> { /// The [input](System::In) type for a [`CombinatorSystem`]. type In: SystemInput; /// The [output](System::Out) type for a [`CombinatorSystem`]. type Out; /// When used in a [`CombinatorSystem`], this function customizes how /// the two composite systems are invoked and their outputs are combined. /// /// See the trait-level docs for [`Combine`] for an example implementation. fn combine<T>( input: <Self::In as SystemInput>::Inner<'_>, data: &mut T, a: impl FnOnce(SystemIn<'_, A>, &mut T) -> Result<A::Out, RunSystemError>, b: impl FnOnce(SystemIn<'_, B>, &mut T) -> Result<B::Out, RunSystemError>, ) -> Result<Self::Out, RunSystemError>; } /// A [`System`] defined by combining two other systems. /// The behavior of this combinator is specified by implementing the [`Combine`] trait. /// For a full usage example, see the docs for [`Combine`]. pub struct CombinatorSystem<Func, A, B> { _marker: PhantomData<fn() -> Func>, a: A, b: B, name: DebugName, } impl<Func, A, B> CombinatorSystem<Func, A, B> { /// Creates a new system that combines two inner systems. /// /// The returned system will only be usable if `Func` implements [`Combine<A, B>`]. pub fn new(a: A, b: B, name: DebugName) -> Self { Self { _marker: PhantomData, a, b, name, } } } impl<A, B, Func> System for CombinatorSystem<Func, A, B> where Func: Combine<A, B> + 'static, A: System, B: System, { type In = Func::In; type Out = Func::Out; fn name(&self) -> DebugName { self.name.clone() } #[inline] fn flags(&self) -> super::SystemStateFlags { self.a.flags() | self.b.flags() } unsafe fn run_unsafe( &mut self, input: SystemIn<'_, Self>, world: UnsafeWorldCell, ) -> Result<Self::Out, RunSystemError> { struct PrivateUnsafeWorldCell<'w>(UnsafeWorldCell<'w>); // Since control over handling system run errors is passed on to the // implementation of `Func::combine`, which may run the two closures // however it wants, errors must be intercepted here if they should be // handled by the world's error handler. unsafe fn run_system<S: System>( system: &mut S, input: SystemIn<S>, world: &mut PrivateUnsafeWorldCell, ) -> Result<S::Out, RunSystemError> { // SAFETY: see comment on `Func::combine` call match (|| unsafe { system.validate_param_unsafe(world.0)?; system.run_unsafe(input, world.0) })() { // let the world's default error handler handle the error if `Failed(_)` Err(RunSystemError::Failed(err)) => { // SAFETY: We registered access to DefaultErrorHandler in `initialize`. (unsafe { world.0.default_error_handler() })( err, ErrorContext::System { name: system.name(), last_run: system.get_last_run(), }, ); // Since the error handler takes the error by value, create a new error: // The original error has already been handled, including // the reason for the failure here isn't important. Err(format!("System `{}` failed", system.name()).into()) } // `Skipped(_)` and `Ok(_)` are passed through: // system skipping is not an error, and isn't passed to the // world's error handler by the executors. result @ (Ok(_) | Err(RunSystemError::Skipped(_))) => result, } } Func::combine( input, &mut PrivateUnsafeWorldCell(world), // SAFETY: The world accesses for both underlying systems have been registered, // so the caller will guarantee that no other systems will conflict with (`a` or `b`) and the `DefaultErrorHandler` resource. // If either system has `is_exclusive()`, then the combined system also has `is_exclusive`. // Since we require a `combine` to pass in a mutable reference to `world` and that's a private type // passed to a function as an unbound non-'static generic argument, they can never be called in parallel // or re-entrantly because that would require forging another instance of `PrivateUnsafeWorldCell`. // This means that the world accesses in the two closures will not conflict with each other. // The closure's access to the DefaultErrorHandler does not // conflict with any potential access to the DefaultErrorHandler by // the systems since the closures are not run in parallel. |input, world| unsafe { run_system(&mut self.a, input, world) }, // SAFETY: See the comment above. |input, world| unsafe { run_system(&mut self.b, input, world) }, ) } #[cfg(feature = "hotpatching")] #[inline] fn refresh_hotpatch(&mut self) { self.a.refresh_hotpatch(); self.b.refresh_hotpatch(); } #[inline] fn apply_deferred(&mut self, world: &mut World) { self.a.apply_deferred(world); self.b.apply_deferred(world); } #[inline] fn queue_deferred(&mut self, mut world: crate::world::DeferredWorld) { self.a.queue_deferred(world.reborrow()); self.b.queue_deferred(world); } #[inline] unsafe fn validate_param_unsafe( &mut self, _world: UnsafeWorldCell, ) -> Result<(), SystemParamValidationError> { // Both systems are validated in `Self::run_unsafe`, so that we get the // chance to run the second system even if the first one fails to // validate. Ok(()) } fn initialize(&mut self, world: &mut World) -> FilteredAccessSet { let mut a_access = self.a.initialize(world); let b_access = self.b.initialize(world); a_access.extend(b_access); // We might need to read the default error handler after the component // systems have run to report failures. let error_resource = world.register_resource::<crate::error::DefaultErrorHandler>(); a_access.add_unfiltered_resource_read(error_resource); a_access } fn check_change_tick(&mut self, check: CheckChangeTicks) { self.a.check_change_tick(check); self.b.check_change_tick(check); } fn default_system_sets(&self) -> Vec<InternedSystemSet> { let mut default_sets = self.a.default_system_sets(); default_sets.append(&mut self.b.default_system_sets()); default_sets } fn get_last_run(&self) -> Tick { self.a.get_last_run() } fn set_last_run(&mut self, last_run: Tick) { self.a.set_last_run(last_run); self.b.set_last_run(last_run); } } /// SAFETY: Both systems are read-only, so any system created by combining them will only read from the world. unsafe impl<Func, A, B> ReadOnlySystem for CombinatorSystem<Func, A, B> where Func: Combine<A, B> + 'static, A: ReadOnlySystem, B: ReadOnlySystem, { } impl<Func, A, B> Clone for CombinatorSystem<Func, A, B> where A: Clone, B: Clone, { /// Clone the combined system. The cloned instance must be `.initialize()`d before it can run. fn clone(&self) -> Self { CombinatorSystem::new(self.a.clone(), self.b.clone(), self.name.clone()) } } /// An [`IntoSystem`] creating an instance of [`PipeSystem`]. #[derive(Clone)] pub struct IntoPipeSystem<A, B> { a: A, b: B, } impl<A, B> IntoPipeSystem<A, B> { /// Creates a new [`IntoSystem`] that pipes two inner systems. pub const fn new(a: A, b: B) -> Self { Self { a, b } } } #[doc(hidden)] pub struct IsPipeSystemMarker; impl<A, B, IA, OA, IB, OB, MA, MB> IntoSystem<IA, OB, (IsPipeSystemMarker, OA, IB, MA, MB)> for IntoPipeSystem<A, B> where IA: SystemInput, A: IntoSystem<IA, OA, MA>, B: IntoSystem<IB, OB, MB>, for<'a> IB: SystemInput<Inner<'a> = OA>, { type System = PipeSystem<A::System, B::System>; fn into_system(this: Self) -> Self::System { let system_a = IntoSystem::into_system(this.a); let system_b = IntoSystem::into_system(this.b); let name = format!("Pipe({}, {})", system_a.name(), system_b.name()); PipeSystem::new(system_a, system_b, DebugName::owned(name)) } } /// A [`System`] created by piping the output of the first system into the input of the second. /// /// This can be repeated indefinitely, but system pipes cannot branch: the output is consumed by the receiving system. /// /// Given two systems `A` and `B`, A may be piped into `B` as `A.pipe(B)` if the output type of `A` is /// equal to the input type of `B`. /// /// Note that for [`FunctionSystem`](crate::system::FunctionSystem)s the output is the return value /// of the function and the input is the first [`SystemParam`](crate::system::SystemParam) if it is /// tagged with [`In`](crate::system::In) or `()` if the function has no designated input parameter. /// /// # Examples /// /// ``` /// use std::num::ParseIntError; /// /// use bevy_ecs::prelude::*; /// /// fn main() { /// let mut world = World::default(); /// world.insert_resource(Message("42".to_string())); /// /// // pipe the `parse_message_system`'s output into the `filter_system`s input /// let mut piped_system = IntoSystem::into_system(parse_message_system.pipe(filter_system)); /// piped_system.initialize(&mut world); /// assert_eq!(piped_system.run((), &mut world).unwrap(), Some(42)); /// } /// /// #[derive(Resource)] /// struct Message(String); /// /// fn parse_message_system(message: Res<Message>) -> Result<usize, ParseIntError> { /// message.0.parse::<usize>() /// } /// /// fn filter_system(In(result): In<Result<usize, ParseIntError>>) -> Option<usize> { /// result.ok().filter(|&n| n < 100) /// } /// ``` pub struct PipeSystem<A, B> { a: A, b: B, name: DebugName, } impl<A, B> PipeSystem<A, B> where A: System, B: System, for<'a> B::In: SystemInput<Inner<'a> = A::Out>, { /// Creates a new system that pipes two inner systems. pub fn new(a: A, b: B, name: DebugName) -> Self { Self { a, b, name } } } impl<A, B> System for PipeSystem<A, B> where A: System, B: System, for<'a> B::In: SystemInput<Inner<'a> = A::Out>, { type In = A::In; type Out = B::Out; fn name(&self) -> DebugName { self.name.clone() } #[inline] fn flags(&self) -> super::SystemStateFlags { self.a.flags() | self.b.flags() } unsafe fn run_unsafe( &mut self, input: SystemIn<'_, Self>, world: UnsafeWorldCell, ) -> Result<Self::Out, RunSystemError> { // SAFETY: Upheld by caller unsafe { let value = self.a.run_unsafe(input, world)?; // `Self::validate_param_unsafe` already validated the first system, // but we still need to validate the second system once the first one runs. self.b.validate_param_unsafe(world)?; self.b.run_unsafe(value, world) } } #[cfg(feature = "hotpatching")] #[inline] fn refresh_hotpatch(&mut self) { self.a.refresh_hotpatch(); self.b.refresh_hotpatch(); } fn apply_deferred(&mut self, world: &mut World) { self.a.apply_deferred(world); self.b.apply_deferred(world); } fn queue_deferred(&mut self, mut world: crate::world::DeferredWorld) { self.a.queue_deferred(world.reborrow()); self.b.queue_deferred(world); } unsafe fn validate_param_unsafe( &mut self, world: UnsafeWorldCell, ) -> Result<(), SystemParamValidationError> { // We only validate parameters for the first system, // since it may make changes to the world that affect // whether the second system has valid parameters. // The second system will be validated in `Self::run_unsafe`. // SAFETY: Delegate to the `System` implementation for `a`. unsafe { self.a.validate_param_unsafe(world) } } fn initialize(&mut self, world: &mut World) -> FilteredAccessSet { let mut a_access = self.a.initialize(world); let b_access = self.b.initialize(world); a_access.extend(b_access); a_access } fn check_change_tick(&mut self, check: CheckChangeTicks) { self.a.check_change_tick(check); self.b.check_change_tick(check); } fn default_system_sets(&self) -> Vec<InternedSystemSet> { let mut default_sets = self.a.default_system_sets(); default_sets.append(&mut self.b.default_system_sets()); default_sets } fn get_last_run(&self) -> Tick { self.a.get_last_run() } fn set_last_run(&mut self, last_run: Tick) { self.a.set_last_run(last_run); self.b.set_last_run(last_run); } } /// SAFETY: Both systems are read-only, so any system created by piping them will only read from the world. unsafe impl<A, B> ReadOnlySystem for PipeSystem<A, B> where A: ReadOnlySystem, B: ReadOnlySystem, for<'a> B::In: SystemInput<Inner<'a> = A::Out>, { } #[cfg(test)] mod tests { use crate::error::DefaultErrorHandler; use crate::prelude::*; use bevy_utils::prelude::DebugName; use crate::{ schedule::OrMarker, system::{assert_system_does_not_conflict, CombinatorSystem}, }; #[test] fn combinator_with_error_handler_access() { fn my_system(_: ResMut<DefaultErrorHandler>) {} fn a() -> bool { true } fn b(_: ResMut<DefaultErrorHandler>) -> bool { true } fn asdf(_: In<bool>) {} let mut world = World::new(); world.insert_resource(DefaultErrorHandler::default()); let system = CombinatorSystem::<OrMarker, _, _>::new( IntoSystem::into_system(a), IntoSystem::into_system(b), DebugName::borrowed("a OR b"), ); // `system` should not conflict with itself by mutably accessing the error handler resource. assert_system_does_not_conflict(system.clone()); let mut schedule = Schedule::default(); schedule.add_systems((my_system, system.pipe(asdf))); schedule.initialize(&mut world).unwrap(); // `my_system` should conflict with the combinator system because the combinator reads the error handler resource. assert!(!schedule.graph().conflicting_systems().is_empty()); schedule.run(&mut world); } #[test] fn exclusive_system_piping_is_possible() { fn my_exclusive_system(_world: &mut World) -> u32 { 1 } fn out_pipe(input: In<u32>) { assert!(input.0 == 1); } let mut world = World::new(); let mut schedule = Schedule::default(); schedule.add_systems(my_exclusive_system.pipe(out_pipe)); schedule.run(&mut world); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/adapter_system.rs
crates/bevy_ecs/src/system/adapter_system.rs
use alloc::vec::Vec; use bevy_utils::prelude::DebugName; use super::{IntoSystem, ReadOnlySystem, RunSystemError, System, SystemParamValidationError}; use crate::{ schedule::InternedSystemSet, system::{input::SystemInput, SystemIn}, world::unsafe_world_cell::UnsafeWorldCell, }; /// Customizes the behavior of an [`AdapterSystem`] /// /// # Examples /// /// ``` /// # use bevy_ecs::prelude::*; /// use bevy_ecs::system::{Adapt, AdapterSystem, RunSystemError}; /// /// // A system adapter that inverts the result of a system. /// // NOTE: Instead of manually implementing this, you can just use `bevy_ecs::schedule::common_conditions::not`. /// pub type NotSystem<S> = AdapterSystem<NotMarker, S>; /// /// // This struct is used to customize the behavior of our adapter. /// pub struct NotMarker; /// /// impl<S> Adapt<S> for NotMarker /// where /// S: System, /// S::Out: std::ops::Not, /// { /// type In = S::In; /// type Out = <S::Out as std::ops::Not>::Output; /// /// fn adapt( /// &mut self, /// input: <Self::In as SystemInput>::Inner<'_>, /// run_system: impl FnOnce(SystemIn<'_, S>) -> Result<S::Out, RunSystemError>, /// ) -> Result<Self::Out, RunSystemError> { /// let result = run_system(input)?; /// Ok(!result) /// } /// } /// # let mut world = World::new(); /// # let mut system = NotSystem::new(NotMarker, IntoSystem::into_system(|| false), "".into()); /// # system.initialize(&mut world); /// # assert!(system.run((), &mut world).unwrap()); /// ``` #[diagnostic::on_unimplemented( message = "`{Self}` can not adapt a system of type `{S}`", label = "invalid system adapter" )] pub trait Adapt<S: System>: Send + Sync + 'static { /// The [input](System::In) type for an [`AdapterSystem`]. type In: SystemInput; /// The [output](System::Out) type for an [`AdapterSystem`]. type Out; /// When used in an [`AdapterSystem`], this function customizes how the system /// is run and how its inputs/outputs are adapted. fn adapt( &mut self, input: <Self::In as SystemInput>::Inner<'_>, run_system: impl FnOnce(SystemIn<'_, S>) -> Result<S::Out, RunSystemError>, ) -> Result<Self::Out, RunSystemError>; } /// An [`IntoSystem`] creating an instance of [`AdapterSystem`]. #[derive(Clone)] pub struct IntoAdapterSystem<Func, S> { func: Func, system: S, } impl<Func, S> IntoAdapterSystem<Func, S> { /// Creates a new [`IntoSystem`] that uses `func` to adapt `system`, via the [`Adapt`] trait. pub const fn new(func: Func, system: S) -> Self { Self { func, system } } } #[doc(hidden)] pub struct IsAdapterSystemMarker; impl<Func, S, I, O, M> IntoSystem<Func::In, Func::Out, (IsAdapterSystemMarker, I, O, M)> for IntoAdapterSystem<Func, S> where Func: Adapt<S::System>, I: SystemInput, S: IntoSystem<I, O, M>, { type System = AdapterSystem<Func, S::System>; // Required method fn into_system(this: Self) -> Self::System { let system = IntoSystem::into_system(this.system); let name = system.name(); AdapterSystem::new(this.func, system, name) } } /// A [`System`] that takes the output of `S` and transforms it by applying `Func` to it. #[derive(Clone)] pub struct AdapterSystem<Func, S> { func: Func, system: S, name: DebugName, } impl<Func, S> AdapterSystem<Func, S> where Func: Adapt<S>, S: System, { /// Creates a new [`System`] that uses `func` to adapt `system`, via the [`Adapt`] trait. pub const fn new(func: Func, system: S, name: DebugName) -> Self { Self { func, system, name } } } impl<Func, S> System for AdapterSystem<Func, S> where Func: Adapt<S>, S: System, { type In = Func::In; type Out = Func::Out; fn name(&self) -> DebugName { self.name.clone() } #[inline] fn flags(&self) -> super::SystemStateFlags { self.system.flags() } #[inline] unsafe fn run_unsafe( &mut self, input: SystemIn<'_, Self>, world: UnsafeWorldCell, ) -> Result<Self::Out, RunSystemError> { // SAFETY: `system.run_unsafe` has the same invariants as `self.run_unsafe`. self.func.adapt(input, |input| unsafe { self.system.run_unsafe(input, world) }) } #[cfg(feature = "hotpatching")] #[inline] fn refresh_hotpatch(&mut self) { self.system.refresh_hotpatch(); } #[inline] fn apply_deferred(&mut self, world: &mut crate::prelude::World) { self.system.apply_deferred(world); } #[inline] fn queue_deferred(&mut self, world: crate::world::DeferredWorld) { self.system.queue_deferred(world); } #[inline] unsafe fn validate_param_unsafe( &mut self, world: UnsafeWorldCell, ) -> Result<(), SystemParamValidationError> { // SAFETY: Delegate to other `System` implementations. unsafe { self.system.validate_param_unsafe(world) } } fn initialize(&mut self, world: &mut crate::prelude::World) -> crate::query::FilteredAccessSet { self.system.initialize(world) } fn check_change_tick(&mut self, check: crate::change_detection::CheckChangeTicks) { self.system.check_change_tick(check); } fn default_system_sets(&self) -> Vec<InternedSystemSet> { self.system.default_system_sets() } fn get_last_run(&self) -> crate::change_detection::Tick { self.system.get_last_run() } fn set_last_run(&mut self, last_run: crate::change_detection::Tick) { self.system.set_last_run(last_run); } } // SAFETY: The inner system is read-only. unsafe impl<Func, S> ReadOnlySystem for AdapterSystem<Func, S> where Func: Adapt<S>, S: ReadOnlySystem, { } impl<F, S, Out> Adapt<S> for F where F: Send + Sync + 'static + FnMut(S::Out) -> Out, S: System, { type In = S::In; type Out = Out; fn adapt( &mut self, input: <Self::In as SystemInput>::Inner<'_>, run_system: impl FnOnce(SystemIn<'_, S>) -> Result<S::Out, RunSystemError>, ) -> Result<Self::Out, RunSystemError> { run_system(input).map(self) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/system_registry.rs
crates/bevy_ecs/src/system/system_registry.rs
#[cfg(feature = "hotpatching")] use crate::{change_detection::DetectChanges, HotPatchChanges}; use crate::{ change_detection::Mut, entity::Entity, error::BevyError, system::{ input::SystemInput, BoxedSystem, IntoSystem, RunSystemError, SystemParamValidationError, }, world::World, }; use alloc::boxed::Box; use bevy_ecs_macros::{Component, Resource}; use bevy_utils::prelude::DebugName; use core::{any::TypeId, marker::PhantomData}; use thiserror::Error; /// A small wrapper for [`BoxedSystem`] that also keeps track whether or not the system has been initialized. #[derive(Component)] #[require(SystemIdMarker = SystemIdMarker::typed_system_id_marker::<I, O>())] pub(crate) struct RegisteredSystem<I, O> { initialized: bool, system: BoxedSystem<I, O>, } impl<I, O> RegisteredSystem<I, O> { pub fn new(system: BoxedSystem<I, O>) -> Self { RegisteredSystem { initialized: false, system, } } } #[derive(Debug, Clone)] struct TypeIdAndName { type_id: TypeId, name: DebugName, } impl TypeIdAndName { fn new<T: 'static>() -> Self { Self { type_id: TypeId::of::<T>(), name: DebugName::type_name::<T>(), } } } impl Default for TypeIdAndName { fn default() -> Self { Self { type_id: TypeId::of::<()>(), name: DebugName::type_name::<()>(), } } } /// Marker [`Component`](bevy_ecs::component::Component) for identifying [`SystemId`] [`Entity`]s. #[derive(Debug, Default, Clone, Component)] pub struct SystemIdMarker { input_type_id: TypeIdAndName, output_type_id: TypeIdAndName, } impl SystemIdMarker { fn typed_system_id_marker<I: 'static, O: 'static>() -> Self { Self { input_type_id: TypeIdAndName::new::<I>(), output_type_id: TypeIdAndName::new::<O>(), } } } /// A system that has been removed from the registry. /// It contains the system and whether or not it has been initialized. /// /// This struct is returned by [`World::unregister_system`]. pub struct RemovedSystem<I = (), O = ()> { initialized: bool, system: BoxedSystem<I, O>, } impl<I, O> RemovedSystem<I, O> { /// Is the system initialized? /// A system is initialized the first time it's ran. pub fn initialized(&self) -> bool { self.initialized } /// The system removed from the storage. pub fn system(self) -> BoxedSystem<I, O> { self.system } } /// An identifier for a registered system. /// /// These are opaque identifiers, keyed to a specific [`World`], /// and are created via [`World::register_system`]. pub struct SystemId<I: SystemInput = (), O = ()> { pub(crate) entity: Entity, pub(crate) marker: PhantomData<fn(I) -> O>, } impl<I: SystemInput, O> SystemId<I, O> { /// Transforms a [`SystemId`] into the [`Entity`] that holds the one-shot system's state. /// /// It's trivial to convert [`SystemId`] into an [`Entity`] since a one-shot system /// is really an entity with associated handler function. /// /// For example, this is useful if you want to assign a name label to a system. pub fn entity(self) -> Entity { self.entity } /// Create [`SystemId`] from an [`Entity`]. Useful when you only have entity handles to avoid /// adding extra components that have a [`SystemId`] everywhere. To run a system with this ID /// - The entity must be a system /// - The `I` + `O` types must be correct pub fn from_entity(entity: Entity) -> Self { Self { entity, marker: PhantomData, } } } impl<I: SystemInput, O> Eq for SystemId<I, O> {} // A manual impl is used because the trait bounds should ignore the `I` and `O` phantom parameters. impl<I: SystemInput, O> Copy for SystemId<I, O> {} // A manual impl is used because the trait bounds should ignore the `I` and `O` phantom parameters. impl<I: SystemInput, O> Clone for SystemId<I, O> { fn clone(&self) -> Self { *self } } // A manual impl is used because the trait bounds should ignore the `I` and `O` phantom parameters. impl<I: SystemInput, O> PartialEq for SystemId<I, O> { fn eq(&self, other: &Self) -> bool { self.entity == other.entity && self.marker == other.marker } } // A manual impl is used because the trait bounds should ignore the `I` and `O` phantom parameters. impl<I: SystemInput, O> core::hash::Hash for SystemId<I, O> { fn hash<H: core::hash::Hasher>(&self, state: &mut H) { self.entity.hash(state); } } impl<I: SystemInput, O> core::fmt::Debug for SystemId<I, O> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("SystemId").field(&self.entity).finish() } } /// A cached [`SystemId`] distinguished by the unique function type of its system. /// /// This resource is inserted by [`World::register_system_cached`]. #[derive(Resource)] pub struct CachedSystemId<S> { /// The cached `SystemId` as an `Entity`. pub entity: Entity, _marker: PhantomData<fn() -> S>, } impl<S> CachedSystemId<S> { /// Creates a new `CachedSystemId` struct given a `SystemId`. pub fn new<I: SystemInput, O>(id: SystemId<I, O>) -> Self { Self { entity: id.entity(), _marker: PhantomData, } } } impl World { /// Registers a system and returns a [`SystemId`] so it can later be called by [`World::run_system`]. /// /// It's possible to register multiple copies of the same system by calling this function /// multiple times. If that's not what you want, consider using [`World::register_system_cached`] /// instead. /// /// This is different from adding systems to a [`Schedule`](crate::schedule::Schedule), /// because the [`SystemId`] that is returned can be used anywhere in the [`World`] to run the associated system. /// This allows for running systems in a pushed-based fashion. /// Using a [`Schedule`](crate::schedule::Schedule) is still preferred for most cases /// due to its better performance and ability to run non-conflicting systems simultaneously. pub fn register_system<I, O, M>( &mut self, system: impl IntoSystem<I, O, M> + 'static, ) -> SystemId<I, O> where I: SystemInput + 'static, O: 'static, { self.register_boxed_system(Box::new(IntoSystem::into_system(system))) } /// Similar to [`Self::register_system`], but allows passing in a [`BoxedSystem`]. /// /// This is useful if the [`IntoSystem`] implementor has already been turned into a /// [`System`](crate::system::System) trait object and put in a [`Box`]. pub fn register_boxed_system<I, O>(&mut self, system: BoxedSystem<I, O>) -> SystemId<I, O> where I: SystemInput + 'static, O: 'static, { let entity = self.spawn(RegisteredSystem::new(system)).id(); SystemId::from_entity(entity) } /// Removes a registered system and returns the system, if it exists. /// After removing a system, the [`SystemId`] becomes invalid and attempting to use it afterwards will result in errors. /// Re-adding the removed system will register it on a new [`SystemId`]. /// /// If no system corresponds to the given [`SystemId`], this method returns an error. /// Systems are also not allowed to remove themselves, this returns an error too. pub fn unregister_system<I, O>( &mut self, id: SystemId<I, O>, ) -> Result<RemovedSystem<I, O>, RegisteredSystemError<I, O>> where I: SystemInput + 'static, O: 'static, { match self.get_entity_mut(id.entity) { Ok(mut entity) => { let registered_system = entity .take::<RegisteredSystem<I, O>>() .ok_or(RegisteredSystemError::SelfRemove(id))?; entity.despawn(); Ok(RemovedSystem { initialized: registered_system.initialized, system: registered_system.system, }) } Err(_) => Err(RegisteredSystemError::SystemIdNotRegistered(id)), } } /// Run stored systems by their [`SystemId`]. /// Before running a system, it must first be registered. /// The method [`World::register_system`] stores a given system and returns a [`SystemId`]. /// This is different from [`RunSystemOnce::run_system_once`](crate::system::RunSystemOnce::run_system_once), /// because it keeps local state between calls and change detection works correctly. /// /// Also runs any queued-up commands. /// /// In order to run a chained system with an input, use [`World::run_system_with`] instead. /// /// # Examples /// /// ## Running a system /// /// ``` /// # use bevy_ecs::prelude::*; /// fn increment(mut counter: Local<u8>) { /// *counter += 1; /// println!("{}", *counter); /// } /// /// let mut world = World::default(); /// let counter_one = world.register_system(increment); /// let counter_two = world.register_system(increment); /// world.run_system(counter_one); // -> 1 /// world.run_system(counter_one); // -> 2 /// world.run_system(counter_two); // -> 1 /// ``` /// /// ## Change detection /// /// ``` /// # use bevy_ecs::prelude::*; /// #[derive(Resource, Default)] /// struct ChangeDetector; /// /// let mut world = World::default(); /// world.init_resource::<ChangeDetector>(); /// let detector = world.register_system(|change_detector: ResMut<ChangeDetector>| { /// if change_detector.is_changed() { /// println!("Something happened!"); /// } else { /// println!("Nothing happened."); /// } /// }); /// /// // Resources are changed when they are first added /// let _ = world.run_system(detector); // -> Something happened! /// let _ = world.run_system(detector); // -> Nothing happened. /// world.resource_mut::<ChangeDetector>().set_changed(); /// let _ = world.run_system(detector); // -> Something happened! /// ``` /// /// ## Getting system output /// /// ``` /// # use bevy_ecs::prelude::*; /// /// #[derive(Resource)] /// struct PlayerScore(i32); /// /// #[derive(Resource)] /// struct OpponentScore(i32); /// /// fn get_player_score(player_score: Res<PlayerScore>) -> i32 { /// player_score.0 /// } /// /// fn get_opponent_score(opponent_score: Res<OpponentScore>) -> i32 { /// opponent_score.0 /// } /// /// let mut world = World::default(); /// world.insert_resource(PlayerScore(3)); /// world.insert_resource(OpponentScore(2)); /// /// let scoring_systems = [ /// ("player", world.register_system(get_player_score)), /// ("opponent", world.register_system(get_opponent_score)), /// ]; /// /// for (label, scoring_system) in scoring_systems { /// println!("{label} has score {}", world.run_system(scoring_system).expect("system succeeded")); /// } /// ``` pub fn run_system<O: 'static>( &mut self, id: SystemId<(), O>, ) -> Result<O, RegisteredSystemError<(), O>> { self.run_system_with(id, ()) } /// Run a stored chained system by its [`SystemId`], providing an input value. /// Before running a system, it must first be registered. /// The method [`World::register_system`] stores a given system and returns a [`SystemId`]. /// /// Also runs any queued-up commands. /// /// # Examples /// /// ``` /// # use bevy_ecs::prelude::*; /// fn increment(In(increment_by): In<u8>, mut counter: Local<u8>) -> u8 { /// *counter += increment_by; /// *counter /// } /// /// let mut world = World::default(); /// let counter_one = world.register_system(increment); /// let counter_two = world.register_system(increment); /// assert_eq!(world.run_system_with(counter_one, 1).unwrap(), 1); /// assert_eq!(world.run_system_with(counter_one, 20).unwrap(), 21); /// assert_eq!(world.run_system_with(counter_two, 30).unwrap(), 30); /// ``` /// /// See [`World::run_system`] for more examples. pub fn run_system_with<I, O>( &mut self, id: SystemId<I, O>, input: I::Inner<'_>, ) -> Result<O, RegisteredSystemError<I, O>> where I: SystemInput + 'static, O: 'static, { // Lookup let mut entity = self .get_entity_mut(id.entity) .map_err(|_| RegisteredSystemError::SystemIdNotRegistered(id))?; // Take ownership of system trait object let Some(RegisteredSystem { mut initialized, mut system, }) = entity.take::<RegisteredSystem<I, O>>() else { let Some(system_id_marker) = entity.get::<SystemIdMarker>() else { return Err(RegisteredSystemError::SystemIdNotRegistered(id)); }; if system_id_marker.input_type_id.type_id != TypeId::of::<I>() || system_id_marker.output_type_id.type_id != TypeId::of::<O>() { return Err(RegisteredSystemError::IncorrectType( id, system_id_marker.clone(), )); } return Err(RegisteredSystemError::Recursive(id)); }; // Initialize the system if !initialized { system.initialize(self); initialized = true; } // refresh hotpatches for stored systems #[cfg(feature = "hotpatching")] if self .get_resource_ref::<HotPatchChanges>() .map(|r| r.last_changed()) .unwrap_or_default() .is_newer_than(system.get_last_run(), self.change_tick()) { system.refresh_hotpatch(); } // Wait to run the commands until the system is available again. // This is needed so the systems can recursively run themselves. let result = system.run_without_applying_deferred(input, self); system.queue_deferred(self.into()); // Return ownership of system trait object (if entity still exists) if let Ok(mut entity) = self.get_entity_mut(id.entity) { entity.insert::<RegisteredSystem<I, O>>(RegisteredSystem { initialized, system, }); } // Run any commands enqueued by the system self.flush(); Ok(result?) } /// Registers a system or returns its cached [`SystemId`]. /// /// If you want to run the system immediately and you don't need its `SystemId`, see /// [`World::run_system_cached`]. /// /// The first time this function is called for a particular system, it will register it and /// store its [`SystemId`] in a [`CachedSystemId`] resource for later. If you would rather /// manage the `SystemId` yourself, or register multiple copies of the same system, use /// [`World::register_system`] instead. /// /// # Limitations /// /// This function only accepts ZST (zero-sized) systems to guarantee that any two systems of /// the same type must be equal. This means that closures that capture the environment, and /// function pointers, are not accepted. /// /// If you want to access values from the environment within a system, consider passing them in /// as inputs via [`World::run_system_cached_with`]. If that's not an option, consider /// [`World::register_system`] instead. pub fn register_system_cached<I, O, M, S>(&mut self, system: S) -> SystemId<I, O> where I: SystemInput + 'static, O: 'static, S: IntoSystem<I, O, M> + 'static, { const { assert!( size_of::<S>() == 0, "Non-ZST systems (e.g. capturing closures, function pointers) cannot be cached.", ); } if !self.contains_resource::<CachedSystemId<S>>() { let id = self.register_system(system); self.insert_resource(CachedSystemId::<S>::new(id)); return id; } self.resource_scope(|world, mut id: Mut<CachedSystemId<S>>| { if let Ok(mut entity) = world.get_entity_mut(id.entity) { if !entity.contains::<RegisteredSystem<I, O>>() { entity.insert(RegisteredSystem::new(Box::new(IntoSystem::into_system( system, )))); } } else { id.entity = world.register_system(system).entity(); } SystemId::from_entity(id.entity) }) } /// Removes a cached system and its [`CachedSystemId`] resource. /// /// See [`World::register_system_cached`] for more information. pub fn unregister_system_cached<I, O, M, S>( &mut self, _system: S, ) -> Result<RemovedSystem<I, O>, RegisteredSystemError<I, O>> where I: SystemInput + 'static, O: 'static, S: IntoSystem<I, O, M> + 'static, { let id = self .remove_resource::<CachedSystemId<S>>() .ok_or(RegisteredSystemError::SystemNotCached)?; self.unregister_system(SystemId::<I, O>::from_entity(id.entity)) } /// Runs a cached system, registering it if necessary. /// /// See [`World::register_system_cached`] for more information. pub fn run_system_cached<O: 'static, M, S: IntoSystem<(), O, M> + 'static>( &mut self, system: S, ) -> Result<O, RegisteredSystemError<(), O>> { self.run_system_cached_with(system, ()) } /// Runs a cached system with an input, registering it if necessary. /// /// See [`World::register_system_cached`] for more information. pub fn run_system_cached_with<I, O, M, S>( &mut self, system: S, input: I::Inner<'_>, ) -> Result<O, RegisteredSystemError<I, O>> where I: SystemInput + 'static, O: 'static, S: IntoSystem<I, O, M> + 'static, { let id = self.register_system_cached(system); self.run_system_with(id, input) } } /// An operation with stored systems failed. #[derive(Error)] pub enum RegisteredSystemError<I: SystemInput = (), O = ()> { /// A system was run by id, but no system with that id was found. /// /// Did you forget to register it? #[error("System {0:?} was not registered")] SystemIdNotRegistered(SystemId<I, O>), /// A cached system was removed by value, but no system with its type was found. /// /// Did you forget to register it? #[error("Cached system was not found")] SystemNotCached, /// A system tried to run itself recursively. #[error("System {0:?} tried to run itself recursively")] Recursive(SystemId<I, O>), /// A system tried to remove itself. #[error("System {0:?} tried to remove itself")] SelfRemove(SystemId<I, O>), /// System could not be run due to parameters that failed validation. /// This is not considered an error. #[error("System did not run due to failed parameter validation: {0}")] Skipped(SystemParamValidationError), /// System returned an error or failed required parameter validation. #[error("System returned error: {0}")] Failed(BevyError), /// [`SystemId`] had different input and/or output types than [`SystemIdMarker`] #[error("Could not get system from `{}`, entity was `SystemId<{}, {}>`", DebugName::type_name::<SystemId<I, O>>(), .1.input_type_id.name, .1.output_type_id.name)] IncorrectType(SystemId<I, O>, SystemIdMarker), } impl<I: SystemInput, O> From<RunSystemError> for RegisteredSystemError<I, O> { fn from(value: RunSystemError) -> Self { match value { RunSystemError::Skipped(err) => Self::Skipped(err), RunSystemError::Failed(err) => Self::Failed(err), } } } impl<I: SystemInput, O> core::fmt::Debug for RegisteredSystemError<I, O> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Self::SystemIdNotRegistered(arg0) => { f.debug_tuple("SystemIdNotRegistered").field(arg0).finish() } Self::SystemNotCached => write!(f, "SystemNotCached"), Self::Recursive(arg0) => f.debug_tuple("Recursive").field(arg0).finish(), Self::SelfRemove(arg0) => f.debug_tuple("SelfRemove").field(arg0).finish(), Self::Skipped(arg0) => f.debug_tuple("Skipped").field(arg0).finish(), Self::Failed(arg0) => f.debug_tuple("Failed").field(arg0).finish(), Self::IncorrectType(arg0, arg1) => f .debug_tuple("IncorrectType") .field(arg0) .field(arg1) .finish(), } } } #[cfg(test)] mod tests { use core::cell::Cell; use bevy_utils::default; use crate::{ prelude::*, system::{RegisteredSystemError, SystemId}, }; #[derive(Resource, Default, PartialEq, Debug)] struct Counter(u8); #[test] fn change_detection() { #[derive(Resource, Default)] struct ChangeDetector; fn count_up_iff_changed( mut counter: ResMut<Counter>, change_detector: ResMut<ChangeDetector>, ) { if change_detector.is_changed() { counter.0 += 1; } } let mut world = World::new(); world.init_resource::<ChangeDetector>(); world.init_resource::<Counter>(); assert_eq!(*world.resource::<Counter>(), Counter(0)); // Resources are changed when they are first added. let id = world.register_system(count_up_iff_changed); world.run_system(id).expect("system runs successfully"); assert_eq!(*world.resource::<Counter>(), Counter(1)); // Nothing changed world.run_system(id).expect("system runs successfully"); assert_eq!(*world.resource::<Counter>(), Counter(1)); // Making a change world.resource_mut::<ChangeDetector>().set_changed(); world.run_system(id).expect("system runs successfully"); assert_eq!(*world.resource::<Counter>(), Counter(2)); } #[test] fn local_variables() { // The `Local` begins at the default value of 0 fn doubling(last_counter: Local<Counter>, mut counter: ResMut<Counter>) { counter.0 += last_counter.0 .0; last_counter.0 .0 = counter.0; } let mut world = World::new(); world.insert_resource(Counter(1)); assert_eq!(*world.resource::<Counter>(), Counter(1)); let id = world.register_system(doubling); world.run_system(id).expect("system runs successfully"); assert_eq!(*world.resource::<Counter>(), Counter(1)); world.run_system(id).expect("system runs successfully"); assert_eq!(*world.resource::<Counter>(), Counter(2)); world.run_system(id).expect("system runs successfully"); assert_eq!(*world.resource::<Counter>(), Counter(4)); world.run_system(id).expect("system runs successfully"); assert_eq!(*world.resource::<Counter>(), Counter(8)); } #[test] fn input_values() { // Verify that a non-Copy, non-Clone type can be passed in. struct NonCopy(u8); fn increment_sys(In(NonCopy(increment_by)): In<NonCopy>, mut counter: ResMut<Counter>) { counter.0 += increment_by; } let mut world = World::new(); let id = world.register_system(increment_sys); // Insert the resource after registering the system. world.insert_resource(Counter(1)); assert_eq!(*world.resource::<Counter>(), Counter(1)); world .run_system_with(id, NonCopy(1)) .expect("system runs successfully"); assert_eq!(*world.resource::<Counter>(), Counter(2)); world .run_system_with(id, NonCopy(1)) .expect("system runs successfully"); assert_eq!(*world.resource::<Counter>(), Counter(3)); world .run_system_with(id, NonCopy(20)) .expect("system runs successfully"); assert_eq!(*world.resource::<Counter>(), Counter(23)); world .run_system_with(id, NonCopy(1)) .expect("system runs successfully"); assert_eq!(*world.resource::<Counter>(), Counter(24)); } #[test] fn output_values() { // Verify that a non-Copy, non-Clone type can be returned. #[derive(Eq, PartialEq, Debug)] struct NonCopy(u8); fn increment_sys(mut counter: ResMut<Counter>) -> NonCopy { counter.0 += 1; NonCopy(counter.0) } let mut world = World::new(); let id = world.register_system(increment_sys); // Insert the resource after registering the system. world.insert_resource(Counter(1)); assert_eq!(*world.resource::<Counter>(), Counter(1)); let output = world.run_system(id).expect("system runs successfully"); assert_eq!(*world.resource::<Counter>(), Counter(2)); assert_eq!(output, NonCopy(2)); let output = world.run_system(id).expect("system runs successfully"); assert_eq!(*world.resource::<Counter>(), Counter(3)); assert_eq!(output, NonCopy(3)); } #[test] fn fallible_system() { fn sys() -> Result<()> { Err("error")?; Ok(()) } let mut world = World::new(); let fallible_system_id = world.register_system(sys); let output = world.run_system(fallible_system_id); assert!(matches!(output, Ok(Err(_)))); } #[test] fn exclusive_system() { let mut world = World::new(); let exclusive_system_id = world.register_system(|world: &mut World| { world.spawn_empty(); }); let entity_count = world.entities.count_spawned(); let _ = world.run_system(exclusive_system_id); assert_eq!(world.entities.count_spawned(), entity_count + 1); } #[test] fn nested_systems() { use crate::system::SystemId; #[derive(Component)] struct Callback(SystemId); fn nested(query: Query<&Callback>, mut commands: Commands) { for callback in query.iter() { commands.run_system(callback.0); } } let mut world = World::new(); world.insert_resource(Counter(0)); let increment_two = world.register_system(|mut counter: ResMut<Counter>| { counter.0 += 2; }); let increment_three = world.register_system(|mut counter: ResMut<Counter>| { counter.0 += 3; }); let nested_id = world.register_system(nested); world.spawn(Callback(increment_two)); world.spawn(Callback(increment_three)); let _ = world.run_system(nested_id); assert_eq!(*world.resource::<Counter>(), Counter(5)); } #[test] fn nested_systems_with_inputs() { use crate::system::SystemId; #[derive(Component)] struct Callback(SystemId<In<u8>>, u8); fn nested(query: Query<&Callback>, mut commands: Commands) { for callback in query.iter() { commands.run_system_with(callback.0, callback.1); } } let mut world = World::new(); world.insert_resource(Counter(0)); let increment_by = world.register_system(|In(amt): In<u8>, mut counter: ResMut<Counter>| { counter.0 += amt; }); let nested_id = world.register_system(nested); world.spawn(Callback(increment_by, 2)); world.spawn(Callback(increment_by, 3)); let _ = world.run_system(nested_id); assert_eq!(*world.resource::<Counter>(), Counter(5)); } #[test] fn cached_system() { use crate::system::RegisteredSystemError; fn four() -> i32 { 4 } let mut world = World::new(); let old = world.register_system_cached(four); let new = world.register_system_cached(four); assert_eq!(old, new); let result = world.unregister_system_cached(four); assert!(result.is_ok()); let new = world.register_system_cached(four); assert_ne!(old, new); let output = world.run_system(old); assert!(matches!( output, Err(RegisteredSystemError::SystemIdNotRegistered(x)) if x == old, )); let output = world.run_system(new); assert!(matches!(output, Ok(x) if x == four())); let output = world.run_system_cached(four); assert!(matches!(output, Ok(x) if x == four())); let output = world.run_system_cached_with(four, ()); assert!(matches!(output, Ok(x) if x == four())); } #[test] fn cached_fallible_system() { fn sys() -> Result<()> { Err("error")?; Ok(()) } let mut world = World::new(); let fallible_system_id = world.register_system_cached(sys); let output = world.run_system(fallible_system_id); assert!(matches!(output, Ok(Err(_)))); let output = world.run_system_cached(sys); assert!(matches!(output, Ok(Err(_)))); let output = world.run_system_cached_with(sys, ()); assert!(matches!(output, Ok(Err(_)))); } #[test] fn cached_system_commands() { fn sys(mut counter: ResMut<Counter>) { counter.0 += 1; } let mut world = World::new(); world.insert_resource(Counter(0)); world.commands().run_system_cached(sys); world.flush_commands(); assert_eq!(world.resource::<Counter>().0, 1); world.commands().run_system_cached_with(sys, ()); world.flush_commands(); assert_eq!(world.resource::<Counter>().0, 2); } #[test] fn cached_fallible_system_commands() { fn sys(mut counter: ResMut<Counter>) -> Result { counter.0 += 1; Ok(()) } let mut world = World::new(); world.insert_resource(Counter(0)); world.commands().run_system_cached(sys); world.flush_commands(); assert_eq!(world.resource::<Counter>().0, 1); world.commands().run_system_cached_with(sys, ()); world.flush_commands(); assert_eq!(world.resource::<Counter>().0, 2); } #[test] #[should_panic(expected = "This system always fails")] fn cached_fallible_system_commands_can_fail() { use crate::system::command; fn sys() -> Result { Err("This system always fails".into()) } let mut world = World::new(); world.commands().queue(command::run_system_cached(sys)); world.flush_commands(); } #[test] fn cached_system_adapters() { fn four() -> i32 { 4 } fn double(In(i): In<i32>) -> i32 { i * 2 } let mut world = World::new(); let output = world.run_system_cached(four.pipe(double)); assert!(matches!(output, Ok(8))); let output = world.run_system_cached(four.map(|i| i * 2)); assert!(matches!(output, Ok(8))); } #[test] fn cached_system_into_same_system_type() { struct Foo; impl IntoSystem<(), (), ()> for Foo { type System = ApplyDeferred; fn into_system(_: Self) -> Self::System { ApplyDeferred } } struct Bar; impl IntoSystem<(), (), ()> for Bar { type System = ApplyDeferred; fn into_system(_: Self) -> Self::System { ApplyDeferred } } let mut world = World::new(); let foo1 = world.register_system_cached(Foo); let foo2 = world.register_system_cached(Foo); let bar1 = world.register_system_cached(Bar); let bar2 = world.register_system_cached(Bar); // The `S: IntoSystem` types are different, so they should be cached // as separate systems, even though the `<S as IntoSystem>::System` // types / values are the same (`ApplyDeferred`). assert_ne!(foo1, bar1);
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/function_system.rs
crates/bevy_ecs/src/system/function_system.rs
use crate::{ change_detection::{CheckChangeTicks, Tick}, error::{BevyError, Result}, never::Never, prelude::FromWorld, query::FilteredAccessSet, schedule::{InternedSystemSet, SystemSet}, system::{ check_system_change_tick, FromInput, ReadOnlySystemParam, System, SystemIn, SystemInput, SystemParam, SystemParamItem, }, world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, World, WorldId}, }; use alloc::{borrow::Cow, vec, vec::Vec}; use bevy_utils::prelude::DebugName; use core::marker::PhantomData; use variadics_please::all_tuples; #[cfg(feature = "trace")] use tracing::{info_span, Span}; #[cfg(feature = "trace")] use alloc::string::ToString as _; use super::{ IntoSystem, ReadOnlySystem, RunSystemError, SystemParamBuilder, SystemParamValidationError, SystemStateFlags, }; /// The metadata of a [`System`]. #[derive(Clone)] pub struct SystemMeta { pub(crate) name: DebugName, // NOTE: this must be kept private. making a SystemMeta non-send is irreversible to prevent // SystemParams from overriding each other flags: SystemStateFlags, pub(crate) last_run: Tick, #[cfg(feature = "trace")] pub(crate) system_span: Span, #[cfg(feature = "trace")] pub(crate) commands_span: Span, } impl SystemMeta { pub(crate) fn new<T>() -> Self { let name = DebugName::type_name::<T>(); Self { // These spans are initialized during plugin build, so we set the parent to `None` to prevent // them from being children of the span that is measuring the plugin build time. #[cfg(feature = "trace")] system_span: info_span!(parent: None, "system", name = name.clone().to_string()), #[cfg(feature = "trace")] commands_span: info_span!(parent: None, "system_commands", name = name.clone().to_string()), name, flags: SystemStateFlags::empty(), last_run: Tick::new(0), } } /// Returns the system's name #[inline] pub fn name(&self) -> &DebugName { &self.name } /// Sets the name of this system. /// /// Useful to give closure systems more readable and unique names for debugging and tracing. #[inline] pub fn set_name(&mut self, new_name: impl Into<Cow<'static, str>>) { let new_name: Cow<'static, str> = new_name.into(); #[cfg(feature = "trace")] { let name = new_name.as_ref(); self.system_span = info_span!(parent: None, "system", name = name); self.commands_span = info_span!(parent: None, "system_commands", name = name); } self.name = new_name.into(); } /// Returns true if the system is [`Send`]. #[inline] pub fn is_send(&self) -> bool { !self.flags.intersects(SystemStateFlags::NON_SEND) } /// Sets the system to be not [`Send`]. /// /// This is irreversible. #[inline] pub fn set_non_send(&mut self) { self.flags |= SystemStateFlags::NON_SEND; } /// Returns true if the system has deferred [`SystemParam`]'s #[inline] pub fn has_deferred(&self) -> bool { self.flags.intersects(SystemStateFlags::DEFERRED) } /// Marks the system as having deferred buffers like [`Commands`](`super::Commands`) /// This lets the scheduler insert [`ApplyDeferred`](`crate::prelude::ApplyDeferred`) systems automatically. #[inline] pub fn set_has_deferred(&mut self) { self.flags |= SystemStateFlags::DEFERRED; } /// Mark the system to run exclusively. i.e. no other systems will run at the same time. pub fn set_exclusive(&mut self) { self.flags |= SystemStateFlags::EXCLUSIVE; } } // TODO: Actually use this in FunctionSystem. We should probably only do this once Systems are constructed using a World reference // (to avoid the need for unwrapping to retrieve SystemMeta) /// Holds on to persistent state required to drive [`SystemParam`] for a [`System`]. /// /// This is a powerful and convenient tool for working with exclusive world access, /// allowing you to fetch data from the [`World`] as if you were running a [`System`]. /// However, simply calling `world::run_system(my_system)` using a [`World::run_system`](World::run_system) /// can be significantly simpler and ensures that change detection and command flushing work as expected. /// /// Borrow-checking is handled for you, allowing you to mutably access multiple compatible system parameters at once, /// and arbitrary system parameters (like [`MessageWriter`](crate::message::MessageWriter)) can be conveniently fetched. /// /// For an alternative approach to split mutable access to the world, see [`World::resource_scope`]. /// /// # Warning /// /// [`SystemState`] values created can be cached to improve performance, /// and *must* be cached and reused in order for system parameters that rely on local state to work correctly. /// These include: /// - [`Added`](crate::query::Added), [`Changed`](crate::query::Changed) and [`Spawned`](crate::query::Spawned) query filters /// - [`Local`](crate::system::Local) variables that hold state /// - [`MessageReader`](crate::message::MessageReader) system parameters, which rely on a [`Local`](crate::system::Local) to track which messages have been seen /// /// Note that this is automatically handled for you when using a [`World::run_system`](World::run_system). /// /// # Example /// /// Basic usage: /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_ecs::system::SystemState; /// # /// # #[derive(Message)] /// # struct MyMessage; /// # #[derive(Resource)] /// # struct MyResource(u32); /// # /// # #[derive(Component)] /// # struct MyComponent; /// # /// // Work directly on the `World` /// let mut world = World::new(); /// world.init_resource::<Messages<MyMessage>>(); /// /// // Construct a `SystemState` struct, passing in a tuple of `SystemParam` /// // as if you were writing an ordinary system. /// let mut system_state: SystemState<( /// MessageWriter<MyMessage>, /// Option<ResMut<MyResource>>, /// Query<&MyComponent>, /// )> = SystemState::new(&mut world); /// /// // Use system_state.get_mut(&mut world) and unpack your system parameters into variables! /// // system_state.get(&world) provides read-only versions of your system parameters instead. /// let (message_writer, maybe_resource, query) = system_state.get_mut(&mut world); /// /// // If you are using `Commands`, you can choose when you want to apply them to the world. /// // You need to manually call `.apply(world)` on the `SystemState` to apply them. /// ``` /// Caching: /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_ecs::system::SystemState; /// # use bevy_ecs::message::Messages; /// # /// # #[derive(Message)] /// # struct MyMessage; /// #[derive(Resource)] /// struct CachedSystemState { /// message_state: SystemState<MessageReader<'static, 'static, MyMessage>>, /// } /// /// // Create and store a system state once /// let mut world = World::new(); /// world.init_resource::<Messages<MyMessage>>(); /// let initial_state: SystemState<MessageReader<MyMessage>> = SystemState::new(&mut world); /// /// // The system state is cached in a resource /// world.insert_resource(CachedSystemState { /// message_state: initial_state, /// }); /// /// // Later, fetch the cached system state, saving on overhead /// world.resource_scope(|world, mut cached_state: Mut<CachedSystemState>| { /// let mut message_reader = cached_state.message_state.get_mut(world); /// /// for message in message_reader.read() { /// println!("Hello World!"); /// } /// }); /// ``` /// Exclusive System: /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_ecs::system::SystemState; /// # /// # #[derive(Message)] /// # struct MyMessage; /// # /// fn exclusive_system(world: &mut World, system_state: &mut SystemState<MessageReader<MyMessage>>) { /// let mut message_reader = system_state.get_mut(world); /// /// for message in message_reader.read() { /// println!("Hello World!"); /// } /// } /// ``` pub struct SystemState<Param: SystemParam + 'static> { meta: SystemMeta, param_state: Param::State, world_id: WorldId, } // Allow closure arguments to be inferred. // For a closure to be used as a `SystemParamFunction`, it needs to be generic in any `'w` or `'s` lifetimes. // Rust will only infer a closure to be generic over lifetimes if it's passed to a function with a Fn constraint. // So, generate a function for each arity with an explicit `FnMut` constraint to enable higher-order lifetimes, // along with a regular `SystemParamFunction` constraint to allow the system to be built. macro_rules! impl_build_system { ($(#[$meta:meta])* $($param: ident),*) => { $(#[$meta])* impl<$($param: SystemParam),*> SystemState<($($param,)*)> { /// Create a [`FunctionSystem`] from a [`SystemState`]. /// This method signature allows type inference of closure parameters for a system with no input. /// You can use [`SystemState::build_system_with_input()`] if you have input, or [`SystemState::build_any_system()`] if you don't need type inference. #[inline] pub fn build_system< InnerOut: IntoResult<Out>, Out, Marker, F: FnMut($(SystemParamItem<$param>),*) -> InnerOut + SystemParamFunction<Marker, In = (), Out = InnerOut, Param = ($($param,)*)> > ( self, func: F, ) -> FunctionSystem<Marker, (), Out, F> { self.build_any_system(func) } /// Create a [`FunctionSystem`] from a [`SystemState`]. /// This method signature allows type inference of closure parameters for a system with input. /// You can use [`SystemState::build_system()`] if you have no input, or [`SystemState::build_any_system()`] if you don't need type inference. #[inline] pub fn build_system_with_input< InnerIn: SystemInput + FromInput<In>, In: SystemInput, InnerOut: IntoResult<Out>, Out, Marker, F: FnMut(InnerIn, $(SystemParamItem<$param>),*) -> InnerOut + SystemParamFunction<Marker, In = InnerIn, Out = InnerOut, Param = ($($param,)*)> > ( self, func: F, ) -> FunctionSystem<Marker, In, Out, F> { self.build_any_system(func) } } } } all_tuples!( #[doc(fake_variadic)] impl_build_system, 0, 16, P ); impl<Param: SystemParam> SystemState<Param> { /// Creates a new [`SystemState`] with default state. pub fn new(world: &mut World) -> Self { let mut meta = SystemMeta::new::<Param>(); meta.last_run = world.change_tick().relative_to(Tick::MAX); let param_state = Param::init_state(world); let mut component_access_set = FilteredAccessSet::new(); // We need to call `init_access` to ensure there are no panics from conflicts within `Param`, // even though we don't use the calculated access. Param::init_access(&param_state, &mut meta, &mut component_access_set, world); Self { meta, param_state, world_id: world.id(), } } /// Create a [`SystemState`] from a [`SystemParamBuilder`] pub(crate) fn from_builder(world: &mut World, builder: impl SystemParamBuilder<Param>) -> Self { let mut meta = SystemMeta::new::<Param>(); meta.last_run = world.change_tick().relative_to(Tick::MAX); let param_state = builder.build(world); let mut component_access_set = FilteredAccessSet::new(); // We need to call `init_access` to ensure there are no panics from conflicts within `Param`, // even though we don't use the calculated access. Param::init_access(&param_state, &mut meta, &mut component_access_set, world); Self { meta, param_state, world_id: world.id(), } } /// Create a [`FunctionSystem`] from a [`SystemState`]. /// This method signature allows any system function, but the compiler will not perform type inference on closure parameters. /// You can use [`SystemState::build_system()`] or [`SystemState::build_system_with_input()`] to get type inference on parameters. #[inline] pub fn build_any_system<Marker, In, Out, F>(self, func: F) -> FunctionSystem<Marker, In, Out, F> where In: SystemInput, F: SystemParamFunction<Marker, In: FromInput<In>, Out: IntoResult<Out>, Param = Param>, { FunctionSystem::new( func, self.meta, Some(FunctionSystemState { param: self.param_state, world_id: self.world_id, }), ) } /// Gets the metadata for this instance. #[inline] pub fn meta(&self) -> &SystemMeta { &self.meta } /// Gets the metadata for this instance. #[inline] pub fn meta_mut(&mut self) -> &mut SystemMeta { &mut self.meta } /// Retrieve the [`SystemParam`] values. This can only be called when all parameters are read-only. #[inline] pub fn get<'w, 's>(&'s mut self, world: &'w World) -> SystemParamItem<'w, 's, Param> where Param: ReadOnlySystemParam, { self.validate_world(world.id()); // SAFETY: Param is read-only and doesn't allow mutable access to World. // It also matches the World this SystemState was created with. unsafe { self.get_unchecked(world.as_unsafe_world_cell_readonly()) } } /// Retrieve the mutable [`SystemParam`] values. #[inline] pub fn get_mut<'w, 's>(&'s mut self, world: &'w mut World) -> SystemParamItem<'w, 's, Param> { self.validate_world(world.id()); // SAFETY: World is uniquely borrowed and matches the World this SystemState was created with. unsafe { self.get_unchecked(world.as_unsafe_world_cell()) } } /// Applies all state queued up for [`SystemParam`] values. For example, this will apply commands queued up /// by a [`Commands`](`super::Commands`) parameter to the given [`World`]. /// This function should be called manually after the values returned by [`SystemState::get`] and [`SystemState::get_mut`] /// are finished being used. pub fn apply(&mut self, world: &mut World) { Param::apply(&mut self.param_state, &self.meta, world); } /// Wrapper over [`SystemParam::validate_param`]. /// /// # Safety /// /// - The passed [`UnsafeWorldCell`] must have read-only access to /// world data in `component_access_set`. /// - `world` must be the same [`World`] that was used to initialize [`state`](SystemParam::init_state). pub unsafe fn validate_param( state: &mut Self, world: UnsafeWorldCell, ) -> Result<(), SystemParamValidationError> { // SAFETY: Delegated to existing `SystemParam` implementations. unsafe { Param::validate_param(&mut state.param_state, &state.meta, world) } } /// Returns `true` if `world_id` matches the [`World`] that was used to call [`SystemState::new`]. /// Otherwise, this returns false. #[inline] pub fn matches_world(&self, world_id: WorldId) -> bool { self.world_id == world_id } /// Asserts that the [`SystemState`] matches the provided world. #[inline] #[track_caller] fn validate_world(&self, world_id: WorldId) { #[inline(never)] #[track_caller] #[cold] fn panic_mismatched(this: WorldId, other: WorldId) -> ! { panic!("Encountered a mismatched World. This SystemState was created from {this:?}, but a method was called using {other:?}."); } if !self.matches_world(world_id) { panic_mismatched(self.world_id, world_id); } } /// Retrieve the [`SystemParam`] values. /// /// # Safety /// This call might access any of the input parameters in a way that violates Rust's mutability rules. Make sure the data /// access is safe in the context of global [`World`] access. The passed-in [`World`] _must_ be the [`World`] the [`SystemState`] was /// created with. #[inline] pub unsafe fn get_unchecked<'w, 's>( &'s mut self, world: UnsafeWorldCell<'w>, ) -> SystemParamItem<'w, 's, Param> { let change_tick = world.increment_change_tick(); // SAFETY: The invariants are upheld by the caller. unsafe { self.fetch(world, change_tick) } } /// # Safety /// This call might access any of the input parameters in a way that violates Rust's mutability rules. Make sure the data /// access is safe in the context of global [`World`] access. The passed-in [`World`] _must_ be the [`World`] the [`SystemState`] was /// created with. #[inline] unsafe fn fetch<'w, 's>( &'s mut self, world: UnsafeWorldCell<'w>, change_tick: Tick, ) -> SystemParamItem<'w, 's, Param> { // SAFETY: The invariants are upheld by the caller. let param = unsafe { Param::get_param(&mut self.param_state, &self.meta, world, change_tick) }; self.meta.last_run = change_tick; param } /// Returns a reference to the current system param states. pub fn param_state(&self) -> &Param::State { &self.param_state } /// Returns a mutable reference to the current system param states. /// Marked as unsafe because modifying the system states may result in violation to certain /// assumptions made by the [`SystemParam`]. Use with care. /// /// # Safety /// Modifying the system param states may have unintended consequences. /// The param state is generally considered to be owned by the [`SystemParam`]. Modifications /// should respect any invariants as required by the [`SystemParam`]. /// For example, modifying the system state of [`ResMut`](crate::system::ResMut) will obviously create issues. pub unsafe fn param_state_mut(&mut self) -> &mut Param::State { &mut self.param_state } } impl<Param: SystemParam> FromWorld for SystemState<Param> { fn from_world(world: &mut World) -> Self { Self::new(world) } } /// The [`System`] counter part of an ordinary function. /// /// You get this by calling [`IntoSystem::into_system`] on a function that only accepts /// [`SystemParam`]s. The output of the system becomes the functions return type, while the input /// becomes the functions first parameter or `()` if no such parameter exists. /// /// [`FunctionSystem`] must be `.initialized` before they can be run. /// /// The [`Clone`] implementation for [`FunctionSystem`] returns a new instance which /// is NOT initialized. The cloned system must also be `.initialized` before it can be run. pub struct FunctionSystem<Marker, In, Out, F> where F: SystemParamFunction<Marker>, { func: F, #[cfg(feature = "hotpatching")] current_ptr: subsecond::HotFnPtr, state: Option<FunctionSystemState<F::Param>>, system_meta: SystemMeta, // NOTE: PhantomData<fn()-> T> gives this safe Send/Sync impls marker: PhantomData<fn(In) -> (Marker, Out)>, } /// The state of a [`FunctionSystem`], which must be initialized with /// [`System::initialize`] before the system can be run. A panic will occur if /// the system is run without being initialized. struct FunctionSystemState<P: SystemParam> { /// The cached state of the system's [`SystemParam`]s. param: P::State, /// The id of the [`World`] this system was initialized with. If the world /// passed to [`System::run_unsafe`] or [`System::validate_param_unsafe`] does not match /// this id, a panic will occur. world_id: WorldId, } impl<Marker, In, Out, F> FunctionSystem<Marker, In, Out, F> where F: SystemParamFunction<Marker>, { #[inline] fn new(func: F, system_meta: SystemMeta, state: Option<FunctionSystemState<F::Param>>) -> Self { Self { func, #[cfg(feature = "hotpatching")] current_ptr: subsecond::HotFn::current(<F as SystemParamFunction<Marker>>::run) .ptr_address(), state, system_meta, marker: PhantomData, } } /// Return this system with a new name. /// /// Useful to give closure systems more readable and unique names for debugging and tracing. pub fn with_name(mut self, new_name: impl Into<Cow<'static, str>>) -> Self { self.system_meta.set_name(new_name.into()); self } } // De-initializes the cloned system. impl<Marker, In, Out, F> Clone for FunctionSystem<Marker, In, Out, F> where F: SystemParamFunction<Marker> + Clone, { fn clone(&self) -> Self { Self { func: self.func.clone(), #[cfg(feature = "hotpatching")] current_ptr: subsecond::HotFn::current(<F as SystemParamFunction<Marker>>::run) .ptr_address(), state: None, system_meta: SystemMeta::new::<F>(), marker: PhantomData, } } } /// A marker type used to distinguish regular function systems from exclusive function systems. #[doc(hidden)] pub struct IsFunctionSystem; impl<Marker, In, Out, F> IntoSystem<In, Out, (IsFunctionSystem, Marker)> for F where Marker: 'static, In: SystemInput + 'static, Out: 'static, F: SystemParamFunction<Marker, In: FromInput<In>, Out: IntoResult<Out>>, { type System = FunctionSystem<Marker, In, Out, F>; fn into_system(func: Self) -> Self::System { FunctionSystem::new(func, SystemMeta::new::<F>(), None) } } /// A type that may be converted to the output of a [`System`]. /// This is used to allow systems to return either a plain value or a [`Result`]. pub trait IntoResult<Out>: Sized { /// Converts this type into the system output type. fn into_result(self) -> Result<Out, RunSystemError>; } impl<T> IntoResult<T> for T { fn into_result(self) -> Result<T, RunSystemError> { Ok(self) } } impl<T> IntoResult<T> for Result<T, RunSystemError> { fn into_result(self) -> Result<T, RunSystemError> { self } } impl<T> IntoResult<T> for Result<T, BevyError> { fn into_result(self) -> Result<T, RunSystemError> { Ok(self?) } } // The `!` impl can't be generic in `Out`, since that would overlap with // `impl<T> IntoResult<T> for T` when `T` = `!`. // Use explicit impls for `()` and `bool` so diverging functions // can be used for systems and conditions. impl IntoResult<()> for Never { fn into_result(self) -> Result<(), RunSystemError> { self } } impl IntoResult<bool> for Never { fn into_result(self) -> Result<bool, RunSystemError> { self } } impl<Marker, In, Out, F> FunctionSystem<Marker, In, Out, F> where F: SystemParamFunction<Marker>, { /// Message shown when a system isn't initialized // When lines get too long, rustfmt can sometimes refuse to format them. // Work around this by storing the message separately. const ERROR_UNINITIALIZED: &'static str = "System's state was not found. Did you forget to initialize this system before running it?"; } impl<Marker, In, Out, F> System for FunctionSystem<Marker, In, Out, F> where Marker: 'static, In: SystemInput + 'static, Out: 'static, F: SystemParamFunction<Marker, In: FromInput<In>, Out: IntoResult<Out>>, { type In = In; type Out = Out; #[inline] fn name(&self) -> DebugName { self.system_meta.name.clone() } #[inline] fn flags(&self) -> SystemStateFlags { self.system_meta.flags } #[inline] unsafe fn run_unsafe( &mut self, input: SystemIn<'_, Self>, world: UnsafeWorldCell, ) -> Result<Self::Out, RunSystemError> { #[cfg(feature = "trace")] let _span_guard = self.system_meta.system_span.enter(); let change_tick = world.increment_change_tick(); let input = F::In::from_inner(input); let state = self.state.as_mut().expect(Self::ERROR_UNINITIALIZED); assert_eq!(state.world_id, world.id(), "Encountered a mismatched World. A System cannot be used with Worlds other than the one it was initialized with."); // SAFETY: // - The above assert ensures the world matches. // - All world accesses used by `F::Param` have been registered, so the caller // will ensure that there are no data access conflicts. let params = unsafe { F::Param::get_param(&mut state.param, &self.system_meta, world, change_tick) }; #[cfg(feature = "hotpatching")] let out = { let mut hot_fn = subsecond::HotFn::current(<F as SystemParamFunction<Marker>>::run); // SAFETY: // - pointer used to call is from the current jump table unsafe { hot_fn .try_call_with_ptr(self.current_ptr, (&mut self.func, input, params)) .expect("Error calling hotpatched system. Run a full rebuild") } }; #[cfg(not(feature = "hotpatching"))] let out = self.func.run(input, params); self.system_meta.last_run = change_tick; IntoResult::into_result(out) } #[cfg(feature = "hotpatching")] #[inline] fn refresh_hotpatch(&mut self) { let new = subsecond::HotFn::current(<F as SystemParamFunction<Marker>>::run).ptr_address(); if new != self.current_ptr { log::debug!("system {} hotpatched", self.name()); } self.current_ptr = new; } #[inline] fn apply_deferred(&mut self, world: &mut World) { let param_state = &mut self.state.as_mut().expect(Self::ERROR_UNINITIALIZED).param; F::Param::apply(param_state, &self.system_meta, world); } #[inline] fn queue_deferred(&mut self, world: DeferredWorld) { let param_state = &mut self.state.as_mut().expect(Self::ERROR_UNINITIALIZED).param; F::Param::queue(param_state, &self.system_meta, world); } #[inline] unsafe fn validate_param_unsafe( &mut self, world: UnsafeWorldCell, ) -> Result<(), SystemParamValidationError> { let state = self.state.as_mut().expect(Self::ERROR_UNINITIALIZED); assert_eq!(state.world_id, world.id(), "Encountered a mismatched World. A System cannot be used with Worlds other than the one it was initialized with."); // SAFETY: // - The above assert ensures the world matches. // - All world accesses used by `F::Param` have been registered, so the caller // will ensure that there are no data access conflicts. unsafe { F::Param::validate_param(&mut state.param, &self.system_meta, world) } } #[inline] fn initialize(&mut self, world: &mut World) -> FilteredAccessSet { if let Some(state) = &self.state { assert_eq!( state.world_id, world.id(), "System built with a different world than the one it was added to.", ); } let state = self.state.get_or_insert_with(|| FunctionSystemState { param: F::Param::init_state(world), world_id: world.id(), }); self.system_meta.last_run = world.change_tick().relative_to(Tick::MAX); let mut component_access_set = FilteredAccessSet::new(); F::Param::init_access( &state.param, &mut self.system_meta, &mut component_access_set, world, ); component_access_set } #[inline] fn check_change_tick(&mut self, check: CheckChangeTicks) { check_system_change_tick( &mut self.system_meta.last_run, check, self.system_meta.name.clone(), ); } fn default_system_sets(&self) -> Vec<InternedSystemSet> { let set = crate::schedule::SystemTypeSet::<Self>::new(); vec![set.intern()] } fn get_last_run(&self) -> Tick { self.system_meta.last_run } fn set_last_run(&mut self, last_run: Tick) { self.system_meta.last_run = last_run; } } /// SAFETY: `F`'s param is [`ReadOnlySystemParam`], so this system will only read from the world. unsafe impl<Marker, In, Out, F> ReadOnlySystem for FunctionSystem<Marker, In, Out, F> where Marker: 'static, In: SystemInput + 'static, Out: 'static, F: SystemParamFunction< Marker, In: FromInput<In>, Out: IntoResult<Out>, Param: ReadOnlySystemParam, >, { } /// A trait implemented for all functions that can be used as [`System`]s. /// /// This trait can be useful for making your own systems which accept other systems, /// sometimes called higher order systems. /// /// This should be used in combination with [`ParamSet`] when calling other systems /// within your system. /// Using [`ParamSet`] in this case avoids [`SystemParam`] collisions. /// /// # Example /// /// To create something like [`PipeSystem`], but in entirely safe code. /// /// ``` /// use std::num::ParseIntError; /// /// use bevy_ecs::prelude::*; /// use bevy_ecs::system::StaticSystemInput; /// /// /// Pipe creates a new system which calls `a`, then calls `b` with the output of `a` /// pub fn pipe<A, B, AMarker, BMarker>( /// mut a: A, /// mut b: B, /// ) -> impl FnMut(StaticSystemInput<A::In>, ParamSet<(A::Param, B::Param)>) -> B::Out /// where /// // We need A and B to be systems, add those bounds /// A: SystemParamFunction<AMarker>, /// B: SystemParamFunction<BMarker>, /// for<'a> B::In: SystemInput<Inner<'a> = A::Out>, /// { /// // The type of `params` is inferred based on the return of this function above /// move |StaticSystemInput(a_in), mut params| { /// let shared = a.run(a_in, params.p0()); /// b.run(shared, params.p1()) /// } /// } /// /// // Usage example for `pipe`: /// fn main() { /// let mut world = World::default(); /// world.insert_resource(Message("42".to_string())); /// /// // pipe the `parse_message_system`'s output into the `filter_system`s input. /// // Type annotations should only needed when using `StaticSystemInput` as input /// // AND the input type isn't constrained by nearby code. /// let mut piped_system = IntoSystem::<(), Option<usize>, _>::into_system(pipe(parse_message, filter)); /// piped_system.initialize(&mut world); /// assert_eq!(piped_system.run((), &mut world).unwrap(), Some(42)); /// } /// /// #[derive(Resource)] /// struct Message(String); /// /// fn parse_message(message: Res<Message>) -> Result<usize, ParseIntError> { /// message.0.parse::<usize>() /// } /// /// fn filter(In(result): In<Result<usize, ParseIntError>>) -> Option<usize> { /// result.ok().filter(|&n| n < 100) /// } /// ``` /// [`PipeSystem`]: crate::system::PipeSystem /// [`ParamSet`]: crate::system::ParamSet #[diagnostic::on_unimplemented( message = "`{Self}` is not a valid system", label = "invalid system" )] pub trait SystemParamFunction<Marker>: Send + Sync + 'static { /// The input type of this system. See [`System::In`]. type In: SystemInput; /// The return type of this system. See [`System::Out`]. type Out; /// The [`SystemParam`]/s used by this system to access the [`World`]. type Param: SystemParam; /// Executes this system once. See [`System::run`] or [`System::run_unsafe`]. fn run( &mut self, input: <Self::In as SystemInput>::Inner<'_>, param_value: SystemParamItem<Self::Param>, ) -> Self::Out; } /// A marker type used to distinguish function systems with and without input. #[doc(hidden)] pub struct HasSystemInput; macro_rules! impl_system_function { ($($param: ident),*) => { #[expect( clippy::allow_attributes, reason = "This is within a macro, and as such, the below lints may not always apply." )] #[allow( non_snake_case, reason = "Certain variable names are provided by the caller, not by us." )] impl<Out, Func, $($param: SystemParam),*> SystemParamFunction<fn($($param,)*) -> Out> for Func where Func: Send + Sync + 'static, for <'a> &'a mut Func:
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/system_name.rs
crates/bevy_ecs/src/system/system_name.rs
use crate::{ change_detection::Tick, prelude::World, query::FilteredAccessSet, system::{ExclusiveSystemParam, ReadOnlySystemParam, SystemMeta, SystemParam}, world::unsafe_world_cell::UnsafeWorldCell, }; use bevy_utils::prelude::DebugName; use derive_more::derive::{Display, Into}; /// [`SystemParam`] that returns the name of the system which it is used in. /// /// This is not a reliable identifier, it is more so useful for debugging or logging. /// /// # Examples /// /// ``` /// # use bevy_ecs::system::SystemName; /// # use bevy_ecs::system::SystemParam; /// /// #[derive(SystemParam)] /// struct Logger { /// system_name: SystemName, /// } /// /// impl Logger { /// fn log(&mut self, message: &str) { /// eprintln!("{}: {}", self.system_name, message); /// } /// } /// /// fn system1(mut logger: Logger) { /// // Prints: "crate_name::mod_name::system1: Hello". /// logger.log("Hello"); /// } /// ``` #[derive(Debug, Into, Display)] pub struct SystemName(DebugName); impl SystemName { /// Gets the name of the system. pub fn name(&self) -> DebugName { self.0.clone() } } // SAFETY: no component value access unsafe impl SystemParam for SystemName { type State = (); type Item<'w, 's> = SystemName; fn init_state(_world: &mut World) -> Self::State {} fn init_access( _state: &Self::State, _system_meta: &mut SystemMeta, _component_access_set: &mut FilteredAccessSet, _world: &mut World, ) { } #[inline] unsafe fn get_param<'w, 's>( _state: &'s mut Self::State, system_meta: &SystemMeta, _world: UnsafeWorldCell<'w>, _change_tick: Tick, ) -> Self::Item<'w, 's> { SystemName(system_meta.name.clone()) } } // SAFETY: Only reads internal system state unsafe impl ReadOnlySystemParam for SystemName {} impl ExclusiveSystemParam for SystemName { type State = (); type Item<'s> = SystemName; fn init(_world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {} fn get_param<'s>(_state: &'s mut Self::State, system_meta: &SystemMeta) -> Self::Item<'s> { SystemName(system_meta.name.clone()) } } #[cfg(test)] #[cfg(all(feature = "trace", feature = "debug"))] mod tests { use crate::{ system::{IntoSystem, RunSystemOnce, SystemName}, world::World, }; use alloc::{borrow::ToOwned, string::String}; #[test] fn test_system_name_regular_param() { fn testing(name: SystemName) -> String { name.name().as_string() } let mut world = World::default(); let id = world.register_system(testing); let name = world.run_system(id).unwrap(); assert!(name.ends_with("testing")); } #[test] fn test_system_name_exclusive_param() { fn testing(_world: &mut World, name: SystemName) -> String { name.name().as_string() } let mut world = World::default(); let id = world.register_system(testing); let name = world.run_system(id).unwrap(); assert!(name.ends_with("testing")); } #[test] fn test_closure_system_name_regular_param() { let mut world = World::default(); let system = IntoSystem::into_system(|name: SystemName| name.name().to_owned()).with_name("testing"); let name = world.run_system_once(system).unwrap().as_string(); assert_eq!(name, "testing"); } #[test] fn test_exclusive_closure_system_name_regular_param() { let mut world = World::default(); let system = IntoSystem::into_system(|_world: &mut World, name: SystemName| name.name().to_owned()) .with_name("testing"); let name = world.run_system_once(system).unwrap().as_string(); assert_eq!(name, "testing"); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/system.rs
crates/bevy_ecs/src/system/system.rs
#![expect( clippy::module_inception, reason = "This instance of module inception is being discussed; see #17353." )] use bevy_utils::prelude::DebugName; use bitflags::bitflags; use core::fmt::{Debug, Display}; use log::warn; use crate::{ change_detection::{CheckChangeTicks, Tick}, error::BevyError, query::FilteredAccessSet, schedule::InternedSystemSet, system::{input::SystemInput, SystemIn}, world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, World}, }; use alloc::{boxed::Box, vec::Vec}; use core::any::{Any, TypeId}; use super::{IntoSystem, SystemParamValidationError}; bitflags! { /// Bitflags representing system states and requirements. #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct SystemStateFlags: u8 { /// Set if system cannot be sent across threads const NON_SEND = 1 << 0; /// Set if system requires exclusive World access const EXCLUSIVE = 1 << 1; /// Set if system has deferred buffers. const DEFERRED = 1 << 2; } } /// An ECS system that can be added to a [`Schedule`](crate::schedule::Schedule) /// /// Systems are functions with all arguments implementing /// [`SystemParam`](crate::system::SystemParam). /// /// Systems are added to an application using `App::add_systems(Update, my_system)` /// or similar methods, and will generally run once per pass of the main loop. /// /// Systems are executed in parallel, in opportunistic order; data access is managed automatically. /// It's possible to specify explicit execution order between specific systems, /// see [`IntoScheduleConfigs`](crate::schedule::IntoScheduleConfigs). #[diagnostic::on_unimplemented(message = "`{Self}` is not a system", label = "invalid system")] pub trait System: Send + Sync + 'static { /// The system's input. type In: SystemInput; /// The system's output. type Out; /// Returns the system's name. fn name(&self) -> DebugName; /// Returns the [`TypeId`] of the underlying system type. #[inline] fn type_id(&self) -> TypeId { TypeId::of::<Self>() } /// Returns the [`SystemStateFlags`] of the system. fn flags(&self) -> SystemStateFlags; /// Returns true if the system is [`Send`]. #[inline] fn is_send(&self) -> bool { !self.flags().intersects(SystemStateFlags::NON_SEND) } /// Returns true if the system must be run exclusively. #[inline] fn is_exclusive(&self) -> bool { self.flags().intersects(SystemStateFlags::EXCLUSIVE) } /// Returns true if system has deferred buffers. #[inline] fn has_deferred(&self) -> bool { self.flags().intersects(SystemStateFlags::DEFERRED) } /// Runs the system with the given input in the world. Unlike [`System::run`], this function /// can be called in parallel with other systems and may break Rust's aliasing rules /// if used incorrectly, making it unsafe to call. /// /// Unlike [`System::run`], this will not apply deferred parameters, which must be independently /// applied by calling [`System::apply_deferred`] at later point in time. /// /// # Safety /// /// - The caller must ensure that [`world`](UnsafeWorldCell) has permission to access any world data /// registered in the access returned from [`System::initialize`]. There must be no conflicting /// simultaneous accesses while the system is running. /// - If [`System::is_exclusive`] returns `true`, then it must be valid to call /// [`UnsafeWorldCell::world_mut`] on `world`. unsafe fn run_unsafe( &mut self, input: SystemIn<'_, Self>, world: UnsafeWorldCell, ) -> Result<Self::Out, RunSystemError>; /// Refresh the inner pointer based on the latest hot patch jump table #[cfg(feature = "hotpatching")] fn refresh_hotpatch(&mut self); /// Runs the system with the given input in the world. /// /// For [read-only](ReadOnlySystem) systems, see [`run_readonly`], which can be called using `&World`. /// /// Unlike [`System::run_unsafe`], this will apply deferred parameters *immediately*. /// /// [`run_readonly`]: ReadOnlySystem::run_readonly fn run( &mut self, input: SystemIn<'_, Self>, world: &mut World, ) -> Result<Self::Out, RunSystemError> { let ret = self.run_without_applying_deferred(input, world)?; self.apply_deferred(world); Ok(ret) } /// Runs the system with the given input in the world. /// /// [`run_readonly`]: ReadOnlySystem::run_readonly fn run_without_applying_deferred( &mut self, input: SystemIn<'_, Self>, world: &mut World, ) -> Result<Self::Out, RunSystemError> { let world_cell = world.as_unsafe_world_cell(); // SAFETY: // - We have exclusive access to the entire world. unsafe { self.validate_param_unsafe(world_cell) }?; // SAFETY: // - We have exclusive access to the entire world. unsafe { self.run_unsafe(input, world_cell) } } /// Applies any [`Deferred`](crate::system::Deferred) system parameters (or other system buffers) of this system to the world. /// /// This is where [`Commands`](crate::system::Commands) get applied. fn apply_deferred(&mut self, world: &mut World); /// Enqueues any [`Deferred`](crate::system::Deferred) system parameters (or other system buffers) /// of this system into the world's command buffer. fn queue_deferred(&mut self, world: DeferredWorld); /// Validates that all parameters can be acquired and that system can run without panic. /// Built-in executors use this to prevent invalid systems from running. /// /// However calling and respecting [`System::validate_param_unsafe`] or its safe variant /// is not a strict requirement, both [`System::run`] and [`System::run_unsafe`] /// should provide their own safety mechanism to prevent undefined behavior. /// /// This method has to be called directly before [`System::run_unsafe`] with no other (relevant) /// world mutations in between. Otherwise, while it won't lead to any undefined behavior, /// the validity of the param may change. /// /// # Safety /// /// - The caller must ensure that [`world`](UnsafeWorldCell) has permission to access any world data /// registered in the access returned from [`System::initialize`]. There must be no conflicting /// simultaneous accesses while the system is running. unsafe fn validate_param_unsafe( &mut self, world: UnsafeWorldCell, ) -> Result<(), SystemParamValidationError>; /// Safe version of [`System::validate_param_unsafe`]. /// that runs on exclusive, single-threaded `world` pointer. fn validate_param(&mut self, world: &World) -> Result<(), SystemParamValidationError> { let world_cell = world.as_unsafe_world_cell_readonly(); // SAFETY: // - We have exclusive access to the entire world. unsafe { self.validate_param_unsafe(world_cell) } } /// Initialize the system. /// /// Returns a [`FilteredAccessSet`] with the access required to run the system. fn initialize(&mut self, _world: &mut World) -> FilteredAccessSet; /// Checks any [`Tick`]s stored on this system and wraps their value if they get too old. /// /// This method must be called periodically to ensure that change detection behaves correctly. /// When using bevy's default configuration, this will be called for you as needed. fn check_change_tick(&mut self, check: CheckChangeTicks); /// Returns the system's default [system sets](crate::schedule::SystemSet). /// /// Each system will create a default system set that contains the system. fn default_system_sets(&self) -> Vec<InternedSystemSet> { Vec::new() } /// Gets the tick indicating the last time this system ran. fn get_last_run(&self) -> Tick; /// Overwrites the tick indicating the last time this system ran. /// /// # Warning /// This is a complex and error-prone operation, that can have unexpected consequences on any system relying on this code. /// However, it can be an essential escape hatch when, for example, /// you are trying to synchronize representations using change detection and need to avoid infinite recursion. fn set_last_run(&mut self, last_run: Tick); } /// [`System`] types that do not modify the [`World`] when run. /// This is implemented for any systems whose parameters all implement [`ReadOnlySystemParam`]. /// /// Note that systems which perform [deferred](System::apply_deferred) mutations (such as with [`Commands`]) /// may implement this trait. /// /// [`ReadOnlySystemParam`]: crate::system::ReadOnlySystemParam /// [`Commands`]: crate::system::Commands /// /// # Safety /// /// This must only be implemented for system types which do not mutate the `World` /// when [`System::run_unsafe`] is called. #[diagnostic::on_unimplemented( message = "`{Self}` is not a read-only system", label = "invalid read-only system" )] pub unsafe trait ReadOnlySystem: System { /// Runs this system with the given input in the world. /// /// Unlike [`System::run`], this can be called with a shared reference to the world, /// since this system is known not to modify the world. fn run_readonly( &mut self, input: SystemIn<'_, Self>, world: &World, ) -> Result<Self::Out, RunSystemError> { let world = world.as_unsafe_world_cell_readonly(); // SAFETY: // - We have read-only access to the entire world. unsafe { self.validate_param_unsafe(world) }?; // SAFETY: // - We have read-only access to the entire world. unsafe { self.run_unsafe(input, world) } } } /// A convenience type alias for a boxed [`System`] trait object. pub type BoxedSystem<In = (), Out = ()> = Box<dyn System<In = In, Out = Out>>; /// A convenience type alias for a boxed [`ReadOnlySystem`] trait object. pub type BoxedReadOnlySystem<In = (), Out = ()> = Box<dyn ReadOnlySystem<In = In, Out = Out>>; pub(crate) fn check_system_change_tick( last_run: &mut Tick, check: CheckChangeTicks, system_name: DebugName, ) { if last_run.check_tick(check) { let age = check.present_tick().relative_to(*last_run).get(); warn!( "System '{system_name}' has not run for {age} ticks. \ Changes older than {} ticks will not be detected.", Tick::MAX.get() - 1, ); } } impl<In, Out> Debug for dyn System<In = In, Out = Out> where In: SystemInput + 'static, Out: 'static, { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("System") .field("name", &self.name()) .field("is_exclusive", &self.is_exclusive()) .field("is_send", &self.is_send()) .finish_non_exhaustive() } } /// Trait used to run a system immediately on a [`World`]. /// /// # Warning /// This function is not an efficient method of running systems and it's meant to be used as a utility /// for testing and/or diagnostics. /// /// Systems called through [`run_system_once`](RunSystemOnce::run_system_once) do not hold onto any state, /// as they are created and destroyed every time [`run_system_once`](RunSystemOnce::run_system_once) is called. /// Practically, this means that [`Local`](crate::system::Local) variables are /// reset on every run and change detection does not work. /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_ecs::system::RunSystemOnce; /// #[derive(Resource, Default)] /// struct Counter(u8); /// /// fn increment(mut counter: Local<Counter>) { /// counter.0 += 1; /// println!("{}", counter.0); /// } /// /// let mut world = World::default(); /// world.run_system_once(increment); // prints 1 /// world.run_system_once(increment); // still prints 1 /// ``` /// /// If you do need systems to hold onto state between runs, use [`World::run_system_cached`](World::run_system_cached) /// or [`World::run_system`](World::run_system). /// /// # Usage /// Typically, to test a system, or to extract specific diagnostics information from a world, /// you'd need a [`Schedule`](crate::schedule::Schedule) to run the system. This can create redundant boilerplate code /// when writing tests or trying to quickly iterate on debug specific systems. /// /// For these situations, this function can be useful because it allows you to execute a system /// immediately with some custom input and retrieve its output without requiring the necessary boilerplate. /// /// # Examples /// /// ## Immediate Command Execution /// /// This usage is helpful when trying to test systems or functions that operate on [`Commands`](crate::system::Commands): /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_ecs::system::RunSystemOnce; /// let mut world = World::default(); /// let entity = world.run_system_once(|mut commands: Commands| { /// commands.spawn_empty().id() /// }).unwrap(); /// # assert!(world.get_entity(entity).is_ok()); /// ``` /// /// ## Immediate Queries /// /// This usage is helpful when trying to run an arbitrary query on a world for testing or debugging purposes: /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_ecs::system::RunSystemOnce; /// /// #[derive(Component)] /// struct T(usize); /// /// let mut world = World::default(); /// world.spawn(T(0)); /// world.spawn(T(1)); /// world.spawn(T(1)); /// let count = world.run_system_once(|query: Query<&T>| { /// query.iter().filter(|t| t.0 == 1).count() /// }).unwrap(); /// /// # assert_eq!(count, 2); /// ``` /// /// Note that instead of closures you can also pass in regular functions as systems: /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_ecs::system::RunSystemOnce; /// /// #[derive(Component)] /// struct T(usize); /// /// fn count(query: Query<&T>) -> usize { /// query.iter().filter(|t| t.0 == 1).count() /// } /// /// let mut world = World::default(); /// world.spawn(T(0)); /// world.spawn(T(1)); /// world.spawn(T(1)); /// let count = world.run_system_once(count).unwrap(); /// /// # assert_eq!(count, 2); /// ``` pub trait RunSystemOnce: Sized { /// Tries to run a system and apply its deferred parameters. fn run_system_once<T, Out, Marker>(self, system: T) -> Result<Out, RunSystemError> where T: IntoSystem<(), Out, Marker>, { self.run_system_once_with(system, ()) } /// Tries to run a system with given input and apply deferred parameters. fn run_system_once_with<T, In, Out, Marker>( self, system: T, input: SystemIn<'_, T::System>, ) -> Result<Out, RunSystemError> where T: IntoSystem<In, Out, Marker>, In: SystemInput; } impl RunSystemOnce for &mut World { fn run_system_once_with<T, In, Out, Marker>( self, system: T, input: SystemIn<'_, T::System>, ) -> Result<Out, RunSystemError> where T: IntoSystem<In, Out, Marker>, In: SystemInput, { let mut system: T::System = IntoSystem::into_system(system); system.initialize(self); system.run(input, self) } } /// Running system failed. #[derive(Debug)] pub enum RunSystemError { /// System could not be run due to parameters that failed validation. /// This is not considered an error. Skipped(SystemParamValidationError), /// System returned an error or failed required parameter validation. Failed(BevyError), } impl Display for RunSystemError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Self::Skipped(err) => write!( f, "System did not run due to failed parameter validation: {err}" ), Self::Failed(err) => write!(f, "{err}"), } } } impl<E: Any> From<E> for RunSystemError where BevyError: From<E>, { fn from(mut value: E) -> Self { // Specialize the impl so that a skipped `SystemParamValidationError` // is converted to `Skipped` instead of `Failed`. // Note that the `downcast_mut` check is based on the static type, // and can be optimized out after monomorphization. let any: &mut dyn Any = &mut value; if let Some(err) = any.downcast_mut::<SystemParamValidationError>() && err.skipped { return Self::Skipped(core::mem::replace(err, SystemParamValidationError::EMPTY)); } Self::Failed(From::from(value)) } } #[cfg(test)] mod tests { use super::*; use crate::prelude::*; use alloc::string::ToString; #[test] fn run_system_once() { #[derive(Resource)] struct T(usize); fn system(In(n): In<usize>, mut commands: Commands) -> usize { commands.insert_resource(T(n)); n + 1 } let mut world = World::default(); let n = world.run_system_once_with(system, 1).unwrap(); assert_eq!(n, 2); assert_eq!(world.resource::<T>().0, 1); } #[derive(Resource, Default, PartialEq, Debug)] struct Counter(u8); fn count_up(mut counter: ResMut<Counter>) { counter.0 += 1; } #[test] fn run_two_systems() { let mut world = World::new(); world.init_resource::<Counter>(); assert_eq!(*world.resource::<Counter>(), Counter(0)); world.run_system_once(count_up).unwrap(); assert_eq!(*world.resource::<Counter>(), Counter(1)); world.run_system_once(count_up).unwrap(); assert_eq!(*world.resource::<Counter>(), Counter(2)); } #[derive(Component)] struct A; fn spawn_entity(mut commands: Commands) { commands.spawn(A); } #[test] fn command_processing() { let mut world = World::new(); assert_eq!(world.entities.count_spawned(), 0); world.run_system_once(spawn_entity).unwrap(); assert_eq!(world.entities.count_spawned(), 1); } #[test] fn non_send_resources() { fn non_send_count_down(mut ns: NonSendMut<Counter>) { ns.0 -= 1; } let mut world = World::new(); world.insert_non_send_resource(Counter(10)); assert_eq!(*world.non_send_resource::<Counter>(), Counter(10)); world.run_system_once(non_send_count_down).unwrap(); assert_eq!(*world.non_send_resource::<Counter>(), Counter(9)); } #[test] fn run_system_once_invalid_params() { #[derive(Resource)] struct T; fn system(_: Res<T>) {} let mut world = World::default(); // This fails because `T` has not been added to the world yet. let result = world.run_system_once(system); assert!(matches!(result, Err(RunSystemError::Failed { .. }))); let expected = "Resource does not exist"; let actual = result.unwrap_err().to_string(); assert!( actual.contains(expected), "Expected error message to contain `{}` but got `{}`", expected, actual ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/mod.rs
crates/bevy_ecs/src/system/mod.rs
//! Tools for controlling behavior in an ECS application. //! //! Systems define how an ECS based application behaves. //! Systems are added to a [`Schedule`](crate::schedule::Schedule), which is then run. //! A system is usually written as a normal function, which is automatically converted into a system. //! //! System functions can have parameters, through which one can query and mutate Bevy ECS state. //! Only types that implement [`SystemParam`] can be used, automatically fetching data from //! the [`World`]. //! //! System functions often look like this: //! //! ``` //! # use bevy_ecs::prelude::*; //! # //! # #[derive(Component)] //! # struct Player { alive: bool } //! # #[derive(Component)] //! # struct Score(u32); //! # #[derive(Resource)] //! # struct Round(u32); //! # //! fn update_score_system( //! mut query: Query<(&Player, &mut Score)>, //! mut round: ResMut<Round>, //! ) { //! for (player, mut score) in &mut query { //! if player.alive { //! score.0 += round.0; //! } //! } //! round.0 += 1; //! } //! # bevy_ecs::system::assert_is_system(update_score_system); //! ``` //! //! # System ordering //! //! By default, the execution of systems is parallel and not deterministic. //! Not all systems can run together: if a system mutably accesses data, //! no other system that reads or writes that data can be run at the same time. //! These systems are said to be **incompatible**. //! //! The relative order in which incompatible systems are run matters. //! When this is not specified, a **system order ambiguity** exists in your schedule. //! You can **explicitly order** systems: //! //! - by calling the `.before(this_system)` or `.after(that_system)` methods when adding them to your schedule //! - by adding them to a [`SystemSet`], and then using `.configure_sets(ThisSet.before(ThatSet))` syntax to configure many systems at once //! - through the use of `.add_systems((system_a, system_b, system_c).chain())` //! //! [`SystemSet`]: crate::schedule::SystemSet //! //! ## Example //! //! ``` //! # use bevy_ecs::prelude::*; //! # let mut schedule = Schedule::default(); //! # let mut world = World::new(); //! // Configure these systems to run in order using `chain()`. //! schedule.add_systems((print_first, print_last).chain()); //! // Prints "HelloWorld!" //! schedule.run(&mut world); //! //! // Configure this system to run in between the other two systems //! // using explicit dependencies. //! schedule.add_systems(print_mid.after(print_first).before(print_last)); //! // Prints "Hello, World!" //! schedule.run(&mut world); //! //! fn print_first() { //! print!("Hello"); //! } //! fn print_mid() { //! print!(", "); //! } //! fn print_last() { //! println!("World!"); //! } //! ``` //! //! # System return type //! //! Systems added to a schedule through [`add_systems`](crate::schedule::Schedule) may either return //! empty `()` or a [`Result`](crate::error::Result). Other contexts (like one shot systems) allow //! systems to return arbitrary values. //! //! # System parameter list //! Following is the complete list of accepted types as system parameters: //! //! - [`Query`] //! - [`Res`] and `Option<Res>` //! - [`ResMut`] and `Option<ResMut>` //! - [`Commands`] //! - [`Local`] //! - [`MessageReader`](crate::message::MessageReader) //! - [`MessageWriter`](crate::message::MessageWriter) //! - [`NonSend`] and `Option<NonSend>` //! - [`NonSendMut`] and `Option<NonSendMut>` //! - [`RemovedComponents`](crate::lifecycle::RemovedComponents) //! - [`SystemName`] //! - [`SystemChangeTick`] //! - [`Archetypes`](crate::archetype::Archetypes) (Provides Archetype metadata) //! - [`Bundles`](crate::bundle::Bundles) (Provides Bundles metadata) //! - [`Components`](crate::component::Components) (Provides Components metadata) //! - [`Entities`](crate::entity::Entities) (Provides Entities metadata) //! - All tuples between 1 to 16 elements where each element implements [`SystemParam`] //! - [`ParamSet`] //! - [`()` (unit primitive type)](https://doc.rust-lang.org/stable/std/primitive.unit.html) //! //! In addition, the following parameters can be used when constructing a dynamic system with [`SystemParamBuilder`], //! but will only provide an empty value when used with an ordinary system: //! //! - [`FilteredResources`](crate::world::FilteredResources) //! - [`FilteredResourcesMut`](crate::world::FilteredResourcesMut) //! - [`DynSystemParam`] //! - [`Vec<P>`] where `P: SystemParam` //! - [`ParamSet<Vec<P>>`] where `P: SystemParam` //! //! [`Vec<P>`]: alloc::vec::Vec mod adapter_system; mod builder; mod combinator; mod commands; mod exclusive_function_system; mod exclusive_system_param; mod function_system; mod input; mod observer_system; mod query; mod schedule_system; mod system; mod system_name; mod system_param; mod system_registry; use core::any::TypeId; pub use adapter_system::*; pub use builder::*; pub use combinator::*; pub use commands::*; pub use exclusive_function_system::*; pub use exclusive_system_param::*; pub use function_system::*; pub use input::*; pub use observer_system::*; pub use query::*; pub use schedule_system::*; pub use system::*; pub use system_name::*; pub use system_param::*; pub use system_registry::*; use crate::world::{FromWorld, World}; /// Conversion trait to turn something into a [`System`]. /// /// Use this to get a system from a function. Also note that every system implements this trait as /// well. /// /// # Usage notes /// /// This trait should only be used as a bound for trait implementations or as an /// argument to a function. If a system needs to be returned from a function or /// stored somewhere, use [`System`] instead of this trait. /// /// # Examples /// /// ``` /// use bevy_ecs::prelude::*; /// /// fn my_system_function(a_usize_local: Local<usize>) {} /// /// let system = IntoSystem::into_system(my_system_function); /// ``` // This trait has to be generic because we have potentially overlapping impls, in particular // because Rust thinks a type could impl multiple different `FnMut` combinations // even though none can currently #[diagnostic::on_unimplemented( message = "`{Self}` is not a valid system with input `{In}` and output `{Out}`", label = "invalid system" )] pub trait IntoSystem<In: SystemInput, Out, Marker>: Sized { /// The type of [`System`] that this instance converts into. type System: System<In = In, Out = Out>; /// Turns this value into its corresponding [`System`]. fn into_system(this: Self) -> Self::System; /// Pass the output of this system `A` into a second system `B`, creating a new compound system. /// /// The second system must have [`In<T>`](crate::system::In) as its first parameter, /// where `T` is the return type of the first system. fn pipe<B, BIn, BOut, MarkerB>(self, system: B) -> IntoPipeSystem<Self, B> where Out: 'static, B: IntoSystem<BIn, BOut, MarkerB>, for<'a> BIn: SystemInput<Inner<'a> = Out>, { IntoPipeSystem::new(self, system) } /// Pass the output of this system into the passed function `f`, creating a new system that /// outputs the value returned from the function. /// /// ``` /// # use bevy_ecs::prelude::*; /// # let mut schedule = Schedule::default(); /// // Ignores the output of a system that may fail. /// schedule.add_systems(my_system.map(drop)); /// # let mut world = World::new(); /// # world.insert_resource(T); /// # schedule.run(&mut world); /// /// # #[derive(Resource)] struct T; /// # type Err = (); /// fn my_system(res: Res<T>) -> Result<(), Err> { /// // ... /// # Err(()) /// } /// ``` fn map<T, F>(self, f: F) -> IntoAdapterSystem<F, Self> where F: Send + Sync + 'static + FnMut(Out) -> T, { IntoAdapterSystem::new(f, self) } /// Passes a mutable reference to `value` as input to the system each run, /// turning it into a system that takes no input. /// /// `Self` can have any [`SystemInput`] type that takes a mutable reference /// to `T`, such as [`InMut`]. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// fn my_system(InMut(value): InMut<usize>) { /// *value += 1; /// if *value > 10 { /// println!("Value is greater than 10!"); /// } /// } /// /// # let mut schedule = Schedule::default(); /// schedule.add_systems(my_system.with_input(0)); /// # bevy_ecs::system::assert_is_system(my_system.with_input(0)); /// ``` fn with_input<T>(self, value: T) -> WithInputWrapper<Self::System, T> where for<'i> In: SystemInput<Inner<'i> = &'i mut T>, T: Send + Sync + 'static, { WithInputWrapper::new(self, value) } /// Passes a mutable reference to a value of type `T` created via /// [`FromWorld`] as input to the system each run, turning it into a system /// that takes no input. /// /// `Self` can have any [`SystemInput`] type that takes a mutable reference /// to `T`, such as [`InMut`]. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// struct MyData { /// value: usize, /// } /// /// impl FromWorld for MyData { /// fn from_world(world: &mut World) -> Self { /// // Fetch from the world the data needed to create `MyData` /// # MyData { value: 0 } /// } /// } /// /// fn my_system(InMut(data): InMut<MyData>) { /// data.value += 1; /// if data.value > 10 { /// println!("Value is greater than 10!"); /// } /// } /// # let mut schedule = Schedule::default(); /// schedule.add_systems(my_system.with_input_from::<MyData>()); /// # bevy_ecs::system::assert_is_system(my_system.with_input_from::<MyData>()); /// ``` fn with_input_from<T>(self) -> WithInputFromWrapper<Self::System, T> where for<'i> In: SystemInput<Inner<'i> = &'i mut T>, T: FromWorld + Send + Sync + 'static, { WithInputFromWrapper::new(self) } /// Get the [`TypeId`] of the [`System`] produced after calling [`into_system`](`IntoSystem::into_system`). #[inline] fn system_type_id(&self) -> TypeId { TypeId::of::<Self::System>() } } // All systems implicitly implement IntoSystem. impl<T: System> IntoSystem<T::In, T::Out, ()> for T { type System = T; fn into_system(this: Self) -> Self { this } } /// Ensure that a given function is a [system](System). /// /// This should be used when writing doc examples, /// to confirm that systems used in an example are /// valid systems. /// /// # Examples /// /// The following example will panic when run since the /// system's parameters mutably access the same component /// multiple times. /// /// ```should_panic /// # use bevy_ecs::{prelude::*, system::assert_is_system}; /// # /// # #[derive(Component)] /// # struct Transform; /// # /// fn my_system(query1: Query<&mut Transform>, query2: Query<&mut Transform>) { /// // ... /// } /// /// assert_is_system(my_system); /// ``` pub fn assert_is_system<In: SystemInput, Out: 'static, Marker>( system: impl IntoSystem<In, Out, Marker>, ) { let mut system = IntoSystem::into_system(system); // Initialize the system, which will panic if the system has access conflicts. let mut world = World::new(); system.initialize(&mut world); } /// Ensure that a given function is a [read-only system](ReadOnlySystem). /// /// This should be used when writing doc examples, /// to confirm that systems used in an example are /// valid systems. /// /// # Examples /// /// The following example will fail to compile /// since the system accesses a component mutably. /// /// ```compile_fail /// # use bevy_ecs::{prelude::*, system::assert_is_read_only_system}; /// # /// # #[derive(Component)] /// # struct Transform; /// # /// fn my_system(query: Query<&mut Transform>) { /// // ... /// } /// /// assert_is_read_only_system(my_system); /// ``` pub fn assert_is_read_only_system<In, Out, Marker, S>(system: S) where In: SystemInput, Out: 'static, S: IntoSystem<In, Out, Marker>, S::System: ReadOnlySystem, { assert_is_system(system); } /// Ensures that the provided system doesn't conflict with itself. /// /// This function will panic if the provided system conflict with itself. /// /// Note: this will run the system on an empty world. pub fn assert_system_does_not_conflict<Out, Params, S: IntoSystem<(), Out, Params>>(sys: S) { let mut world = World::new(); let mut system = IntoSystem::into_system(sys); system.initialize(&mut world); system.run((), &mut world).unwrap(); } #[cfg(test)] #[expect(clippy::print_stdout, reason = "Allowed in tests.")] mod tests { use alloc::{vec, vec::Vec}; use bevy_utils::default; use core::any::TypeId; use std::println; use crate::{ archetype::Archetypes, bundle::Bundles, change_detection::DetectChanges, component::{Component, Components}, entity::{Entities, Entity}, error::Result, lifecycle::RemovedComponents, name::Name, prelude::{Add, AnyOf, EntityRef, On}, query::{Added, Changed, Or, SpawnDetails, Spawned, With, Without}, resource::Resource, schedule::{ common_conditions::resource_exists, ApplyDeferred, IntoScheduleConfigs, Schedule, SystemCondition, }, system::{ Commands, ExclusiveMarker, In, InMut, IntoSystem, Local, NonSend, NonSendMut, ParamSet, Query, Res, ResMut, Single, StaticSystemParam, System, SystemState, }, world::{DeferredWorld, EntityMut, FromWorld, World}, }; use super::ScheduleSystem; #[derive(Resource, PartialEq, Debug)] enum SystemRan { Yes, No, } #[derive(Component, Debug, Eq, PartialEq, Default)] struct A; #[derive(Component)] struct B; #[derive(Component)] struct C; #[derive(Component)] struct D; #[derive(Component)] struct E; #[derive(Component)] struct F; #[derive(Resource)] struct ResA; #[derive(Resource)] struct ResB; #[derive(Resource)] struct ResC; #[derive(Resource)] struct ResD; #[derive(Resource)] struct ResE; #[derive(Resource)] struct ResF; #[derive(Component, Debug)] struct W<T>(T); #[test] fn simple_system() { fn sys(query: Query<&A>) { for a in &query { println!("{a:?}"); } } let mut system = IntoSystem::into_system(sys); let mut world = World::new(); world.spawn(A); system.initialize(&mut world); system.run((), &mut world).unwrap(); } fn run_system<Marker, S: IntoScheduleConfigs<ScheduleSystem, Marker>>( world: &mut World, system: S, ) { let mut schedule = Schedule::default(); schedule.add_systems(system); schedule.run(world); } #[test] fn get_many_is_ordered() { use crate::resource::Resource; const ENTITIES_COUNT: usize = 1000; #[derive(Resource)] struct EntitiesArray(Vec<Entity>); fn query_system( mut ran: ResMut<SystemRan>, entities_array: Res<EntitiesArray>, q: Query<&W<usize>>, ) { let entities_array: [Entity; ENTITIES_COUNT] = entities_array.0.clone().try_into().unwrap(); for (i, w) in (0..ENTITIES_COUNT).zip(q.get_many(entities_array).unwrap()) { assert_eq!(i, w.0); } *ran = SystemRan::Yes; } fn query_system_mut( mut ran: ResMut<SystemRan>, entities_array: Res<EntitiesArray>, mut q: Query<&mut W<usize>>, ) { let entities_array: [Entity; ENTITIES_COUNT] = entities_array.0.clone().try_into().unwrap(); for (i, w) in (0..ENTITIES_COUNT).zip(q.get_many_mut(entities_array).unwrap()) { assert_eq!(i, w.0); } *ran = SystemRan::Yes; } let mut world = World::default(); world.insert_resource(SystemRan::No); let entity_ids = (0..ENTITIES_COUNT) .map(|i| world.spawn(W(i)).id()) .collect(); world.insert_resource(EntitiesArray(entity_ids)); run_system(&mut world, query_system); assert_eq!(*world.resource::<SystemRan>(), SystemRan::Yes); world.insert_resource(SystemRan::No); run_system(&mut world, query_system_mut); assert_eq!(*world.resource::<SystemRan>(), SystemRan::Yes); } #[test] fn or_param_set_system() { // Regression test for issue #762 fn query_system( mut ran: ResMut<SystemRan>, mut set: ParamSet<( Query<(), Or<(Changed<A>, Changed<B>)>>, Query<(), Or<(Added<A>, Added<B>)>>, )>, ) { let changed = set.p0().iter().count(); let added = set.p1().iter().count(); assert_eq!(changed, 1); assert_eq!(added, 1); *ran = SystemRan::Yes; } let mut world = World::default(); world.insert_resource(SystemRan::No); world.spawn((A, B)); run_system(&mut world, query_system); assert_eq!(*world.resource::<SystemRan>(), SystemRan::Yes); } #[test] fn changed_resource_system() { use crate::resource::Resource; #[derive(Resource)] struct Flipper(bool); #[derive(Resource)] struct Added(usize); #[derive(Resource)] struct Changed(usize); fn incr_e_on_flip( value: Res<Flipper>, mut changed: ResMut<Changed>, mut added: ResMut<Added>, ) { if value.is_added() { added.0 += 1; } if value.is_changed() { changed.0 += 1; } } let mut world = World::default(); world.insert_resource(Flipper(false)); world.insert_resource(Added(0)); world.insert_resource(Changed(0)); let mut schedule = Schedule::default(); schedule.add_systems((incr_e_on_flip, ApplyDeferred, World::clear_trackers).chain()); schedule.run(&mut world); assert_eq!(world.resource::<Added>().0, 1); assert_eq!(world.resource::<Changed>().0, 1); schedule.run(&mut world); assert_eq!(world.resource::<Added>().0, 1); assert_eq!(world.resource::<Changed>().0, 1); world.resource_mut::<Flipper>().0 = true; schedule.run(&mut world); assert_eq!(world.resource::<Added>().0, 1); assert_eq!(world.resource::<Changed>().0, 2); } #[test] #[should_panic = "error[B0001]"] fn option_has_no_filter_with() { fn sys(_: Query<(Option<&A>, &mut B)>, _: Query<&mut B, Without<A>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] fn option_doesnt_remove_unrelated_filter_with() { fn sys(_: Query<(Option<&A>, &mut B, &A)>, _: Query<&mut B, Without<A>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] fn any_of_working() { fn sys(_: Query<AnyOf<(&mut A, &B)>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] fn any_of_with_and_without_common() { fn sys(_: Query<(&mut D, &C, AnyOf<(&A, &B)>)>, _: Query<&mut D, Without<C>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic] fn any_of_with_mut_and_ref() { fn sys(_: Query<AnyOf<(&mut A, &A)>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic] fn any_of_with_ref_and_mut() { fn sys(_: Query<AnyOf<(&A, &mut A)>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic] fn any_of_with_mut_and_option() { fn sys(_: Query<AnyOf<(&mut A, Option<&A>)>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] fn any_of_with_entity_and_mut() { fn sys(_: Query<AnyOf<(Entity, &mut A)>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] fn any_of_with_empty_and_mut() { fn sys(_: Query<AnyOf<((), &mut A)>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic = "error[B0001]"] fn any_of_has_no_filter_with() { fn sys(_: Query<(AnyOf<(&A, ())>, &mut B)>, _: Query<&mut B, Without<A>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic] fn any_of_with_conflicting() { fn sys(_: Query<AnyOf<(&mut A, &mut A)>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] fn any_of_has_filter_with_when_both_have_it() { fn sys(_: Query<(AnyOf<(&A, &A)>, &mut B)>, _: Query<&mut B, Without<A>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] fn any_of_doesnt_remove_unrelated_filter_with() { fn sys(_: Query<(AnyOf<(&A, ())>, &mut B, &A)>, _: Query<&mut B, Without<A>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] fn any_of_and_without() { fn sys(_: Query<(AnyOf<(&A, &B)>, &mut C)>, _: Query<&mut C, (Without<A>, Without<B>)>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic = "error[B0001]"] fn or_has_no_filter_with() { fn sys(_: Query<&mut B, Or<(With<A>, With<B>)>>, _: Query<&mut B, Without<A>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] fn or_has_filter_with_when_both_have_it() { fn sys(_: Query<&mut B, Or<(With<A>, With<A>)>>, _: Query<&mut B, Without<A>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] fn or_has_filter_with() { fn sys( _: Query<&mut C, Or<(With<A>, With<B>)>>, _: Query<&mut C, (Without<A>, Without<B>)>, ) { } let mut world = World::default(); run_system(&mut world, sys); } #[test] fn or_expanded_with_and_without_common() { fn sys(_: Query<&mut D, (With<A>, Or<(With<B>, With<C>)>)>, _: Query<&mut D, Without<A>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] fn or_expanded_nested_with_and_without_common() { fn sys( _: Query<&mut E, (Or<((With<B>, With<C>), (With<C>, With<D>))>, With<A>)>, _: Query<&mut E, (Without<B>, Without<D>)>, ) { } let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic = "error[B0001]"] fn or_expanded_nested_with_and_disjoint_without() { fn sys( _: Query<&mut E, (Or<((With<B>, With<C>), (With<C>, With<D>))>, With<A>)>, _: Query<&mut E, Without<D>>, ) { } let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic = "error[B0001]"] fn or_expanded_nested_or_with_and_disjoint_without() { fn sys( _: Query<&mut D, Or<(Or<(With<A>, With<B>)>, Or<(With<A>, With<C>)>)>>, _: Query<&mut D, Without<A>>, ) { } let mut world = World::default(); run_system(&mut world, sys); } #[test] fn or_expanded_nested_with_and_common_nested_without() { fn sys( _: Query<&mut D, Or<((With<A>, With<B>), (With<B>, With<C>))>>, _: Query<&mut D, Or<(Without<D>, Without<B>)>>, ) { } let mut world = World::default(); run_system(&mut world, sys); } #[test] fn or_with_without_and_compatible_with_without() { fn sys( _: Query<&mut C, Or<(With<A>, Without<B>)>>, _: Query<&mut C, (With<B>, Without<A>)>, ) { } let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic = "error[B0001]"] fn with_and_disjoint_or_empty_without() { fn sys(_: Query<&mut B, With<A>>, _: Query<&mut B, Or<((), Without<A>)>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic = "error[B0001]"] fn or_expanded_with_and_disjoint_nested_without() { fn sys( _: Query<&mut D, Or<(With<A>, With<B>)>>, _: Query<&mut D, Or<(Without<A>, Without<B>)>>, ) { } let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic = "error[B0001]"] fn or_expanded_nested_with_and_disjoint_nested_without() { fn sys( _: Query<&mut D, Or<((With<A>, With<B>), (With<B>, With<C>))>>, _: Query<&mut D, Or<(Without<A>, Without<B>)>>, ) { } let mut world = World::default(); run_system(&mut world, sys); } #[test] fn or_doesnt_remove_unrelated_filter_with() { fn sys(_: Query<&mut B, (Or<(With<A>, With<B>)>, With<A>)>, _: Query<&mut B, Without<A>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic] fn conflicting_query_mut_system() { fn sys(_q1: Query<&mut A>, _q2: Query<&mut A>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] fn disjoint_query_mut_system() { fn sys(_q1: Query<&mut A, With<B>>, _q2: Query<&mut A, Without<B>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] fn disjoint_query_mut_read_component_system() { fn sys(_q1: Query<(&mut A, &B)>, _q2: Query<&mut A, Without<B>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic] fn conflicting_query_immut_system() { fn sys(_q1: Query<&A>, _q2: Query<&mut A>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic] fn changed_trackers_or_conflict() { fn sys(_: Query<&mut A>, _: Query<(), Or<(Changed<A>,)>>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] fn query_set_system() { fn sys(mut _set: ParamSet<(Query<&mut A>, Query<&A>)>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic] fn conflicting_query_with_query_set_system() { fn sys(_query: Query<&mut A>, _set: ParamSet<(Query<&mut A>, Query<&B>)>) {} let mut world = World::default(); run_system(&mut world, sys); } #[test] #[should_panic] fn conflicting_query_sets_system() { fn sys(_set_1: ParamSet<(Query<&mut A>,)>, _set_2: ParamSet<(Query<&mut A>, Query<&B>)>) {} let mut world = World::default(); run_system(&mut world, sys); } #[derive(Default, Resource)] struct BufferRes { _buffer: Vec<u8>, } fn test_for_conflicting_resources<Marker, S: IntoSystem<(), (), Marker>>(sys: S) { let mut world = World::default(); world.insert_resource(BufferRes::default()); world.insert_resource(ResA); world.insert_resource(ResB); run_system(&mut world, sys); } #[test] #[should_panic] fn conflicting_system_resources() { fn sys(_: ResMut<BufferRes>, _: Res<BufferRes>) {} test_for_conflicting_resources(sys); } #[test] #[should_panic] fn conflicting_system_resources_reverse_order() { fn sys(_: Res<BufferRes>, _: ResMut<BufferRes>) {} test_for_conflicting_resources(sys); } #[test] #[should_panic] fn conflicting_system_resources_multiple_mutable() { fn sys(_: ResMut<BufferRes>, _: ResMut<BufferRes>) {} test_for_conflicting_resources(sys); } #[test] fn nonconflicting_system_resources() { fn sys(_: Local<BufferRes>, _: ResMut<BufferRes>, _: Local<A>, _: ResMut<ResA>) {} test_for_conflicting_resources(sys); } #[test] fn local_system() { let mut world = World::default(); world.insert_resource(ProtoFoo { value: 1 }); world.insert_resource(SystemRan::No); struct Foo { value: u32, } #[derive(Resource)] struct ProtoFoo { value: u32, } impl FromWorld for Foo { fn from_world(world: &mut World) -> Self { Foo { value: world.resource::<ProtoFoo>().value + 1, } } } fn sys(local: Local<Foo>, mut system_ran: ResMut<SystemRan>) { assert_eq!(local.value, 2); *system_ran = SystemRan::Yes; } run_system(&mut world, sys); // ensure the system actually ran assert_eq!(*world.resource::<SystemRan>(), SystemRan::Yes); } #[test] #[expect( dead_code, reason = "The `NotSend1` and `NotSend2` structs is used to verify that a system will run, even if the system params include a non-Send resource. As such, the inner value doesn't matter." )] fn non_send_option_system() { let mut world = World::default(); world.insert_resource(SystemRan::No); // Two structs are used, one which is inserted and one which is not, to verify that wrapping // non-Send resources in an `Option` will allow the system to run regardless of their // existence. struct NotSend1(alloc::rc::Rc<i32>); struct NotSend2(alloc::rc::Rc<i32>); world.insert_non_send_resource(NotSend1(alloc::rc::Rc::new(0))); fn sys( op: Option<NonSend<NotSend1>>, mut _op2: Option<NonSendMut<NotSend2>>, mut system_ran: ResMut<SystemRan>, ) { op.expect("NonSend should exist"); *system_ran = SystemRan::Yes; } run_system(&mut world, sys); // ensure the system actually ran assert_eq!(*world.resource::<SystemRan>(), SystemRan::Yes); } #[test] #[expect( dead_code, reason = "The `NotSend1` and `NotSend2` structs are used to verify that a system will run, even if the system params include a non-Send resource. As such, the inner value doesn't matter." )] fn non_send_system() { let mut world = World::default(); world.insert_resource(SystemRan::No); struct NotSend1(alloc::rc::Rc<i32>); struct NotSend2(alloc::rc::Rc<i32>); world.insert_non_send_resource(NotSend1(alloc::rc::Rc::new(1))); world.insert_non_send_resource(NotSend2(alloc::rc::Rc::new(2))); fn sys( _op: NonSend<NotSend1>, mut _op2: NonSendMut<NotSend2>, mut system_ran: ResMut<SystemRan>, ) { *system_ran = SystemRan::Yes; } run_system(&mut world, sys); assert_eq!(*world.resource::<SystemRan>(), SystemRan::Yes); } #[test] fn function_system_as_exclusive() { let mut world = World::default(); world.insert_resource(SystemRan::No); fn sys(_marker: ExclusiveMarker, mut system_ran: ResMut<SystemRan>) { *system_ran = SystemRan::Yes; } let mut sys = IntoSystem::into_system(sys); sys.initialize(&mut world); assert!(sys.is_exclusive()); run_system(&mut world, sys); assert_eq!(*world.resource::<SystemRan>(), SystemRan::Yes); } #[test] fn removal_tracking() { let mut world = World::new(); let entity_to_despawn = world.spawn(W(1)).id(); let entity_to_remove_w_from = world.spawn(W(2)).id(); let spurious_entity = world.spawn_empty().id();
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/system_param.rs
crates/bevy_ecs/src/system/system_param.rs
#![expect( unsafe_op_in_unsafe_fn, reason = "See #11590. To be removed once all applicable unsafe code has an unsafe block with a safety comment." )] pub use crate::change_detection::{NonSend, NonSendMut, Res, ResMut}; use crate::{ archetype::Archetypes, bundle::Bundles, change_detection::{ComponentTicksMut, ComponentTicksRef, Tick}, component::{ComponentId, Components}, entity::{Entities, EntityAllocator}, query::{ Access, FilteredAccess, FilteredAccessSet, QueryData, QueryFilter, QuerySingleError, QueryState, ReadOnlyQueryData, }, resource::Resource, storage::ResourceData, system::{Query, Single, SystemMeta}, world::{ unsafe_world_cell::UnsafeWorldCell, DeferredWorld, FilteredResources, FilteredResourcesMut, FromWorld, World, }, }; use alloc::{borrow::Cow, boxed::Box, vec::Vec}; pub use bevy_ecs_macros::SystemParam; use bevy_platform::cell::SyncCell; use bevy_ptr::UnsafeCellDeref; use bevy_utils::prelude::DebugName; use core::{ any::Any, fmt::{Debug, Display}, marker::PhantomData, ops::{Deref, DerefMut}, }; use thiserror::Error; use super::Populated; use variadics_please::{all_tuples, all_tuples_enumerated}; /// A parameter that can be used in a [`System`](super::System). /// /// # Derive /// /// This trait can be derived with the [`derive@super::SystemParam`] macro. /// This macro only works if each field on the derived struct implements [`SystemParam`]. /// Note: There are additional requirements on the field types. /// See the *Generic `SystemParam`s* section for details and workarounds of the probable /// cause if this derive causes an error to be emitted. /// /// Derived `SystemParam` structs may have two lifetimes: `'w` for data stored in the [`World`], /// and `'s` for data stored in the parameter's state. /// /// The following list shows the most common [`SystemParam`]s and which lifetime they require /// /// ``` /// # use bevy_ecs::prelude::*; /// # #[derive(Component)] /// # struct SomeComponent; /// # #[derive(Resource)] /// # struct SomeResource; /// # #[derive(Message)] /// # struct SomeMessage; /// # #[derive(Resource)] /// # struct SomeOtherResource; /// # use bevy_ecs::system::SystemParam; /// # #[derive(SystemParam)] /// # struct ParamsExample<'w, 's> { /// # query: /// Query<'w, 's, Entity>, /// # query2: /// Query<'w, 's, &'static SomeComponent>, /// # res: /// Res<'w, SomeResource>, /// # res_mut: /// ResMut<'w, SomeOtherResource>, /// # local: /// Local<'s, u8>, /// # commands: /// Commands<'w, 's>, /// # message_reader: /// MessageReader<'w, 's, SomeMessage>, /// # message_writer: /// MessageWriter<'w, SomeMessage> /// # } /// ``` /// ## `PhantomData` /// /// [`PhantomData`] is a special type of `SystemParam` that does nothing. /// This is useful for constraining generic types or lifetimes. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// # #[derive(Resource)] /// # struct SomeResource; /// use std::marker::PhantomData; /// use bevy_ecs::system::SystemParam; /// /// #[derive(SystemParam)] /// struct MyParam<'w, Marker: 'static> { /// foo: Res<'w, SomeResource>, /// marker: PhantomData<Marker>, /// } /// /// fn my_system<T: 'static>(param: MyParam<T>) { /// // Access the resource through `param.foo` /// } /// /// # bevy_ecs::system::assert_is_system(my_system::<()>); /// ``` /// /// # Generic `SystemParam`s /// /// When using the derive macro, you may see an error in the form of: /// /// ```text /// expected ... [ParamType] /// found associated type `<[ParamType] as SystemParam>::Item<'_, '_>` /// ``` /// where `[ParamType]` is the type of one of your fields. /// To solve this error, you can wrap the field of type `[ParamType]` with [`StaticSystemParam`] /// (i.e. `StaticSystemParam<[ParamType]>`). /// /// ## Details /// /// The derive macro requires that the [`SystemParam`] implementation of /// each field `F`'s [`Item`](`SystemParam::Item`)'s is itself `F` /// (ignoring lifetimes for simplicity). /// This assumption is due to type inference reasons, so that the derived [`SystemParam`] can be /// used as an argument to a function system. /// If the compiler cannot validate this property for `[ParamType]`, it will error in the form shown above. /// /// This will most commonly occur when working with `SystemParam`s generically, as the requirement /// has not been proven to the compiler. /// /// ## Custom Validation Messages /// /// When using the derive macro, any [`SystemParamValidationError`]s will be propagated from the sub-parameters. /// If you want to override the error message, add a `#[system_param(validation_message = "New message")]` attribute to the parameter. /// /// ``` /// # use bevy_ecs::prelude::*; /// # #[derive(Resource)] /// # struct SomeResource; /// # use bevy_ecs::system::SystemParam; /// # /// #[derive(SystemParam)] /// struct MyParam<'w> { /// #[system_param(validation_message = "Custom Message")] /// foo: Res<'w, SomeResource>, /// } /// /// let mut world = World::new(); /// let err = world.run_system_cached(|param: MyParam| {}).unwrap_err(); /// let expected = "Parameter `MyParam::foo` failed validation: Custom Message"; /// # #[cfg(feature="Trace")] // Without debug_utils/debug enabled MyParam::foo is stripped and breaks the assert /// assert!(err.to_string().contains(expected)); /// ``` /// /// ## Builders /// /// If you want to use a [`SystemParamBuilder`](crate::system::SystemParamBuilder) with a derived [`SystemParam`] implementation, /// add a `#[system_param(builder)]` attribute to the struct. /// This will generate a builder struct whose name is the param struct suffixed with `Builder`. /// The builder will not be `pub`, so you may want to expose a method that returns an `impl SystemParamBuilder<T>`. /// /// ``` /// mod custom_param { /// # use bevy_ecs::{ /// # prelude::*, /// # system::{LocalBuilder, QueryParamBuilder, SystemParam}, /// # }; /// # /// #[derive(SystemParam)] /// #[system_param(builder)] /// pub struct CustomParam<'w, 's> { /// query: Query<'w, 's, ()>, /// local: Local<'s, usize>, /// } /// /// impl<'w, 's> CustomParam<'w, 's> { /// pub fn builder( /// local: usize, /// query: impl FnOnce(&mut QueryBuilder<()>), /// ) -> impl SystemParamBuilder<Self> { /// CustomParamBuilder { /// local: LocalBuilder(local), /// query: QueryParamBuilder::new(query), /// } /// } /// } /// } /// /// use custom_param::CustomParam; /// /// # use bevy_ecs::prelude::*; /// # #[derive(Component)] /// # struct A; /// # /// # let mut world = World::new(); /// # /// let system = (CustomParam::builder(100, |builder| { /// builder.with::<A>(); /// }),) /// .build_state(&mut world) /// .build_system(|param: CustomParam| {}); /// ``` /// /// # Safety /// /// The implementor must ensure the following is true. /// - [`SystemParam::init_access`] correctly registers all [`World`] accesses used /// by [`SystemParam::get_param`] with the provided [`system_meta`](SystemMeta). /// - None of the world accesses may conflict with any prior accesses registered /// on `system_meta`. pub unsafe trait SystemParam: Sized { /// Used to store data which persists across invocations of a system. type State: Send + Sync + 'static; /// The item type returned when constructing this system param. /// The value of this associated type should be `Self`, instantiated with new lifetimes. /// /// You could think of [`SystemParam::Item<'w, 's>`] as being an *operation* that changes the lifetimes bound to `Self`. type Item<'world, 'state>: SystemParam<State = Self::State>; /// Creates a new instance of this param's [`State`](SystemParam::State). fn init_state(world: &mut World) -> Self::State; /// Registers any [`World`] access used by this [`SystemParam`] fn init_access( state: &Self::State, system_meta: &mut SystemMeta, component_access_set: &mut FilteredAccessSet, world: &mut World, ); /// Applies any deferred mutations stored in this [`SystemParam`]'s state. /// This is used to apply [`Commands`] during [`ApplyDeferred`](crate::prelude::ApplyDeferred). /// /// [`Commands`]: crate::prelude::Commands #[inline] #[expect( unused_variables, reason = "The parameters here are intentionally unused by the default implementation; however, putting underscores here will result in the underscores being copied by rust-analyzer's tab completion." )] fn apply(state: &mut Self::State, system_meta: &SystemMeta, world: &mut World) {} /// Queues any deferred mutations to be applied at the next [`ApplyDeferred`](crate::prelude::ApplyDeferred). #[inline] #[expect( unused_variables, reason = "The parameters here are intentionally unused by the default implementation; however, putting underscores here will result in the underscores being copied by rust-analyzer's tab completion." )] fn queue(state: &mut Self::State, system_meta: &SystemMeta, world: DeferredWorld) {} /// Validates that the param can be acquired by the [`get_param`](SystemParam::get_param). /// /// Built-in executors use this to prevent systems with invalid params from running, /// and any failures here will be bubbled up to the default error handler defined in [`bevy_ecs::error`], /// with a value of type [`SystemParamValidationError`]. /// /// For nested [`SystemParam`]s validation will fail if any /// delegated validation fails. /// /// However calling and respecting [`SystemParam::validate_param`] /// is not a strict requirement, [`SystemParam::get_param`] should /// provide it's own safety mechanism to prevent undefined behavior. /// /// The [`world`](UnsafeWorldCell) can only be used to read param's data /// and world metadata. No data can be written. /// /// When using system parameters that require `change_tick` you can use /// [`UnsafeWorldCell::change_tick()`]. Even if this isn't the exact /// same tick used for [`SystemParam::get_param`], the world access /// ensures that the queried data will be the same in both calls. /// /// This method has to be called directly before [`SystemParam::get_param`] with no other (relevant) /// world mutations inbetween. Otherwise, while it won't lead to any undefined behavior, /// the validity of the param may change. /// /// [`System::validate_param`](super::system::System::validate_param), /// calls this method for each supplied system param. /// /// # Safety /// /// - The passed [`UnsafeWorldCell`] must have read-only access to world data /// registered in [`init_access`](SystemParam::init_access). /// - `world` must be the same [`World`] that was used to initialize [`state`](SystemParam::init_state). #[expect( unused_variables, reason = "The parameters here are intentionally unused by the default implementation; however, putting underscores here will result in the underscores being copied by rust-analyzer's tab completion." )] unsafe fn validate_param( state: &mut Self::State, system_meta: &SystemMeta, world: UnsafeWorldCell, ) -> Result<(), SystemParamValidationError> { Ok(()) } /// Creates a parameter to be passed into a [`SystemParamFunction`](super::SystemParamFunction). /// /// # Safety /// /// - The passed [`UnsafeWorldCell`] must have access to any world data registered /// in [`init_access`](SystemParam::init_access). /// - `world` must be the same [`World`] that was used to initialize [`state`](SystemParam::init_state). unsafe fn get_param<'world, 'state>( state: &'state mut Self::State, system_meta: &SystemMeta, world: UnsafeWorldCell<'world>, change_tick: Tick, ) -> Self::Item<'world, 'state>; } /// A [`SystemParam`] that only reads a given [`World`]. /// /// # Safety /// This must only be implemented for [`SystemParam`] impls that exclusively read the World passed in to [`SystemParam::get_param`] pub unsafe trait ReadOnlySystemParam: SystemParam {} /// Shorthand way of accessing the associated type [`SystemParam::Item`] for a given [`SystemParam`]. pub type SystemParamItem<'w, 's, P> = <P as SystemParam>::Item<'w, 's>; // SAFETY: QueryState is constrained to read-only fetches, so it only reads World. unsafe impl<'w, 's, D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static> ReadOnlySystemParam for Query<'w, 's, D, F> { } // SAFETY: Relevant query ComponentId access is applied to SystemMeta. If // this Query conflicts with any prior access, a panic will occur. unsafe impl<D: QueryData + 'static, F: QueryFilter + 'static> SystemParam for Query<'_, '_, D, F> { type State = QueryState<D, F>; type Item<'w, 's> = Query<'w, 's, D, F>; fn init_state(world: &mut World) -> Self::State { QueryState::new(world) } fn init_access( state: &Self::State, system_meta: &mut SystemMeta, component_access_set: &mut FilteredAccessSet, world: &mut World, ) { assert_component_access_compatibility( &system_meta.name, DebugName::type_name::<D>(), DebugName::type_name::<F>(), component_access_set, &state.component_access, world, ); component_access_set.add(state.component_access.clone()); } #[inline] unsafe fn get_param<'w, 's>( state: &'s mut Self::State, system_meta: &SystemMeta, world: UnsafeWorldCell<'w>, change_tick: Tick, ) -> Self::Item<'w, 's> { // SAFETY: We have registered all of the query's world accesses, // so the caller ensures that `world` has permission to access any // world data that the query needs. // The caller ensures the world matches the one used in init_state. unsafe { state.query_unchecked_with_ticks(world, system_meta.last_run, change_tick) } } } fn assert_component_access_compatibility( system_name: &DebugName, query_type: DebugName, filter_type: DebugName, system_access: &FilteredAccessSet, current: &FilteredAccess, world: &World, ) { let conflicts = system_access.get_conflicts_single(current); if conflicts.is_empty() { return; } let mut accesses = conflicts.format_conflict_list(world); // Access list may be empty (if access to all components requested) if !accesses.is_empty() { accesses.push(' '); } panic!("error[B0001]: Query<{}, {}> in system {system_name} accesses component(s) {accesses}in a way that conflicts with a previous system parameter. Consider using `Without<T>` to create disjoint Queries or merging conflicting Queries into a `ParamSet`. See: https://bevy.org/learn/errors/b0001", query_type.shortname(), filter_type.shortname()); } // SAFETY: Relevant query ComponentId access is applied to SystemMeta. If // this Query conflicts with any prior access, a panic will occur. unsafe impl<'a, 'b, D: QueryData + 'static, F: QueryFilter + 'static> SystemParam for Single<'a, 'b, D, F> { type State = QueryState<D, F>; type Item<'w, 's> = Single<'w, 's, D, F>; fn init_state(world: &mut World) -> Self::State { Query::init_state(world) } fn init_access( state: &Self::State, system_meta: &mut SystemMeta, component_access_set: &mut FilteredAccessSet, world: &mut World, ) { Query::init_access(state, system_meta, component_access_set, world); } #[inline] unsafe fn get_param<'w, 's>( state: &'s mut Self::State, system_meta: &SystemMeta, world: UnsafeWorldCell<'w>, change_tick: Tick, ) -> Self::Item<'w, 's> { // SAFETY: State ensures that the components it accesses are not accessible somewhere elsewhere. // The caller ensures the world matches the one used in init_state. let query = unsafe { state.query_unchecked_with_ticks(world, system_meta.last_run, change_tick) }; let single = query .single_inner() .expect("The query was expected to contain exactly one matching entity."); Single { item: single, _filter: PhantomData, } } #[inline] unsafe fn validate_param( state: &mut Self::State, system_meta: &SystemMeta, world: UnsafeWorldCell, ) -> Result<(), SystemParamValidationError> { // SAFETY: State ensures that the components it accesses are not mutably accessible elsewhere // and the query is read only. // The caller ensures the world matches the one used in init_state. let query = unsafe { state.query_unchecked_with_ticks(world, system_meta.last_run, world.change_tick()) }; match query.single_inner() { Ok(_) => Ok(()), Err(QuerySingleError::NoEntities(_)) => Err( SystemParamValidationError::skipped::<Self>("No matching entities"), ), Err(QuerySingleError::MultipleEntities(_)) => Err( SystemParamValidationError::skipped::<Self>("Multiple matching entities"), ), } } } // SAFETY: QueryState is constrained to read-only fetches, so it only reads World. unsafe impl<'a, 'b, D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static> ReadOnlySystemParam for Single<'a, 'b, D, F> { } // SAFETY: Relevant query ComponentId access is applied to SystemMeta. If // this Query conflicts with any prior access, a panic will occur. unsafe impl<D: QueryData + 'static, F: QueryFilter + 'static> SystemParam for Populated<'_, '_, D, F> { type State = QueryState<D, F>; type Item<'w, 's> = Populated<'w, 's, D, F>; fn init_state(world: &mut World) -> Self::State { Query::init_state(world) } fn init_access( state: &Self::State, system_meta: &mut SystemMeta, component_access_set: &mut FilteredAccessSet, world: &mut World, ) { Query::init_access(state, system_meta, component_access_set, world); } #[inline] unsafe fn get_param<'w, 's>( state: &'s mut Self::State, system_meta: &SystemMeta, world: UnsafeWorldCell<'w>, change_tick: Tick, ) -> Self::Item<'w, 's> { // SAFETY: Delegate to existing `SystemParam` implementations. let query = unsafe { Query::get_param(state, system_meta, world, change_tick) }; Populated(query) } #[inline] unsafe fn validate_param( state: &mut Self::State, system_meta: &SystemMeta, world: UnsafeWorldCell, ) -> Result<(), SystemParamValidationError> { // SAFETY: // - We have read-only access to the components accessed by query. // - The caller ensures the world matches the one used in init_state. let query = unsafe { state.query_unchecked_with_ticks(world, system_meta.last_run, world.change_tick()) }; if query.is_empty() { Err(SystemParamValidationError::skipped::<Self>( "No matching entities", )) } else { Ok(()) } } } // SAFETY: QueryState is constrained to read-only fetches, so it only reads World. unsafe impl<'w, 's, D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static> ReadOnlySystemParam for Populated<'w, 's, D, F> { } /// A collection of potentially conflicting [`SystemParam`]s allowed by disjoint access. /// /// Allows systems to safely access and interact with up to 8 mutually exclusive [`SystemParam`]s, such as /// two queries that reference the same mutable data or an event reader and writer of the same type. /// /// Each individual [`SystemParam`] can be accessed by using the functions `p0()`, `p1()`, ..., `p7()`, /// according to the order they are defined in the `ParamSet`. This ensures that there's either /// only one mutable reference to a parameter at a time or any number of immutable references. /// /// # Examples /// /// The following system mutably accesses the same component two times, /// which is not allowed due to rust's mutability rules. /// /// ```should_panic /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct Health; /// # /// # #[derive(Component)] /// # struct Enemy; /// # /// # #[derive(Component)] /// # struct Ally; /// # /// // This will panic at runtime when the system gets initialized. /// fn bad_system( /// mut enemies: Query<&mut Health, With<Enemy>>, /// mut allies: Query<&mut Health, With<Ally>>, /// ) { /// // ... /// } /// # /// # let mut bad_system_system = IntoSystem::into_system(bad_system); /// # let mut world = World::new(); /// # bad_system_system.initialize(&mut world); /// # bad_system_system.run((), &mut world); /// ``` /// /// Conflicting `SystemParam`s like these can be placed in a `ParamSet`, /// which leverages the borrow checker to ensure that only one of the contained parameters are accessed at a given time. /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct Health; /// # /// # #[derive(Component)] /// # struct Enemy; /// # /// # #[derive(Component)] /// # struct Ally; /// # /// // Given the following system /// fn fancy_system( /// mut set: ParamSet<( /// Query<&mut Health, With<Enemy>>, /// Query<&mut Health, With<Ally>>, /// )> /// ) { /// // This will access the first `SystemParam`. /// for mut health in set.p0().iter_mut() { /// // Do your fancy stuff here... /// } /// /// // The second `SystemParam`. /// // This would fail to compile if the previous parameter was still borrowed. /// for mut health in set.p1().iter_mut() { /// // Do even fancier stuff here... /// } /// } /// # bevy_ecs::system::assert_is_system(fancy_system); /// ``` /// /// Of course, `ParamSet`s can be used with any kind of `SystemParam`, not just [queries](Query). /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Message)] /// # struct MyMessage; /// # impl MyMessage { /// # pub fn new() -> Self { Self } /// # } /// fn message_system( /// mut set: ParamSet<( /// // PROBLEM: `MessageReader` and `MessageWriter` cannot be used together normally, /// // because they both need access to the same message queue. /// // SOLUTION: `ParamSet` allows these conflicting parameters to be used safely /// // by ensuring only one is accessed at a time. /// MessageReader<MyMessage>, /// MessageWriter<MyMessage>, /// // PROBLEM: `&World` needs read access to everything, which conflicts with /// // any mutable access in the same system. /// // SOLUTION: `ParamSet` ensures `&World` is only accessed when we're not /// // using the other mutable parameters. /// &World, /// )>, /// ) { /// for message in set.p0().read() { /// // ... /// # let _message = message; /// } /// set.p1().write(MyMessage::new()); /// /// let entities = set.p2().entities(); /// // ... /// # let _entities = entities; /// } /// # bevy_ecs::system::assert_is_system(message_system); /// ``` pub struct ParamSet<'w, 's, T: SystemParam> { param_states: &'s mut T::State, world: UnsafeWorldCell<'w>, system_meta: SystemMeta, change_tick: Tick, } macro_rules! impl_param_set { ($(($index: tt, $param: ident, $fn_name: ident)),*) => { // SAFETY: All parameters are constrained to ReadOnlySystemParam, so World is only read unsafe impl<'w, 's, $($param,)*> ReadOnlySystemParam for ParamSet<'w, 's, ($($param,)*)> where $($param: ReadOnlySystemParam,)* { } // SAFETY: Relevant parameter ComponentId access is applied to SystemMeta. If any ParamState conflicts // with any prior access, a panic will occur. unsafe impl<'_w, '_s, $($param: SystemParam,)*> SystemParam for ParamSet<'_w, '_s, ($($param,)*)> { type State = ($($param::State,)*); type Item<'w, 's> = ParamSet<'w, 's, ($($param,)*)>; #[expect( clippy::allow_attributes, reason = "This is inside a macro meant for tuples; as such, `non_snake_case` won't always lint." )] #[allow( non_snake_case, reason = "Certain variable names are provided by the caller, not by us." )] fn init_state(world: &mut World) -> Self::State { ($($param::init_state(world),)*) } #[expect( clippy::allow_attributes, reason = "This is inside a macro meant for tuples; as such, `non_snake_case` won't always lint." )] #[allow( non_snake_case, reason = "Certain variable names are provided by the caller, not by us." )] fn init_access(state: &Self::State, system_meta: &mut SystemMeta, component_access_set: &mut FilteredAccessSet, world: &mut World) { let ($($param,)*) = state; $( // Call `init_access` on a clone of the original access set to check for conflicts let component_access_set_clone = &mut component_access_set.clone(); $param::init_access($param, system_meta, component_access_set_clone, world); )* $( // Pretend to add the param to the system alone to gather the new access, // then merge its access into the system. let mut access_set = FilteredAccessSet::new(); $param::init_access($param, system_meta, &mut access_set, world); component_access_set.extend(access_set); )* } fn apply(state: &mut Self::State, system_meta: &SystemMeta, world: &mut World) { <($($param,)*) as SystemParam>::apply(state, system_meta, world); } fn queue(state: &mut Self::State, system_meta: &SystemMeta, mut world: DeferredWorld) { <($($param,)*) as SystemParam>::queue(state, system_meta, world.reborrow()); } #[inline] unsafe fn validate_param<'w, 's>( state: &'s mut Self::State, system_meta: &SystemMeta, world: UnsafeWorldCell<'w>, ) -> Result<(), SystemParamValidationError> { // SAFETY: Upheld by caller unsafe { <($($param,)*) as SystemParam>::validate_param(state, system_meta, world) } } #[inline] unsafe fn get_param<'w, 's>( state: &'s mut Self::State, system_meta: &SystemMeta, world: UnsafeWorldCell<'w>, change_tick: Tick, ) -> Self::Item<'w, 's> { ParamSet { param_states: state, system_meta: system_meta.clone(), world, change_tick, } } } impl<'w, 's, $($param: SystemParam,)*> ParamSet<'w, 's, ($($param,)*)> { $( /// Gets exclusive access to the parameter at index #[doc = stringify!($index)] /// in this [`ParamSet`]. /// No other parameters may be accessed while this one is active. pub fn $fn_name<'a>(&'a mut self) -> SystemParamItem<'a, 'a, $param> { // SAFETY: systems run without conflicts with other systems. // Conflicting params in ParamSet are not accessible at the same time // ParamSets are guaranteed to not conflict with other SystemParams unsafe { $param::get_param(&mut self.param_states.$index, &self.system_meta, self.world, self.change_tick) } } )* } } } all_tuples_enumerated!(impl_param_set, 1, 8, P, p); // SAFETY: Res only reads a single World resource unsafe impl<'a, T: Resource> ReadOnlySystemParam for Res<'a, T> {} // SAFETY: Res ComponentId access is applied to SystemMeta. If this Res // conflicts with any prior access, a panic will occur. unsafe impl<'a, T: Resource> SystemParam for Res<'a, T> { type State = ComponentId; type Item<'w, 's> = Res<'w, T>; fn init_state(world: &mut World) -> Self::State { world.components_registrator().register_resource::<T>() } fn init_access( &component_id: &Self::State, system_meta: &mut SystemMeta, component_access_set: &mut FilteredAccessSet, _world: &mut World, ) { let combined_access = component_access_set.combined_access(); assert!( !combined_access.has_resource_write(component_id), "error[B0002]: Res<{}> in system {} conflicts with a previous ResMut<{0}> access. Consider removing the duplicate access. See: https://bevy.org/learn/errors/b0002", DebugName::type_name::<T>(), system_meta.name, ); component_access_set.add_unfiltered_resource_read(component_id); } #[inline] unsafe fn validate_param( &mut component_id: &mut Self::State, _system_meta: &SystemMeta, world: UnsafeWorldCell, ) -> Result<(), SystemParamValidationError> { // SAFETY: Read-only access to resource metadata. if unsafe { world.storages() } .resources .get(component_id) .is_some_and(ResourceData::is_present) { Ok(()) } else { Err(SystemParamValidationError::invalid::<Self>( "Resource does not exist", )) } } #[inline] unsafe fn get_param<'w, 's>( &mut component_id: &'s mut Self::State, system_meta: &SystemMeta, world: UnsafeWorldCell<'w>, change_tick: Tick, ) -> Self::Item<'w, 's> { let (ptr, ticks) = world .get_resource_with_ticks(component_id) .unwrap_or_else(|| { panic!( "Resource requested by {} does not exist: {}", system_meta.name, DebugName::type_name::<T>() ); }); Res { value: ptr.deref(), ticks: ComponentTicksRef { added: ticks.added.deref(), changed: ticks.changed.deref(), changed_by: ticks.changed_by.map(|changed_by| changed_by.deref()), last_run: system_meta.last_run, this_run: change_tick, }, } } } // SAFETY: Res ComponentId access is applied to SystemMeta. If this Res // conflicts with any prior access, a panic will occur. unsafe impl<'a, T: Resource> SystemParam for ResMut<'a, T> { type State = ComponentId; type Item<'w, 's> = ResMut<'w, T>; fn init_state(world: &mut World) -> Self::State { world.components_registrator().register_resource::<T>() } fn init_access( &component_id: &Self::State, system_meta: &mut SystemMeta, component_access_set: &mut FilteredAccessSet, _world: &mut World, ) { let combined_access = component_access_set.combined_access(); if combined_access.has_resource_write(component_id) { panic!( "error[B0002]: ResMut<{}> in system {} conflicts with a previous ResMut<{0}> access. Consider removing the duplicate access. See: https://bevy.org/learn/errors/b0002", DebugName::type_name::<T>(), system_meta.name); } else if combined_access.has_resource_read(component_id) { panic!( "error[B0002]: ResMut<{}> in system {} conflicts with a previous Res<{0}> access. Consider removing the duplicate access. See: https://bevy.org/learn/errors/b0002", DebugName::type_name::<T>(), system_meta.name); } component_access_set.add_unfiltered_resource_write(component_id); } #[inline] unsafe fn validate_param( &mut component_id: &mut Self::State,
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/query.rs
crates/bevy_ecs/src/system/query.rs
use bevy_utils::prelude::DebugName; use crate::{ batching::BatchingStrategy, change_detection::Tick, entity::{Entity, EntityEquivalent, EntitySet, UniqueEntityArray}, query::{ DebugCheckedUnwrap, NopWorldQuery, QueryCombinationIter, QueryData, QueryEntityError, QueryFilter, QueryIter, QueryManyIter, QueryManyUniqueIter, QueryParIter, QueryParManyIter, QueryParManyUniqueIter, QuerySingleError, QueryState, ROQueryItem, ReadOnlyQueryData, }, world::unsafe_world_cell::UnsafeWorldCell, }; use core::{ marker::PhantomData, mem::MaybeUninit, ops::{Deref, DerefMut}, }; /// A [system parameter] that provides selective access to the [`Component`] data stored in a [`World`]. /// /// Queries enable systems to access [entity identifiers] and [components] without requiring direct access to the [`World`]. /// Its iterators and getter methods return *query items*, which are types containing data related to an entity. /// /// `Query` is a generic data structure that accepts two type parameters: /// /// - **`D` (query data)**: /// The type of data fetched by the query, which will be returned as the query item. /// Only entities that match the requested data will generate an item. /// Must implement the [`QueryData`] trait. /// - **`F` (query filter)**: /// An optional set of conditions that determine whether query items should be kept or discarded. /// This defaults to [`unit`], which means no additional filters will be applied. /// Must implement the [`QueryFilter`] trait. /// /// [system parameter]: crate::system::SystemParam /// [`Component`]: crate::component::Component /// [`World`]: crate::world::World /// [entity identifiers]: Entity /// [components]: crate::component::Component /// /// # Similar parameters /// /// `Query` has few sibling [`SystemParam`]s, which perform additional validation: /// /// - [`Single`] - Exactly one matching query item. /// - [`Option<Single>`] - Zero or one matching query item. /// - [`Populated`] - At least one matching query item. /// /// These parameters will prevent systems from running if their requirements are not met. /// /// [`SystemParam`]: crate::system::system_param::SystemParam /// [`Option<Single>`]: Single /// /// # System parameter declaration /// /// A query should always be declared as a system parameter. /// This section shows the most common idioms involving the declaration of `Query`. /// /// ## Component access /// /// You can fetch an entity's component by specifying a reference to that component in the query's data parameter: /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # /// // A component can be accessed by a shared reference... /// fn immutable_query(query: Query<&ComponentA>) { /// // ... /// } /// /// // ...or by a mutable reference. /// fn mutable_query(query: Query<&mut ComponentA>) { /// // ... /// } /// # /// # bevy_ecs::system::assert_is_system(immutable_query); /// # bevy_ecs::system::assert_is_system(mutable_query); /// ``` /// /// Note that components need to be behind a reference (`&` or `&mut`), or the query will not compile: /// /// ```compile_fail,E0277 /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # /// // This needs to be `&ComponentA` or `&mut ComponentA` in order to compile. /// fn invalid_query(query: Query<ComponentA>) { /// // ... /// } /// ``` /// /// ## Query filtering /// /// Setting the query filter type parameter will ensure that each query item satisfies the given condition: /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # /// # #[derive(Component)] /// # struct ComponentB; /// # /// // `ComponentA` data will be accessed, but only for entities that also contain `ComponentB`. /// fn filtered_query(query: Query<&ComponentA, With<ComponentB>>) { /// // ... /// } /// # /// # bevy_ecs::system::assert_is_system(filtered_query); /// ``` /// /// Note that the filter is `With<ComponentB>`, not `With<&ComponentB>`. Unlike query data, `With` /// does not require components to be behind a reference. /// /// ## `QueryData` or `QueryFilter` tuples /// /// Using [`tuple`]s, each `Query` type parameter can contain multiple elements. /// /// In the following example two components are accessed simultaneously, and the query items are /// filtered on two conditions: /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # /// # #[derive(Component)] /// # struct ComponentB; /// # /// # #[derive(Component)] /// # struct ComponentC; /// # /// # #[derive(Component)] /// # struct ComponentD; /// # /// fn complex_query( /// query: Query<(&mut ComponentA, &ComponentB), (With<ComponentC>, Without<ComponentD>)> /// ) { /// // ... /// } /// # /// # bevy_ecs::system::assert_is_system(complex_query); /// ``` /// /// Note that this currently only works on tuples with 15 or fewer items. You may nest tuples to /// get around this limit: /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # /// # #[derive(Component)] /// # struct ComponentB; /// # /// # #[derive(Component)] /// # struct ComponentC; /// # /// # #[derive(Component)] /// # struct ComponentD; /// # /// fn nested_query( /// query: Query<(&ComponentA, &ComponentB, (&mut ComponentC, &mut ComponentD))> /// ) { /// // ... /// } /// # /// # bevy_ecs::system::assert_is_system(nested_query); /// ``` /// /// ## Entity identifier access /// /// You can access [`Entity`], the entity identifier, by including it in the query data parameter: /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # /// fn entity_id_query(query: Query<(Entity, &ComponentA)>) { /// // ... /// } /// # /// # bevy_ecs::system::assert_is_system(entity_id_query); /// ``` /// /// Be aware that [`Entity`] is not a component, so it does not need to be behind a reference. /// /// ## Optional component access /// /// A component can be made optional by wrapping it into an [`Option`]. In the following example, a /// query item will still be generated even if the queried entity does not contain `ComponentB`. /// When this is the case, `Option<&ComponentB>`'s corresponding value will be `None`. /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # /// # #[derive(Component)] /// # struct ComponentB; /// # /// // Queried items must contain `ComponentA`. If they also contain `ComponentB`, its value will /// // be fetched as well. /// fn optional_component_query(query: Query<(&ComponentA, Option<&ComponentB>)>) { /// // ... /// } /// # /// # bevy_ecs::system::assert_is_system(optional_component_query); /// ``` /// /// Optional components can hurt performance in some cases, so please read the [performance] /// section to learn more about them. Additionally, if you need to declare several optional /// components, you may be interested in using [`AnyOf`]. /// /// [performance]: #performance /// [`AnyOf`]: crate::query::AnyOf /// /// ## Disjoint queries /// /// A system cannot contain two queries that break Rust's mutability rules, or else it will panic /// when initialized. This can often be fixed with the [`Without`] filter, which makes the queries /// disjoint. /// /// In the following example, the two queries can mutably access the same `&mut Health` component /// if an entity has both the `Player` and `Enemy` components. Bevy will catch this and panic, /// however, instead of breaking Rust's mutability rules: /// /// ```should_panic /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct Health; /// # /// # #[derive(Component)] /// # struct Player; /// # /// # #[derive(Component)] /// # struct Enemy; /// # /// fn randomize_health( /// player_query: Query<&mut Health, With<Player>>, /// enemy_query: Query<&mut Health, With<Enemy>>, /// ) { /// // ... /// } /// # /// # bevy_ecs::system::assert_system_does_not_conflict(randomize_health); /// ``` /// /// Adding a [`Without`] filter will disjoint the queries. In the following example, any entity /// that has both the `Player` and `Enemy` components will be excluded from _both_ queries: /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct Health; /// # /// # #[derive(Component)] /// # struct Player; /// # /// # #[derive(Component)] /// # struct Enemy; /// # /// fn randomize_health( /// player_query: Query<&mut Health, (With<Player>, Without<Enemy>)>, /// enemy_query: Query<&mut Health, (With<Enemy>, Without<Player>)>, /// ) { /// // ... /// } /// # /// # bevy_ecs::system::assert_system_does_not_conflict(randomize_health); /// ``` /// /// An alternative solution to this problem would be to wrap the conflicting queries in /// [`ParamSet`]. /// /// [`Without`]: crate::query::Without /// [`ParamSet`]: crate::system::ParamSet /// /// ## Whole Entity Access /// /// [`EntityRef`] can be used in a query to gain read-only access to all components of an entity. /// This is useful when dynamically fetching components instead of baking them into the query type. /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # /// fn all_components_query(query: Query<(EntityRef, &ComponentA)>) { /// // ... /// } /// # /// # bevy_ecs::system::assert_is_system(all_components_query); /// ``` /// /// As [`EntityRef`] can read any component on an entity, a query using it will conflict with *any* /// mutable component access. /// /// ```should_panic /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # /// // `EntityRef` provides read access to *all* components on an entity. When combined with /// // `&mut ComponentA` in the same query, it creates a conflict because `EntityRef` could read /// // `&ComponentA` while `&mut ComponentA` attempts to modify it - violating Rust's borrowing /// // rules. /// fn invalid_query(query: Query<(EntityRef, &mut ComponentA)>) { /// // ... /// } /// # /// # bevy_ecs::system::assert_system_does_not_conflict(invalid_query); /// ``` /// /// It is strongly advised to couple [`EntityRef`] queries with the use of either [`With`] / /// [`Without`] filters or [`ParamSet`]s. Not only does this improve the performance and /// parallelization of the system, but it enables systems to gain mutable access to other /// components: /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # /// # #[derive(Component)] /// # struct ComponentB; /// # /// // The first query only reads entities that have `ComponentA`, while the second query only /// // modifies entities that *don't* have `ComponentA`. Because neither query will access the same /// // entity, this system does not conflict. /// fn disjoint_query( /// query_a: Query<EntityRef, With<ComponentA>>, /// query_b: Query<&mut ComponentB, Without<ComponentA>>, /// ) { /// // ... /// } /// # /// # bevy_ecs::system::assert_system_does_not_conflict(disjoint_query); /// ``` /// /// The fundamental rule: [`EntityRef`]'s ability to read all components means it can never /// coexist with mutable access. [`With`] / [`Without`] filters can guarantee this by keeping the /// queries on completely separate entities. /// /// [`EntityRef`]: crate::world::EntityRef /// [`With`]: crate::query::With /// /// # Accessing query items /// /// The following table summarizes the behavior of safe methods that can be used to get query /// items: /// /// |Query methods|Effect| /// |-|-| /// |[`iter`]\[[`_mut`][`iter_mut`]\]|Returns an iterator over all query items.| /// |[`iter[_mut]().for_each()`][`for_each`],<br />[`par_iter`]\[[`_mut`][`par_iter_mut`]\]|Runs a specified function for each query item.| /// |[`iter_many`]\[[`_unique`][`iter_many_unique`]\]\[[`_mut`][`iter_many_mut`]\]|Iterates over query items that match a list of entities.| /// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]\]|Iterates over all combinations of query items.| /// |[`single`](Self::single)\[[`_mut`][`single_mut`]\]|Returns a single query item if only one exists.| /// |[`get`]\[[`_mut`][`get_mut`]\]|Returns the query item for a specified entity.| /// |[`get_many`]\[[`_unique`][`get_many_unique`]\]\[[`_mut`][`get_many_mut`]\]|Returns all query items that match a list of entities.| /// /// There are two methods for each type of query operation: immutable and mutable (ending with `_mut`). /// When using immutable methods, the query items returned are of type [`ROQueryItem`], a read-only version of the query item. /// In this circumstance, every mutable reference in the query fetch type parameter is substituted by a shared reference. /// /// [`iter`]: Self::iter /// [`iter_mut`]: Self::iter_mut /// [`for_each`]: #iteratorfor_each /// [`par_iter`]: Self::par_iter /// [`par_iter_mut`]: Self::par_iter_mut /// [`iter_many`]: Self::iter_many /// [`iter_many_unique`]: Self::iter_many_unique /// [`iter_many_mut`]: Self::iter_many_mut /// [`iter_combinations`]: Self::iter_combinations /// [`iter_combinations_mut`]: Self::iter_combinations_mut /// [`single_mut`]: Self::single_mut /// [`get`]: Self::get /// [`get_mut`]: Self::get_mut /// [`get_many`]: Self::get_many /// [`get_many_unique`]: Self::get_many_unique /// [`get_many_mut`]: Self::get_many_mut /// /// # Performance /// /// Creating a `Query` is a low-cost constant operation. Iterating it, on the other hand, fetches /// data from the world and generates items, which can have a significant computational cost. /// /// Two systems cannot be executed in parallel if both access the same component type where at /// least one of the accesses is mutable. Because of this, it is recommended for queries to only /// fetch mutable access to components when necessary, since immutable access can be parallelized. /// /// Query filters ([`With`] / [`Without`]) can improve performance because they narrow the kinds of /// entities that can be fetched. Systems that access fewer kinds of entities are more likely to be /// parallelized by the scheduler. /// /// On the other hand, be careful using optional components (`Option<&ComponentA>`) and /// [`EntityRef`] because they broaden the amount of entities kinds that can be accessed. This is /// especially true of a query that _only_ fetches optional components or [`EntityRef`], as the /// query would iterate over all entities in the world. /// /// There are two types of [component storage types]: [`Table`] and [`SparseSet`]. [`Table`] offers /// fast iteration speeds, but slower insertion and removal speeds. [`SparseSet`] is the opposite: /// it offers fast component insertion and removal speeds, but slower iteration speeds. /// /// The following table compares the computational complexity of the various methods and /// operations, where: /// /// - **n** is the number of entities that match the query. /// - **r** is the number of elements in a combination. /// - **k** is the number of involved entities in the operation. /// - **a** is the number of archetypes in the world. /// - **C** is the [binomial coefficient], used to count combinations. <sub>n</sub>C<sub>r</sub> is /// read as "*n* choose *r*" and is equivalent to the number of distinct unordered subsets of *r* /// elements that can be taken from a set of *n* elements. /// /// |Query operation|Computational complexity| /// |-|-| /// |[`iter`]\[[`_mut`][`iter_mut`]\]|O(n)| /// |[`iter[_mut]().for_each()`][`for_each`],<br/>[`par_iter`]\[[`_mut`][`par_iter_mut`]\]|O(n)| /// |[`iter_many`]\[[`_mut`][`iter_many_mut`]\]|O(k)| /// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]\]|O(<sub>n</sub>C<sub>r</sub>)| /// |[`single`](Self::single)\[[`_mut`][`single_mut`]\]|O(a)| /// |[`get`]\[[`_mut`][`get_mut`]\]|O(1)| /// |[`get_many`]|O(k)| /// |[`get_many_mut`]|O(k<sup>2</sup>)| /// |Archetype-based filtering ([`With`], [`Without`], [`Or`])|O(a)| /// |Change detection filtering ([`Added`], [`Changed`], [`Spawned`])|O(a + n)| /// /// [component storage types]: crate::component::StorageType /// [`Table`]: crate::storage::Table /// [`SparseSet`]: crate::storage::SparseSet /// [binomial coefficient]: https://en.wikipedia.org/wiki/Binomial_coefficient /// [`Or`]: crate::query::Or /// [`Added`]: crate::query::Added /// [`Changed`]: crate::query::Changed /// [`Spawned`]: crate::query::Spawned /// /// # `Iterator::for_each` /// /// The `for_each` methods appear to be generally faster than `for`-loops when run on worlds with /// high archetype fragmentation, and may enable additional optimizations like [autovectorization]. It /// is strongly advised to only use [`Iterator::for_each`] if it tangibly improves performance. /// *Always* profile or benchmark before and after the change! /// /// ```rust /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # /// fn system(query: Query<&ComponentA>) { /// // This may result in better performance... /// query.iter().for_each(|component| { /// // ... /// }); /// /// // ...than this. Always benchmark to validate the difference! /// for component in query.iter() { /// // ... /// } /// } /// # /// # bevy_ecs::system::assert_is_system(system); /// ``` /// /// [autovectorization]: https://en.wikipedia.org/wiki/Automatic_vectorization pub struct Query<'world, 'state, D: QueryData, F: QueryFilter = ()> { // SAFETY: Must have access to the components registered in `state`. world: UnsafeWorldCell<'world>, state: &'state QueryState<D, F>, last_run: Tick, this_run: Tick, } impl<D: ReadOnlyQueryData, F: QueryFilter> Clone for Query<'_, '_, D, F> { fn clone(&self) -> Self { *self } } impl<D: ReadOnlyQueryData, F: QueryFilter> Copy for Query<'_, '_, D, F> {} impl<D: QueryData, F: QueryFilter> core::fmt::Debug for Query<'_, '_, D, F> { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { f.debug_struct("Query") .field("matched_entities", &self.iter().count()) .field("state", &self.state) .field("last_run", &self.last_run) .field("this_run", &self.this_run) .field("world", &self.world) .finish() } } impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> { /// Creates a new query. /// /// # Safety /// /// * This will create a query that could violate memory safety rules. Make sure that this is only /// called in ways that ensure the queries have unique mutable access. /// * `world` must be the world used to create `state`. #[inline] pub(crate) unsafe fn new( world: UnsafeWorldCell<'w>, state: &'s QueryState<D, F>, last_run: Tick, this_run: Tick, ) -> Self { Self { world, state, last_run, this_run, } } /// Returns another `Query` from this that fetches the read-only version of the query items. /// /// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`. /// This can be useful when working around the borrow checker, /// or reusing functionality between systems via functions that accept query types. /// /// # See also /// /// [`into_readonly`](Self::into_readonly) for a version that consumes the `Query` to return one with the full `'world` lifetime. pub fn as_readonly(&self) -> Query<'_, 's, D::ReadOnly, F> { // SAFETY: The reborrowed query is converted to read-only, so it cannot perform mutable access, // and the original query is held with a shared borrow, so it cannot perform mutable access either. unsafe { self.reborrow_unsafe() }.into_readonly() } /// Returns another `Query` from this does not return any data, which can be faster. /// /// The resulting query will ignore any non-archetypal filters in `D`, /// so this is only equivalent if `D::IS_ARCHETYPAL` is `true`. fn as_nop(&self) -> Query<'_, 's, NopWorldQuery<D>, F> { let new_state = self.state.as_nop(); // SAFETY: // - The reborrowed query is converted to read-only, so it cannot perform mutable access, // and the original query is held with a shared borrow, so it cannot perform mutable access either. // Note that although `NopWorldQuery` itself performs *no* access and could soundly alias a mutable query, // it has the original `QueryState::component_access` and could be `transmute`d to a read-only query. // - The world matches because it was the same one used to construct self. unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) } } /// Returns another `Query` from this that fetches the read-only version of the query items. /// /// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`. /// This can be useful when working around the borrow checker, /// or reusing functionality between systems via functions that accept query types. /// /// # See also /// /// [`as_readonly`](Self::as_readonly) for a version that borrows the `Query` instead of consuming it. pub fn into_readonly(self) -> Query<'w, 's, D::ReadOnly, F> { let new_state = self.state.as_readonly(); // SAFETY: // - This is memory safe because it turns the query immutable. // - The world matches because it was the same one used to construct self. unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) } } /// Returns a new `Query` reborrowing the access from this one. The current query will be unusable /// while the new one exists. /// /// # Example /// /// For example this allows to call other methods or other systems that require an owned `Query` without /// completely giving up ownership of it. /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct ComponentA; /// /// fn helper_system(query: Query<&ComponentA>) { /* ... */} /// /// fn system(mut query: Query<&ComponentA>) { /// helper_system(query.reborrow()); /// // Can still use query here: /// for component in &query { /// // ... /// } /// } /// ``` pub fn reborrow(&mut self) -> Query<'_, 's, D, F> { // SAFETY: this query is exclusively borrowed while the new one exists, so // no overlapping access can occur. unsafe { self.reborrow_unsafe() } } /// Returns a new `Query` reborrowing the access from this one. /// The current query will still be usable while the new one exists, but must not be used in a way that violates aliasing. /// /// # Safety /// /// This function makes it possible to violate Rust's aliasing guarantees. /// You must make sure this call does not result in a mutable or shared reference to a component with a mutable reference. /// /// # See also /// /// - [`reborrow`](Self::reborrow) for the safe versions. pub unsafe fn reborrow_unsafe(&self) -> Query<'_, 's, D, F> { // SAFETY: // - This is memory safe because the caller ensures that there are no conflicting references. // - The world matches because it was the same one used to construct self. unsafe { self.copy_unsafe() } } /// Returns a new `Query` copying the access from this one. /// The current query will still be usable while the new one exists, but must not be used in a way that violates aliasing. /// /// # Safety /// /// This function makes it possible to violate Rust's aliasing guarantees. /// You must make sure this call does not result in a mutable or shared reference to a component with a mutable reference. /// /// # See also /// /// - [`reborrow_unsafe`](Self::reborrow_unsafe) for a safer version that constrains the returned `'w` lifetime to the length of the borrow. unsafe fn copy_unsafe(&self) -> Query<'w, 's, D, F> { // SAFETY: // - This is memory safe because the caller ensures that there are no conflicting references. // - The world matches because it was the same one used to construct self. unsafe { Query::new(self.world, self.state, self.last_run, self.this_run) } } /// Returns an [`Iterator`] over the read-only query items. /// /// This iterator is always guaranteed to return results from each matching entity once and only once. /// Iteration order is not guaranteed. /// /// # Example /// /// Here, the `report_names_system` iterates over the `Player` component of every entity that contains it: /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct Player { name: String } /// # /// fn report_names_system(query: Query<&Player>) { /// for player in &query { /// println!("Say hello to {}!", player.name); /// } /// } /// # bevy_ecs::system::assert_is_system(report_names_system); /// ``` /// /// # See also /// /// [`iter_mut`](Self::iter_mut) for mutable query items. #[inline] pub fn iter(&self) -> QueryIter<'_, 's, D::ReadOnly, F> { self.as_readonly().into_iter() } /// Returns an [`Iterator`] over the query items. /// /// This iterator is always guaranteed to return results from each matching entity once and only once. /// Iteration order is not guaranteed. /// /// # Example /// /// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it: /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct Velocity { x: f32, y: f32, z: f32 } /// fn gravity_system(mut query: Query<&mut Velocity>) { /// const DELTA: f32 = 1.0 / 60.0; /// for mut velocity in &mut query { /// velocity.y -= 9.8 * DELTA; /// } /// } /// # bevy_ecs::system::assert_is_system(gravity_system); /// ``` /// /// # See also /// /// [`iter`](Self::iter) for read-only query items. #[inline] pub fn iter_mut(&mut self) -> QueryIter<'_, 's, D, F> { self.reborrow().into_iter() } /// Returns a [`QueryCombinationIter`] over all combinations of `K` read-only query items without repetition. /// /// This iterator is always guaranteed to return results from each unique pair of matching entities. /// Iteration order is not guaranteed. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// # #[derive(Component)] /// # struct ComponentA; /// # /// fn some_system(query: Query<&ComponentA>) { /// for [a1, a2] in query.iter_combinations() { /// // ... /// } /// } /// ``` /// /// # See also /// /// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations. /// - [`iter_combinations_inner`](Self::iter_combinations_inner) for mutable query item combinations with the full `'world` lifetime. #[inline] pub fn iter_combinations<const K: usize>( &self, ) -> QueryCombinationIter<'_, 's, D::ReadOnly, F, K> { self.as_readonly().iter_combinations_inner() } /// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition. /// /// This iterator is always guaranteed to return results from each unique pair of matching entities. /// Iteration order is not guaranteed. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// # #[derive(Component)] /// # struct ComponentA; /// fn some_system(mut query: Query<&mut ComponentA>) { /// let mut combinations = query.iter_combinations_mut(); /// while let Some([mut a1, mut a2]) = combinations.fetch_next() { /// // mutably access components data /// } /// } /// ``` /// /// # See also /// /// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations. /// - [`iter_combinations_inner`](Self::iter_combinations_inner) for mutable query item combinations with the full `'world` lifetime. #[inline] pub fn iter_combinations_mut<const K: usize>( &mut self, ) -> QueryCombinationIter<'_, 's, D, F, K> { self.reborrow().iter_combinations_inner() } /// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition. /// This consumes the [`Query`] to return results with the actual "inner" world lifetime. /// /// This iterator is always guaranteed to return results from each unique pair of matching entities. /// Iteration order is not guaranteed. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// # #[derive(Component)] /// # struct ComponentA; /// fn some_system(query: Query<&mut ComponentA>) { /// let mut combinations = query.iter_combinations_inner(); /// while let Some([mut a1, mut a2]) = combinations.fetch_next() { /// // mutably access components data /// } /// } /// ``` /// /// # See also /// /// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations. /// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations. #[inline] pub fn iter_combinations_inner<const K: usize>(self) -> QueryCombinationIter<'w, 's, D, F, K> { // SAFETY: `self.world` has permission to access the required components. unsafe { QueryCombinationIter::new(self.world, self.state, self.last_run, self.this_run) } } /// Returns an [`Iterator`] over the read-only query items generated from an [`Entity`] list. /// /// Items are returned in the order of the list of entities, and may not be unique if the input /// doesn't guarantee uniqueness. Entities that don't match the query are skipped. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// # #[derive(Component)] /// # struct Counter { /// # value: i32 /// # } /// # /// // A component containing an entity list. /// #[derive(Component)] /// struct Friends { /// list: Vec<Entity>, /// } /// /// fn system( /// friends_query: Query<&Friends>, /// counter_query: Query<&Counter>, /// ) { /// for friends in &friends_query { /// for counter in counter_query.iter_many(&friends.list) { /// println!("Friend's counter: {}", counter.value); /// } /// } /// } /// # bevy_ecs::system::assert_is_system(system); /// ``` /// /// # See also /// /// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items. /// - [`iter_many_inner`](Self::iter_many_inner) to get mutable query items with the full `'world` lifetime. #[inline] pub fn iter_many<EntityList: IntoIterator<Item: EntityEquivalent>>( &self, entities: EntityList, ) -> QueryManyIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> { self.as_readonly().iter_many_inner(entities) } /// Returns an iterator over the query items generated from an [`Entity`] list. /// /// Items are returned in the order of the list of entities, and may not be unique if the input /// doesn't guarantee uniqueness. Entities that don't match the query are skipped. /// /// # Examples /// /// ``` /// # use bevy_ecs::prelude::*; /// #[derive(Component)] /// struct Counter { /// value: i32 /// } /// /// #[derive(Component)] /// struct Friends { /// list: Vec<Entity>, /// } /// /// fn system( /// friends_query: Query<&Friends>, /// mut counter_query: Query<&mut Counter>, /// ) { /// for friends in &friends_query { /// let mut iter = counter_query.iter_many_mut(&friends.list); /// while let Some(mut counter) = iter.fetch_next() { /// println!("Friend's counter: {}", counter.value); /// counter.value += 1; /// } /// } /// }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/schedule_system.rs
crates/bevy_ecs/src/system/schedule_system.rs
use bevy_utils::prelude::DebugName; use crate::{ change_detection::{CheckChangeTicks, Tick}, error::Result, query::FilteredAccessSet, system::{input::SystemIn, BoxedSystem, RunSystemError, System, SystemInput}, world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, FromWorld, World}, }; use super::{IntoSystem, SystemParamValidationError, SystemStateFlags}; /// See [`IntoSystem::with_input`] for details. pub struct WithInputWrapper<S, T> where for<'i> S: System<In: SystemInput<Inner<'i> = &'i mut T>>, T: Send + Sync + 'static, { system: S, value: T, } impl<S, T> WithInputWrapper<S, T> where for<'i> S: System<In: SystemInput<Inner<'i> = &'i mut T>>, T: Send + Sync + 'static, { /// Wraps the given system with the given input value. pub fn new<M>(system: impl IntoSystem<S::In, S::Out, M, System = S>, value: T) -> Self { Self { system: IntoSystem::into_system(system), value, } } /// Returns a reference to the input value. pub fn value(&self) -> &T { &self.value } /// Returns a mutable reference to the input value. pub fn value_mut(&mut self) -> &mut T { &mut self.value } } impl<S, T> System for WithInputWrapper<S, T> where for<'i> S: System<In: SystemInput<Inner<'i> = &'i mut T>>, T: Send + Sync + 'static, { type In = (); type Out = S::Out; fn name(&self) -> DebugName { self.system.name() } #[inline] fn flags(&self) -> SystemStateFlags { self.system.flags() } unsafe fn run_unsafe( &mut self, _input: SystemIn<'_, Self>, world: UnsafeWorldCell, ) -> Result<Self::Out, RunSystemError> { // SAFETY: Upheld by caller unsafe { self.system.run_unsafe(&mut self.value, world) } } #[cfg(feature = "hotpatching")] #[inline] fn refresh_hotpatch(&mut self) { self.system.refresh_hotpatch(); } fn apply_deferred(&mut self, world: &mut World) { self.system.apply_deferred(world); } fn queue_deferred(&mut self, world: DeferredWorld) { self.system.queue_deferred(world); } unsafe fn validate_param_unsafe( &mut self, world: UnsafeWorldCell, ) -> Result<(), SystemParamValidationError> { // SAFETY: Upheld by caller unsafe { self.system.validate_param_unsafe(world) } } fn initialize(&mut self, world: &mut World) -> FilteredAccessSet { self.system.initialize(world) } fn check_change_tick(&mut self, check: CheckChangeTicks) { self.system.check_change_tick(check); } fn get_last_run(&self) -> Tick { self.system.get_last_run() } fn set_last_run(&mut self, last_run: Tick) { self.system.set_last_run(last_run); } } /// Constructed in [`IntoSystem::with_input_from`]. pub struct WithInputFromWrapper<S, T> { system: S, value: Option<T>, } impl<S, T> WithInputFromWrapper<S, T> where for<'i> S: System<In: SystemInput<Inner<'i> = &'i mut T>>, T: Send + Sync + 'static, { /// Wraps the given system. pub fn new<M>(system: impl IntoSystem<S::In, S::Out, M, System = S>) -> Self { Self { system: IntoSystem::into_system(system), value: None, } } /// Returns a reference to the input value, if it has been initialized. pub fn value(&self) -> Option<&T> { self.value.as_ref() } /// Returns a mutable reference to the input value, if it has been initialized. pub fn value_mut(&mut self) -> Option<&mut T> { self.value.as_mut() } } impl<S, T> System for WithInputFromWrapper<S, T> where for<'i> S: System<In: SystemInput<Inner<'i> = &'i mut T>>, T: FromWorld + Send + Sync + 'static, { type In = (); type Out = S::Out; fn name(&self) -> DebugName { self.system.name() } #[inline] fn flags(&self) -> SystemStateFlags { self.system.flags() } unsafe fn run_unsafe( &mut self, _input: SystemIn<'_, Self>, world: UnsafeWorldCell, ) -> Result<Self::Out, RunSystemError> { let value = self .value .as_mut() .expect("System input value was not found. Did you forget to initialize the system before running it?"); // SAFETY: Upheld by caller unsafe { self.system.run_unsafe(value, world) } } #[cfg(feature = "hotpatching")] #[inline] fn refresh_hotpatch(&mut self) { self.system.refresh_hotpatch(); } fn apply_deferred(&mut self, world: &mut World) { self.system.apply_deferred(world); } fn queue_deferred(&mut self, world: DeferredWorld) { self.system.queue_deferred(world); } unsafe fn validate_param_unsafe( &mut self, world: UnsafeWorldCell, ) -> Result<(), SystemParamValidationError> { // SAFETY: Upheld by caller unsafe { self.system.validate_param_unsafe(world) } } fn initialize(&mut self, world: &mut World) -> FilteredAccessSet { if self.value.is_none() { self.value = Some(T::from_world(world)); } self.system.initialize(world) } fn check_change_tick(&mut self, check: CheckChangeTicks) { self.system.check_change_tick(check); } fn get_last_run(&self) -> Tick { self.system.get_last_run() } fn set_last_run(&mut self, last_run: Tick) { self.system.set_last_run(last_run); } } /// Type alias for a `BoxedSystem` that a `Schedule` can store. pub type ScheduleSystem = BoxedSystem<(), ()>;
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/input.rs
crates/bevy_ecs/src/system/input.rs
use core::ops::{Deref, DerefMut}; use variadics_please::all_tuples; use crate::{bundle::Bundle, event::Event, prelude::On, system::System}; /// Trait for types that can be used as input to [`System`]s. /// /// Provided implementations are: /// - `()`: No input /// - [`In<T>`]: For values /// - [`InRef<T>`]: For read-only references to values /// - [`InMut<T>`]: For mutable references to values /// - [`On<E, B>`]: For [`ObserverSystem`]s /// - [`StaticSystemInput<I>`]: For arbitrary [`SystemInput`]s in generic contexts /// - Tuples of [`SystemInput`]s up to 8 elements /// /// For advanced usecases, you can implement this trait for your own types. /// /// # Examples /// /// ## Tuples of [`SystemInput`]s /// /// ``` /// use bevy_ecs::prelude::*; /// /// fn add((InMut(a), In(b)): (InMut<usize>, In<usize>)) { /// *a += b; /// } /// # let mut world = World::new(); /// # let mut add = IntoSystem::into_system(add); /// # add.initialize(&mut world); /// # let mut a = 12; /// # let b = 24; /// # add.run((&mut a, b), &mut world); /// # assert_eq!(a, 36); /// ``` /// /// [`ObserverSystem`]: crate::system::ObserverSystem pub trait SystemInput: Sized { /// The wrapper input type that is defined as the first argument to [`FunctionSystem`]s. /// /// [`FunctionSystem`]: crate::system::FunctionSystem type Param<'i>: SystemInput; /// The inner input type that is passed to functions that run systems, /// such as [`System::run`]. /// /// [`System::run`]: crate::system::System::run type Inner<'i>; /// Converts a [`SystemInput::Inner`] into a [`SystemInput::Param`]. fn wrap(this: Self::Inner<'_>) -> Self::Param<'_>; } /// Shorthand way to get the [`System::In`] for a [`System`] as a [`SystemInput::Inner`]. pub type SystemIn<'a, S> = <<S as System>::In as SystemInput>::Inner<'a>; /// A type that may be constructed from the input of a [`System`]. /// This is used to allow systems whose first parameter is a `StaticSystemInput<In>` /// to take an `In` as input, and can be implemented for user types to allow /// similar conversions. pub trait FromInput<In: SystemInput>: SystemInput { /// Converts the system input's inner representation into this type's /// inner representation. fn from_inner<'i>(inner: In::Inner<'i>) -> Self::Inner<'i>; } impl<In: SystemInput> FromInput<In> for In { #[inline] fn from_inner<'i>(inner: In::Inner<'i>) -> Self::Inner<'i> { inner } } impl<'a, In: SystemInput> FromInput<In> for StaticSystemInput<'a, In> { #[inline] fn from_inner<'i>(inner: In::Inner<'i>) -> Self::Inner<'i> { inner } } /// A [`SystemInput`] type which denotes that a [`System`] receives /// an input value of type `T` from its caller. /// /// [`System`]s may take an optional input which they require to be passed to them when they /// are being [`run`](System::run). For [`FunctionSystem`]s the input may be marked /// with this `In` type, but only the first param of a function may be tagged as an input. This also /// means a system can only have one or zero input parameters. /// /// See [`SystemInput`] to learn more about system inputs in general. /// /// # Examples /// /// Here is a simple example of a system that takes a [`usize`] and returns the square of it. /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// fn square(In(input): In<usize>) -> usize { /// input * input /// } /// /// let mut world = World::new(); /// let mut square_system = IntoSystem::into_system(square); /// square_system.initialize(&mut world); /// /// assert_eq!(square_system.run(12, &mut world).unwrap(), 144); /// ``` /// /// [`SystemParam`]: crate::system::SystemParam /// [`FunctionSystem`]: crate::system::FunctionSystem #[derive(Debug)] pub struct In<T>(pub T); impl<T: 'static> SystemInput for In<T> { type Param<'i> = In<T>; type Inner<'i> = T; fn wrap(this: Self::Inner<'_>) -> Self::Param<'_> { In(this) } } impl<T> Deref for In<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> DerefMut for In<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } /// A [`SystemInput`] type which denotes that a [`System`] receives /// a read-only reference to a value of type `T` from its caller. /// /// This is similar to [`In`] but takes a reference to a value instead of the value itself. /// See [`InMut`] for the mutable version. /// /// See [`SystemInput`] to learn more about system inputs in general. /// /// # Examples /// /// Here is a simple example of a system that logs the passed in message. /// /// ``` /// # use bevy_ecs::prelude::*; /// # use std::fmt::Write as _; /// # /// #[derive(Resource, Default)] /// struct Log(String); /// /// fn log(InRef(msg): InRef<str>, mut log: ResMut<Log>) { /// writeln!(log.0, "{}", msg).unwrap(); /// } /// /// let mut world = World::new(); /// world.init_resource::<Log>(); /// let mut log_system = IntoSystem::into_system(log); /// log_system.initialize(&mut world); /// /// log_system.run("Hello, world!", &mut world); /// # assert_eq!(world.get_resource::<Log>().unwrap().0, "Hello, world!\n"); /// ``` /// /// [`SystemParam`]: crate::system::SystemParam #[derive(Debug)] pub struct InRef<'i, T: ?Sized>(pub &'i T); impl<T: ?Sized + 'static> SystemInput for InRef<'_, T> { type Param<'i> = InRef<'i, T>; type Inner<'i> = &'i T; fn wrap(this: Self::Inner<'_>) -> Self::Param<'_> { InRef(this) } } impl<'i, T: ?Sized> Deref for InRef<'i, T> { type Target = T; fn deref(&self) -> &Self::Target { self.0 } } /// A [`SystemInput`] type which denotes that a [`System`] receives /// a mutable reference to a value of type `T` from its caller. /// /// This is similar to [`In`] but takes a mutable reference to a value instead of the value itself. /// See [`InRef`] for the read-only version. /// /// See [`SystemInput`] to learn more about system inputs in general. /// /// # Examples /// /// Here is a simple example of a system that takes a `&mut usize` and squares it. /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// fn square(InMut(input): InMut<usize>) { /// *input *= *input; /// } /// /// let mut world = World::new(); /// let mut square_system = IntoSystem::into_system(square); /// square_system.initialize(&mut world); /// /// let mut value = 12; /// square_system.run(&mut value, &mut world); /// assert_eq!(value, 144); /// ``` /// /// [`SystemParam`]: crate::system::SystemParam #[derive(Debug)] pub struct InMut<'a, T: ?Sized>(pub &'a mut T); impl<T: ?Sized + 'static> SystemInput for InMut<'_, T> { type Param<'i> = InMut<'i, T>; type Inner<'i> = &'i mut T; fn wrap(this: Self::Inner<'_>) -> Self::Param<'_> { InMut(this) } } impl<'i, T: ?Sized> Deref for InMut<'i, T> { type Target = T; fn deref(&self) -> &Self::Target { self.0 } } impl<'i, T: ?Sized> DerefMut for InMut<'i, T> { fn deref_mut(&mut self) -> &mut Self::Target { self.0 } } /// Used for [`ObserverSystem`]s. /// /// [`ObserverSystem`]: crate::system::ObserverSystem impl<E: Event, B: Bundle> SystemInput for On<'_, '_, E, B> { // Note: the fact that we must use a shared lifetime here is // a key piece of the complicated safety story documented above // the `&mut E::Trigger<'_>` cast in `observer_system_runner` and in // the `On` implementation. type Param<'i> = On<'i, 'i, E, B>; type Inner<'i> = On<'i, 'i, E, B>; fn wrap(this: Self::Inner<'_>) -> Self::Param<'_> { this } } /// A helper for using [`SystemInput`]s in generic contexts. /// /// This type is a [`SystemInput`] adapter which always has /// `Self::Param == Self` (ignoring lifetimes for brevity), /// no matter the argument [`SystemInput`] (`I`). /// /// This makes it useful for having arbitrary [`SystemInput`]s in /// function systems. /// /// See [`SystemInput`] to learn more about system inputs in general. pub struct StaticSystemInput<'a, I: SystemInput>(pub I::Inner<'a>); impl<'a, I: SystemInput> SystemInput for StaticSystemInput<'a, I> { type Param<'i> = StaticSystemInput<'i, I>; type Inner<'i> = I::Inner<'i>; fn wrap(this: Self::Inner<'_>) -> Self::Param<'_> { StaticSystemInput(this) } } macro_rules! impl_system_input_tuple { ($(#[$meta:meta])* $($name:ident),*) => { $(#[$meta])* impl<$($name: SystemInput),*> SystemInput for ($($name,)*) { type Param<'i> = ($($name::Param<'i>,)*); type Inner<'i> = ($($name::Inner<'i>,)*); #[expect( clippy::allow_attributes, reason = "This is in a macro; as such, the below lints may not always apply." )] #[allow( non_snake_case, reason = "Certain variable names are provided by the caller, not by us." )] #[allow( clippy::unused_unit, reason = "Zero-length tuples won't have anything to wrap." )] fn wrap(this: Self::Inner<'_>) -> Self::Param<'_> { let ($($name,)*) = this; ($($name::wrap($name),)*) } } }; } all_tuples!( #[doc(fake_variadic)] impl_system_input_tuple, 0, 8, I ); #[cfg(test)] mod tests { use crate::{ system::{assert_is_system, In, InMut, InRef, IntoSystem, StaticSystemInput, System}, world::World, }; #[test] fn two_tuple() { fn by_value((In(a), In(b)): (In<usize>, In<usize>)) -> usize { a + b } fn by_ref((InRef(a), InRef(b)): (InRef<usize>, InRef<usize>)) -> usize { *a + *b } fn by_mut((InMut(a), In(b)): (InMut<usize>, In<usize>)) { *a += b; } let mut world = World::new(); let mut by_value = IntoSystem::into_system(by_value); let mut by_ref = IntoSystem::into_system(by_ref); let mut by_mut = IntoSystem::into_system(by_mut); by_value.initialize(&mut world); by_ref.initialize(&mut world); by_mut.initialize(&mut world); let mut a = 12; let b = 24; assert_eq!(by_value.run((a, b), &mut world).unwrap(), 36); assert_eq!(by_ref.run((&a, &b), &mut world).unwrap(), 36); by_mut.run((&mut a, b), &mut world).unwrap(); assert_eq!(a, 36); } #[test] fn compatible_input() { fn takes_usize(In(a): In<usize>) -> usize { a } fn takes_static_usize(StaticSystemInput(b): StaticSystemInput<In<usize>>) -> usize { b } assert_is_system::<In<usize>, usize, _>(takes_usize); // test if StaticSystemInput is compatible with its inner type assert_is_system::<In<usize>, usize, _>(takes_static_usize); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/exclusive_function_system.rs
crates/bevy_ecs/src/system/exclusive_function_system.rs
use crate::{ change_detection::{CheckChangeTicks, Tick}, error::Result, query::FilteredAccessSet, schedule::{InternedSystemSet, SystemSet}, system::{ check_system_change_tick, ExclusiveSystemParam, ExclusiveSystemParamItem, IntoResult, IntoSystem, System, SystemIn, SystemInput, SystemMeta, }, world::{unsafe_world_cell::UnsafeWorldCell, World}, }; use alloc::{borrow::Cow, vec, vec::Vec}; use bevy_utils::prelude::DebugName; use core::marker::PhantomData; use variadics_please::all_tuples; use super::{RunSystemError, SystemParamValidationError, SystemStateFlags}; /// A function system that runs with exclusive [`World`] access. /// /// You get this by calling [`IntoSystem::into_system`] on a function that only accepts /// [`ExclusiveSystemParam`]s. /// /// [`ExclusiveFunctionSystem`] must be `.initialized` before they can be run. pub struct ExclusiveFunctionSystem<Marker, Out, F> where F: ExclusiveSystemParamFunction<Marker>, { func: F, #[cfg(feature = "hotpatching")] current_ptr: subsecond::HotFnPtr, param_state: Option<<F::Param as ExclusiveSystemParam>::State>, system_meta: SystemMeta, // NOTE: PhantomData<fn()-> T> gives this safe Send/Sync impls marker: PhantomData<fn() -> (Marker, Out)>, } impl<Marker, Out, F> ExclusiveFunctionSystem<Marker, Out, F> where F: ExclusiveSystemParamFunction<Marker>, { /// Return this system with a new name. /// /// Useful to give closure systems more readable and unique names for debugging and tracing. pub fn with_name(mut self, new_name: impl Into<Cow<'static, str>>) -> Self { self.system_meta.set_name(new_name); self } } /// A marker type used to distinguish exclusive function systems from regular function systems. #[doc(hidden)] pub struct IsExclusiveFunctionSystem; impl<Out, Marker, F> IntoSystem<F::In, Out, (IsExclusiveFunctionSystem, Marker, Out)> for F where Out: 'static, Marker: 'static, F::Out: IntoResult<Out>, F: ExclusiveSystemParamFunction<Marker>, { type System = ExclusiveFunctionSystem<Marker, Out, F>; fn into_system(func: Self) -> Self::System { ExclusiveFunctionSystem { func, #[cfg(feature = "hotpatching")] current_ptr: subsecond::HotFn::current( <F as ExclusiveSystemParamFunction<Marker>>::run, ) .ptr_address(), param_state: None, system_meta: SystemMeta::new::<F>(), marker: PhantomData, } } } const PARAM_MESSAGE: &str = "System's param_state was not found. Did you forget to initialize this system before running it?"; impl<Marker, Out, F> System for ExclusiveFunctionSystem<Marker, Out, F> where Marker: 'static, Out: 'static, F::Out: IntoResult<Out>, F: ExclusiveSystemParamFunction<Marker>, { type In = F::In; type Out = Out; #[inline] fn name(&self) -> DebugName { self.system_meta.name.clone() } #[inline] fn flags(&self) -> SystemStateFlags { // non-send , exclusive , no deferred // the executor runs exclusive systems on the main thread, so this // field reflects that constraint // exclusive systems have no deferred system params SystemStateFlags::NON_SEND | SystemStateFlags::EXCLUSIVE } #[inline] unsafe fn run_unsafe( &mut self, input: SystemIn<'_, Self>, world: UnsafeWorldCell, ) -> Result<Self::Out, RunSystemError> { // SAFETY: The safety is upheld by the caller. let world = unsafe { world.world_mut() }; world.last_change_tick_scope(self.system_meta.last_run, |world| { #[cfg(feature = "trace")] let _span_guard = self.system_meta.system_span.enter(); let params = F::Param::get_param( self.param_state.as_mut().expect(PARAM_MESSAGE), &self.system_meta, ); #[cfg(feature = "hotpatching")] let out = { let mut hot_fn = subsecond::HotFn::current(<F as ExclusiveSystemParamFunction<Marker>>::run); // SAFETY: // - pointer used to call is from the current jump table unsafe { hot_fn .try_call_with_ptr(self.current_ptr, (&mut self.func, world, input, params)) .expect("Error calling hotpatched system. Run a full rebuild") } }; #[cfg(not(feature = "hotpatching"))] let out = self.func.run(world, input, params); world.flush(); self.system_meta.last_run = world.increment_change_tick(); IntoResult::into_result(out) }) } #[cfg(feature = "hotpatching")] #[inline] fn refresh_hotpatch(&mut self) { let new = subsecond::HotFn::current(<F as ExclusiveSystemParamFunction<Marker>>::run) .ptr_address(); if new != self.current_ptr { log::debug!("system {} hotpatched", self.name()); } self.current_ptr = new; } #[inline] fn apply_deferred(&mut self, _world: &mut World) { // "pure" exclusive systems do not have any buffers to apply. // Systems made by piping a normal system with an exclusive system // might have buffers to apply, but this is handled by `PipeSystem`. } #[inline] fn queue_deferred(&mut self, _world: crate::world::DeferredWorld) { // "pure" exclusive systems do not have any buffers to apply. // Systems made by piping a normal system with an exclusive system // might have buffers to apply, but this is handled by `PipeSystem`. } #[inline] unsafe fn validate_param_unsafe( &mut self, _world: UnsafeWorldCell, ) -> Result<(), SystemParamValidationError> { // All exclusive system params are always available. Ok(()) } #[inline] fn initialize(&mut self, world: &mut World) -> FilteredAccessSet { self.system_meta.last_run = world.change_tick().relative_to(Tick::MAX); self.param_state = Some(F::Param::init(world, &mut self.system_meta)); FilteredAccessSet::new() } #[inline] fn check_change_tick(&mut self, check: CheckChangeTicks) { check_system_change_tick( &mut self.system_meta.last_run, check, self.system_meta.name.clone(), ); } fn default_system_sets(&self) -> Vec<InternedSystemSet> { let set = crate::schedule::SystemTypeSet::<Self>::new(); vec![set.intern()] } fn get_last_run(&self) -> Tick { self.system_meta.last_run } fn set_last_run(&mut self, last_run: Tick) { self.system_meta.last_run = last_run; } } /// A trait implemented for all exclusive system functions that can be used as [`System`]s. /// /// This trait can be useful for making your own systems which accept other systems, /// sometimes called higher order systems. #[diagnostic::on_unimplemented( message = "`{Self}` is not an exclusive system", label = "invalid system" )] pub trait ExclusiveSystemParamFunction<Marker>: Send + Sync + 'static { /// The input type to this system. See [`System::In`]. type In: SystemInput; /// The return type of this system. See [`System::Out`]. type Out; /// The [`ExclusiveSystemParam`]'s defined by this system's `fn` parameters. type Param: ExclusiveSystemParam; /// Executes this system once. See [`System::run`]. fn run( &mut self, world: &mut World, input: <Self::In as SystemInput>::Inner<'_>, param_value: ExclusiveSystemParamItem<Self::Param>, ) -> Self::Out; } /// A marker type used to distinguish exclusive function systems with and without input. #[doc(hidden)] pub struct HasExclusiveSystemInput; macro_rules! impl_exclusive_system_function { ($($param: ident),*) => { #[expect( clippy::allow_attributes, reason = "This is within a macro, and as such, the below lints may not always apply." )] #[allow( non_snake_case, reason = "Certain variable names are provided by the caller, not by us." )] impl<Out, Func, $($param: ExclusiveSystemParam),*> ExclusiveSystemParamFunction<fn($($param,)*) -> Out> for Func where Func: Send + Sync + 'static, for <'a> &'a mut Func: FnMut(&mut World, $($param),*) -> Out + FnMut(&mut World, $(ExclusiveSystemParamItem<$param>),*) -> Out, Out: 'static, { type In = (); type Out = Out; type Param = ($($param,)*); #[inline] fn run(&mut self, world: &mut World, _in: (), param_value: ExclusiveSystemParamItem< ($($param,)*)>) -> Out { // Yes, this is strange, but `rustc` fails to compile this impl // without using this function. It fails to recognize that `func` // is a function, potentially because of the multiple impls of `FnMut` fn call_inner<Out, $($param,)*>( mut f: impl FnMut(&mut World, $($param,)*) -> Out, world: &mut World, $($param: $param,)* ) -> Out { f(world, $($param,)*) } let ($($param,)*) = param_value; call_inner(self, world, $($param),*) } } #[expect( clippy::allow_attributes, reason = "This is within a macro, and as such, the below lints may not always apply." )] #[allow( non_snake_case, reason = "Certain variable names are provided by the caller, not by us." )] impl<In, Out, Func, $($param: ExclusiveSystemParam),*> ExclusiveSystemParamFunction<(HasExclusiveSystemInput, fn(In, $($param,)*) -> Out)> for Func where Func: Send + Sync + 'static, for <'a> &'a mut Func: FnMut(In, &mut World, $($param),*) -> Out + FnMut(In::Param<'_>, &mut World, $(ExclusiveSystemParamItem<$param>),*) -> Out, In: SystemInput + 'static, Out: 'static, { type In = In; type Out = Out; type Param = ($($param,)*); #[inline] fn run(&mut self, world: &mut World, input: In::Inner<'_>, param_value: ExclusiveSystemParamItem< ($($param,)*)>) -> Out { // Yes, this is strange, but `rustc` fails to compile this impl // without using this function. It fails to recognize that `func` // is a function, potentially because of the multiple impls of `FnMut` fn call_inner<In: SystemInput, Out, $($param,)*>( _: PhantomData<In>, mut f: impl FnMut(In::Param<'_>, &mut World, $($param,)*) -> Out, input: In::Inner<'_>, world: &mut World, $($param: $param,)* ) -> Out { f(In::wrap(input), world, $($param,)*) } let ($($param,)*) = param_value; call_inner(PhantomData::<In>, self, input, world, $($param),*) } } }; } // Note that we rely on the highest impl to be <= the highest order of the tuple impls // of `SystemParam` created. all_tuples!(impl_exclusive_system_function, 0, 16, F); #[cfg(test)] mod tests { use crate::system::input::SystemInput; use super::*; #[test] fn into_system_type_id_consistency() { fn test<T, In: SystemInput, Out, Marker>(function: T) where T: IntoSystem<In, Out, Marker> + Copy, { fn reference_system(_world: &mut World) {} use core::any::TypeId; let system = IntoSystem::into_system(function); assert_eq!( system.type_id(), function.system_type_id(), "System::type_id should be consistent with IntoSystem::system_type_id" ); assert_eq!( system.type_id(), TypeId::of::<T::System>(), "System::type_id should be consistent with TypeId::of::<T::System>()" ); assert_ne!( system.type_id(), IntoSystem::into_system(reference_system).type_id(), "Different systems should have different TypeIds" ); } fn exclusive_function_system(_world: &mut World) {} test(exclusive_function_system); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/commands/entity_command.rs
crates/bevy_ecs/src/system/commands/entity_command.rs
//! Contains the definition of the [`EntityCommand`] trait, //! as well as the blanket implementation of the trait for closures. //! //! It also contains functions that return closures for use with //! [`EntityCommands`](crate::system::EntityCommands). use alloc::{string::ToString, vec::Vec}; #[cfg(not(feature = "trace"))] use log::info; #[cfg(feature = "trace")] use tracing::info; use crate::{ bundle::{Bundle, InsertMode}, change_detection::MaybeLocation, component::{Component, ComponentId}, entity::{Entity, EntityClonerBuilder, OptIn, OptOut}, event::EntityEvent, name::Name, relationship::RelationshipHookMode, system::IntoObserverSystem, world::{error::EntityMutableFetchError, EntityWorldMut, FromWorld}, }; use bevy_ptr::{move_as_ptr, OwningPtr}; /// A command which gets executed for a given [`Entity`]. /// /// Should be used with [`EntityCommands::queue`](crate::system::EntityCommands::queue). /// /// The `Out` generic parameter is the returned "output" of the command. /// /// # Examples /// /// ``` /// # use std::collections::HashSet; /// # use bevy_ecs::prelude::*; /// use bevy_ecs::system::EntityCommand; /// # /// # #[derive(Component, PartialEq)] /// # struct Name(String); /// # impl Name { /// # fn new(s: String) -> Self { Name(s) } /// # fn as_str(&self) -> &str { &self.0 } /// # } /// /// #[derive(Resource, Default)] /// struct Counter(i64); /// /// /// A `Command` which names an entity based on a global counter. /// fn count_name(mut entity: EntityWorldMut) { /// // Get the current value of the counter, and increment it for next time. /// let i = { /// let mut counter = entity.resource_mut::<Counter>(); /// let i = counter.0; /// counter.0 += 1; /// i /// }; /// // Name the entity after the value of the counter. /// entity.insert(Name::new(format!("Entity #{i}"))); /// } /// /// // App creation boilerplate omitted... /// # let mut world = World::new(); /// # world.init_resource::<Counter>(); /// # /// # let mut setup_schedule = Schedule::default(); /// # setup_schedule.add_systems(setup); /// # let mut assert_schedule = Schedule::default(); /// # assert_schedule.add_systems(assert_names); /// # /// # setup_schedule.run(&mut world); /// # assert_schedule.run(&mut world); /// /// fn setup(mut commands: Commands) { /// commands.spawn_empty().queue(count_name); /// commands.spawn_empty().queue(count_name); /// } /// /// fn assert_names(named: Query<&Name>) { /// // We use a HashSet because we do not care about the order. /// let names: HashSet<_> = named.iter().map(Name::as_str).collect(); /// assert_eq!(names, HashSet::from_iter(["Entity #0", "Entity #1"])); /// } /// ``` pub trait EntityCommand<Out = ()>: Send + 'static { /// Executes this command for the given [`Entity`]. fn apply(self, entity: EntityWorldMut) -> Out; } /// An error that occurs when running an [`EntityCommand`] on a specific entity. #[derive(thiserror::Error, Debug)] pub enum EntityCommandError<E> { /// The entity this [`EntityCommand`] tried to run on could not be fetched. #[error(transparent)] EntityFetchError(#[from] EntityMutableFetchError), /// An error that occurred while running the [`EntityCommand`]. #[error("{0}")] CommandFailed(E), } impl<Out, F> EntityCommand<Out> for F where F: FnOnce(EntityWorldMut) -> Out + Send + 'static, { fn apply(self, entity: EntityWorldMut) -> Out { self(entity) } } /// An [`EntityCommand`] that adds the components in a [`Bundle`] to an entity. #[track_caller] pub fn insert(bundle: impl Bundle, mode: InsertMode) -> impl EntityCommand { let caller = MaybeLocation::caller(); move |mut entity: EntityWorldMut| { move_as_ptr!(bundle); entity.insert_with_caller(bundle, mode, caller, RelationshipHookMode::Run); } } /// An [`EntityCommand`] that adds a dynamic component to an entity. /// /// # Safety /// /// - [`ComponentId`] must be from the same world as the target entity. /// - `T` must have the same layout as the one passed during `component_id` creation. #[track_caller] pub unsafe fn insert_by_id<T: Send + 'static>( component_id: ComponentId, value: T, mode: InsertMode, ) -> impl EntityCommand { let caller = MaybeLocation::caller(); move |mut entity: EntityWorldMut| { // SAFETY: // - `component_id` safety is ensured by the caller // - `ptr` is valid within the `make` block OwningPtr::make(value, |ptr| unsafe { entity.insert_by_id_with_caller( component_id, ptr, mode, caller, RelationshipHookMode::Run, ); }); } } /// An [`EntityCommand`] that adds a component to an entity using /// the component's [`FromWorld`] implementation. /// /// `T::from_world` will only be invoked if the component will actually be inserted. /// In other words, `T::from_world` will *not* be invoked if `mode` is [`InsertMode::Keep`] /// and the entity already has the component. #[track_caller] pub fn insert_from_world<T: Component + FromWorld>(mode: InsertMode) -> impl EntityCommand { let caller = MaybeLocation::caller(); move |mut entity: EntityWorldMut| { if !(mode == InsertMode::Keep && entity.contains::<T>()) { let value = entity.world_scope(|world| T::from_world(world)); move_as_ptr!(value); entity.insert_with_caller(value, mode, caller, RelationshipHookMode::Run); } } } /// An [`EntityCommand`] that adds a component to an entity using /// some function that returns the component. /// /// The function will only be invoked if the component will actually be inserted. /// In other words, the function will *not* be invoked if `mode` is [`InsertMode::Keep`] /// and the entity already has the component. #[track_caller] pub fn insert_with<T: Component, F>(component_fn: F, mode: InsertMode) -> impl EntityCommand where F: FnOnce() -> T + Send + 'static, { let caller = MaybeLocation::caller(); move |mut entity: EntityWorldMut| { if !(mode == InsertMode::Keep && entity.contains::<T>()) { let bundle = component_fn(); move_as_ptr!(bundle); entity.insert_with_caller(bundle, mode, caller, RelationshipHookMode::Run); } } } /// An [`EntityCommand`] that removes the components in a [`Bundle`] from an entity. #[track_caller] pub fn remove<T: Bundle>() -> impl EntityCommand { let caller = MaybeLocation::caller(); move |mut entity: EntityWorldMut| { entity.remove_with_caller::<T>(caller); } } /// An [`EntityCommand`] that removes the components in a [`Bundle`] from an entity, /// as well as the required components for each component removed. #[track_caller] pub fn remove_with_requires<T: Bundle>() -> impl EntityCommand { let caller = MaybeLocation::caller(); move |mut entity: EntityWorldMut| { entity.remove_with_requires_with_caller::<T>(caller); } } /// An [`EntityCommand`] that removes a dynamic component from an entity. #[track_caller] pub fn remove_by_id(component_id: ComponentId) -> impl EntityCommand { let caller = MaybeLocation::caller(); move |mut entity: EntityWorldMut| { entity.remove_by_id_with_caller(component_id, caller); } } /// An [`EntityCommand`] that removes all components from an entity. #[track_caller] pub fn clear() -> impl EntityCommand { let caller = MaybeLocation::caller(); move |mut entity: EntityWorldMut| { entity.clear_with_caller(caller); } } /// An [`EntityCommand`] that removes all components from an entity, /// except for those in the given [`Bundle`]. #[track_caller] pub fn retain<T: Bundle>() -> impl EntityCommand { let caller = MaybeLocation::caller(); move |mut entity: EntityWorldMut| { entity.retain_with_caller::<T>(caller); } } /// An [`EntityCommand`] that despawns an entity. /// /// # Note /// /// This will also despawn the entities in any [`RelationshipTarget`](crate::relationship::RelationshipTarget) /// that is configured to despawn descendants. /// /// For example, this will recursively despawn [`Children`](crate::hierarchy::Children). #[track_caller] pub fn despawn() -> impl EntityCommand { let caller = MaybeLocation::caller(); move |entity: EntityWorldMut| { entity.despawn_with_caller(caller); } } /// An [`EntityCommand`] that creates an [`Observer`](crate::observer::Observer) /// watching for an [`EntityEvent`] of type `E` whose [`EntityEvent::event_target`] /// targets this entity. #[track_caller] pub fn observe<E: EntityEvent, B: Bundle, M>( observer: impl IntoObserverSystem<E, B, M>, ) -> impl EntityCommand { let caller = MaybeLocation::caller(); move |mut entity: EntityWorldMut| { entity.observe_with_caller(observer, caller); } } /// An [`EntityCommand`] that clones parts of an entity onto another entity, /// configured through [`EntityClonerBuilder`]. /// /// This builder tries to clone every component from the source entity except /// for components that were explicitly denied, for example by using the /// [`deny`](EntityClonerBuilder<OptOut>::deny) method. /// /// Required components are not considered by denied components and must be /// explicitly denied as well if desired. pub fn clone_with_opt_out( target: Entity, config: impl FnOnce(&mut EntityClonerBuilder<OptOut>) + Send + Sync + 'static, ) -> impl EntityCommand { move |mut entity: EntityWorldMut| { entity.clone_with_opt_out(target, config); } } /// An [`EntityCommand`] that clones parts of an entity onto another entity, /// configured through [`EntityClonerBuilder`]. /// /// This builder tries to clone every component that was explicitly allowed /// from the source entity, for example by using the /// [`allow`](EntityClonerBuilder<OptIn>::allow) method. /// /// Required components are also cloned when the target entity does not contain them. pub fn clone_with_opt_in( target: Entity, config: impl FnOnce(&mut EntityClonerBuilder<OptIn>) + Send + Sync + 'static, ) -> impl EntityCommand { move |mut entity: EntityWorldMut| { entity.clone_with_opt_in(target, config); } } /// An [`EntityCommand`] that clones the specified components of an entity /// and inserts them into another entity. pub fn clone_components<B: Bundle>(target: Entity) -> impl EntityCommand { move |mut entity: EntityWorldMut| { entity.clone_components::<B>(target); } } /// An [`EntityCommand`] moves the specified components of this entity into another entity. /// /// Components with [`Ignore`] clone behavior will not be moved, while components that /// have a [`Custom`] clone behavior will be cloned using it and then removed from the source entity. /// All other components will be moved without any other special handling. /// /// Note that this will trigger `on_remove` hooks/observers on this entity and `on_insert`/`on_add` hooks/observers on the target entity. /// /// # Panics /// /// The command will panic when applied if the target entity does not exist. /// /// [`Ignore`]: crate::component::ComponentCloneBehavior::Ignore /// [`Custom`]: crate::component::ComponentCloneBehavior::Custom pub fn move_components<B: Bundle>(target: Entity) -> impl EntityCommand { move |mut entity: EntityWorldMut| { entity.move_components::<B>(target); } } /// An [`EntityCommand`] that logs the components of an entity. pub fn log_components() -> impl EntityCommand { move |entity: EntityWorldMut| { let name = entity.get::<Name>().map(ToString::to_string); let id = entity.id(); let mut components: Vec<_> = entity .world() .inspect_entity(id) .expect("Entity existence is verified before an EntityCommand is executed") .map(|info| info.name().to_string()) .collect(); components.sort(); #[cfg(not(feature = "debug"))] { let component_count = components.len(); #[cfg(feature = "trace")] { if let Some(name) = name { info!(id=?id, name=?name, ?component_count, "log_components. Enable the `debug` feature to log component names."); } else { info!(id=?id, ?component_count, "log_components. Enable the `debug` feature to log component names."); } } #[cfg(not(feature = "trace"))] { let name = name .map(|name| alloc::format!(" ({name})")) .unwrap_or_default(); info!("Entity {id}{name}: {component_count} components. Enable the `debug` feature to log component names."); } } #[cfg(feature = "debug")] { #[cfg(feature = "trace")] { if let Some(name) = name { info!(id=?id, name=?name, ?components, "log_components"); } else { info!(id=?id, ?components, "log_components"); } } #[cfg(not(feature = "trace"))] { let name = name .map(|name| alloc::format!(" ({name})")) .unwrap_or_default(); info!("Entity {id}{name}: {components:?}"); } } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/commands/command.rs
crates/bevy_ecs/src/system/commands/command.rs
//! Contains the definition of the [`Command`] trait, //! as well as the blanket implementation of the trait for closures. //! //! It also contains functions that return closures for use with //! [`Commands`](crate::system::Commands). use crate::{ bundle::{Bundle, InsertMode, NoBundleEffect}, change_detection::MaybeLocation, entity::Entity, error::Result, event::Event, message::{Message, Messages}, resource::Resource, schedule::ScheduleLabel, system::{IntoSystem, SystemId, SystemInput}, world::{FromWorld, SpawnBatchIter, World}, }; /// A [`World`] mutation. /// /// Should be used with [`Commands::queue`](crate::system::Commands::queue). /// /// The `Out` generic parameter is the returned "output" of the command. /// /// # Usage /// /// ``` /// # use bevy_ecs::prelude::*; /// // Our world resource /// #[derive(Resource, Default)] /// struct Counter(u64); /// /// // Our custom command /// struct AddToCounter(u64); /// /// impl Command for AddToCounter { /// fn apply(self, world: &mut World) { /// let mut counter = world.get_resource_or_insert_with(Counter::default); /// counter.0 += self.0; /// } /// } /// /// fn some_system(mut commands: Commands) { /// commands.queue(AddToCounter(42)); /// } /// ``` pub trait Command<Out = ()>: Send + 'static { /// Applies this command, causing it to mutate the provided `world`. /// /// This method is used to define what a command "does" when it is ultimately applied. /// Because this method takes `self`, you can store data or settings on the type that implements this trait. /// This data is set by the system or other source of the command, and then ultimately read in this method. fn apply(self, world: &mut World) -> Out; } impl<F, Out> Command<Out> for F where F: FnOnce(&mut World) -> Out + Send + 'static, { fn apply(self, world: &mut World) -> Out { self(world) } } /// A [`Command`] that consumes an iterator of [`Bundles`](Bundle) to spawn a series of entities. /// /// This is more efficient than spawning the entities individually. #[track_caller] pub fn spawn_batch<I>(bundles_iter: I) -> impl Command where I: IntoIterator + Send + Sync + 'static, I::Item: Bundle<Effect: NoBundleEffect>, { let caller = MaybeLocation::caller(); move |world: &mut World| { SpawnBatchIter::new(world, bundles_iter.into_iter(), caller); } } /// A [`Command`] that consumes an iterator to add a series of [`Bundles`](Bundle) to a set of entities. /// /// If any entities do not exist in the world, this command will return a /// [`TryInsertBatchError`](crate::world::error::TryInsertBatchError). /// /// This is more efficient than inserting the bundles individually. #[track_caller] pub fn insert_batch<I, B>(batch: I, insert_mode: InsertMode) -> impl Command<Result> where I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static, B: Bundle<Effect: NoBundleEffect>, { let caller = MaybeLocation::caller(); move |world: &mut World| -> Result { world.try_insert_batch_with_caller(batch, insert_mode, caller)?; Ok(()) } } /// A [`Command`] that inserts a [`Resource`] into the world using a value /// created with the [`FromWorld`] trait. #[track_caller] pub fn init_resource<R: Resource + FromWorld>() -> impl Command { move |world: &mut World| { world.init_resource::<R>(); } } /// A [`Command`] that inserts a [`Resource`] into the world. #[track_caller] pub fn insert_resource<R: Resource>(resource: R) -> impl Command { let caller = MaybeLocation::caller(); move |world: &mut World| { world.insert_resource_with_caller(resource, caller); } } /// A [`Command`] that removes a [`Resource`] from the world. pub fn remove_resource<R: Resource>() -> impl Command { move |world: &mut World| { world.remove_resource::<R>(); } } /// A [`Command`] that runs the system corresponding to the given [`SystemId`]. pub fn run_system<O: 'static>(id: SystemId<(), O>) -> impl Command<Result> { move |world: &mut World| -> Result { world.run_system(id)?; Ok(()) } } /// A [`Command`] that runs the system corresponding to the given [`SystemId`] /// and provides the given input value. pub fn run_system_with<I>(id: SystemId<I>, input: I::Inner<'static>) -> impl Command<Result> where I: SystemInput<Inner<'static>: Send> + 'static, { move |world: &mut World| -> Result { world.run_system_with(id, input)?; Ok(()) } } /// A [`Command`] that runs the given system, /// caching its [`SystemId`] in a [`CachedSystemId`](crate::system::CachedSystemId) resource. pub fn run_system_cached<M, S>(system: S) -> impl Command<Result> where M: 'static, S: IntoSystem<(), (), M> + Send + 'static, { move |world: &mut World| -> Result { world.run_system_cached(system)?; Ok(()) } } /// A [`Command`] that runs the given system with the given input value, /// caching its [`SystemId`] in a [`CachedSystemId`](crate::system::CachedSystemId) resource. pub fn run_system_cached_with<I, M, S>(system: S, input: I::Inner<'static>) -> impl Command<Result> where I: SystemInput<Inner<'static>: Send> + Send + 'static, M: 'static, S: IntoSystem<I, (), M> + Send + 'static, { move |world: &mut World| -> Result { world.run_system_cached_with(system, input)?; Ok(()) } } /// A [`Command`] that removes a system previously registered with /// [`Commands::register_system`](crate::system::Commands::register_system) or /// [`World::register_system`]. pub fn unregister_system<I, O>(system_id: SystemId<I, O>) -> impl Command<Result> where I: SystemInput + Send + 'static, O: Send + 'static, { move |world: &mut World| -> Result { world.unregister_system(system_id)?; Ok(()) } } /// A [`Command`] that removes a system previously registered with one of the following: /// - [`Commands::run_system_cached`](crate::system::Commands::run_system_cached) /// - [`World::run_system_cached`] /// - [`World::register_system_cached`] pub fn unregister_system_cached<I, O, M, S>(system: S) -> impl Command<Result> where I: SystemInput + Send + 'static, O: 'static, M: 'static, S: IntoSystem<I, O, M> + Send + 'static, { move |world: &mut World| -> Result { world.unregister_system_cached(system)?; Ok(()) } } /// A [`Command`] that runs the schedule corresponding to the given [`ScheduleLabel`]. pub fn run_schedule(label: impl ScheduleLabel) -> impl Command<Result> { move |world: &mut World| -> Result { world.try_run_schedule(label)?; Ok(()) } } /// Triggers the given [`Event`], which will run any [`Observer`]s watching for it. /// /// [`Observer`]: crate::observer::Observer #[track_caller] pub fn trigger<'a, E: Event<Trigger<'a>: Default>>(mut event: E) -> impl Command { let caller = MaybeLocation::caller(); move |world: &mut World| { world.trigger_ref_with_caller( &mut event, &mut <E::Trigger<'_> as Default>::default(), caller, ); } } /// Triggers the given [`Event`] using the given [`Trigger`], which will run any [`Observer`]s watching for it. /// /// [`Trigger`]: crate::event::Trigger /// [`Observer`]: crate::observer::Observer #[track_caller] pub fn trigger_with<E: Event<Trigger<'static>: Send + Sync>>( mut event: E, mut trigger: E::Trigger<'static>, ) -> impl Command { let caller = MaybeLocation::caller(); move |world: &mut World| { world.trigger_ref_with_caller(&mut event, &mut trigger, caller); } } /// A [`Command`] that writes an arbitrary [`Message`]. #[track_caller] pub fn write_message<M: Message>(message: M) -> impl Command { let caller = MaybeLocation::caller(); move |world: &mut World| { let mut messages = world.resource_mut::<Messages<M>>(); messages.write_with_caller(message, caller); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/commands/mod.rs
crates/bevy_ecs/src/system/commands/mod.rs
pub mod command; pub mod entity_command; #[cfg(feature = "std")] mod parallel_scope; use bevy_ptr::move_as_ptr; pub use command::Command; pub use entity_command::EntityCommand; #[cfg(feature = "std")] pub use parallel_scope::*; use alloc::boxed::Box; use core::marker::PhantomData; use crate::{ self as bevy_ecs, bundle::{Bundle, InsertMode, NoBundleEffect}, change_detection::{MaybeLocation, Mut}, component::{Component, ComponentId, Mutable}, entity::{ Entities, Entity, EntityAllocator, EntityClonerBuilder, EntityNotSpawnedError, InvalidEntityError, OptIn, OptOut, }, error::{warn, BevyError, CommandWithEntity, ErrorContext, HandleError}, event::{EntityEvent, Event}, message::Message, observer::Observer, resource::Resource, schedule::ScheduleLabel, system::{ Deferred, IntoObserverSystem, IntoSystem, RegisteredSystem, SystemId, SystemInput, SystemParamValidationError, }, world::{ command_queue::RawCommandQueue, unsafe_world_cell::UnsafeWorldCell, CommandQueue, EntityWorldMut, FromWorld, World, }, }; /// A [`Command`] queue to perform structural changes to the [`World`]. /// /// Since each command requires exclusive access to the `World`, /// all queued commands are automatically applied in sequence /// when the `ApplyDeferred` system runs (see [`ApplyDeferred`] documentation for more details). /// /// Each command can be used to modify the [`World`] in arbitrary ways: /// * spawning or despawning entities /// * inserting components on new or existing entities /// * inserting resources /// * etc. /// /// For a version of [`Commands`] that works in parallel contexts (such as /// within [`Query::par_iter`](crate::system::Query::par_iter)) see /// [`ParallelCommands`] /// /// # Usage /// /// Add `mut commands: Commands` as a function argument to your system to get a /// copy of this struct that will be applied the next time a copy of [`ApplyDeferred`] runs. /// Commands are almost always used as a [`SystemParam`](crate::system::SystemParam). /// /// ``` /// # use bevy_ecs::prelude::*; /// fn my_system(mut commands: Commands) { /// // ... /// } /// # bevy_ecs::system::assert_is_system(my_system); /// ``` /// /// # Implementing /// /// Each built-in command is implemented as a separate method, e.g. [`Commands::spawn`]. /// In addition to the pre-defined command methods, you can add commands with any arbitrary /// behavior using [`Commands::queue`], which accepts any type implementing [`Command`]. /// /// Since closures and other functions implement this trait automatically, this allows one-shot, /// anonymous custom commands. /// /// ``` /// # use bevy_ecs::prelude::*; /// # fn foo(mut commands: Commands) { /// // NOTE: type inference fails here, so annotations are required on the closure. /// commands.queue(|w: &mut World| { /// // Mutate the world however you want... /// }); /// # } /// ``` /// /// # Error handling /// /// A [`Command`] can return a [`Result`](crate::error::Result), /// which will be passed to an [error handler](crate::error) if the `Result` is an error. /// /// The default error handler panics. It can be configured via /// the [`DefaultErrorHandler`](crate::error::DefaultErrorHandler) resource. /// /// Alternatively, you can customize the error handler for a specific command /// by calling [`Commands::queue_handled`]. /// /// The [`error`](crate::error) module provides some simple error handlers for convenience. /// /// [`ApplyDeferred`]: crate::schedule::ApplyDeferred pub struct Commands<'w, 's> { queue: InternalQueue<'s>, entities: &'w Entities, allocator: &'w EntityAllocator, } // SAFETY: All commands [`Command`] implement [`Send`] unsafe impl Send for Commands<'_, '_> {} // SAFETY: `Commands` never gives access to the inner commands. unsafe impl Sync for Commands<'_, '_> {} const _: () = { type __StructFieldsAlias<'w, 's> = ( Deferred<'s, CommandQueue>, &'w EntityAllocator, &'w Entities, ); #[doc(hidden)] pub struct FetchState { state: <__StructFieldsAlias<'static, 'static> as bevy_ecs::system::SystemParam>::State, } // SAFETY: Only reads Entities unsafe impl bevy_ecs::system::SystemParam for Commands<'_, '_> { type State = FetchState; type Item<'w, 's> = Commands<'w, 's>; fn init_state(world: &mut World) -> Self::State { FetchState { state: <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::init_state( world, ), } } fn init_access( state: &Self::State, system_meta: &mut bevy_ecs::system::SystemMeta, component_access_set: &mut bevy_ecs::query::FilteredAccessSet, world: &mut World, ) { <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::init_access( &state.state, system_meta, component_access_set, world, ); } fn apply( state: &mut Self::State, system_meta: &bevy_ecs::system::SystemMeta, world: &mut World, ) { <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::apply( &mut state.state, system_meta, world, ); } fn queue( state: &mut Self::State, system_meta: &bevy_ecs::system::SystemMeta, world: bevy_ecs::world::DeferredWorld, ) { <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::queue( &mut state.state, system_meta, world, ); } #[inline] unsafe fn validate_param( state: &mut Self::State, system_meta: &bevy_ecs::system::SystemMeta, world: UnsafeWorldCell, ) -> Result<(), SystemParamValidationError> { // SAFETY: Upheld by caller unsafe { <__StructFieldsAlias as bevy_ecs::system::SystemParam>::validate_param( &mut state.state, system_meta, world, ) } } #[inline] unsafe fn get_param<'w, 's>( state: &'s mut Self::State, system_meta: &bevy_ecs::system::SystemMeta, world: UnsafeWorldCell<'w>, change_tick: bevy_ecs::change_detection::Tick, ) -> Self::Item<'w, 's> { // SAFETY: Upheld by caller let params = unsafe { <__StructFieldsAlias as bevy_ecs::system::SystemParam>::get_param( &mut state.state, system_meta, world, change_tick, ) }; Commands { queue: InternalQueue::CommandQueue(params.0), allocator: params.1, entities: params.2, } } } // SAFETY: Only reads Entities unsafe impl<'w, 's> bevy_ecs::system::ReadOnlySystemParam for Commands<'w, 's> where Deferred<'s, CommandQueue>: bevy_ecs::system::ReadOnlySystemParam, &'w Entities: bevy_ecs::system::ReadOnlySystemParam, { } }; enum InternalQueue<'s> { CommandQueue(Deferred<'s, CommandQueue>), RawCommandQueue(RawCommandQueue), } impl<'w, 's> Commands<'w, 's> { /// Returns a new `Commands` instance from a [`CommandQueue`] and a [`World`]. pub fn new(queue: &'s mut CommandQueue, world: &'w World) -> Self { Self::new_from_entities(queue, &world.allocator, &world.entities) } /// Returns a new `Commands` instance from a [`CommandQueue`] and an [`Entities`] reference. pub fn new_from_entities( queue: &'s mut CommandQueue, allocator: &'w EntityAllocator, entities: &'w Entities, ) -> Self { Self { queue: InternalQueue::CommandQueue(Deferred(queue)), allocator, entities, } } /// Returns a new `Commands` instance from a [`RawCommandQueue`] and an [`Entities`] reference. /// /// This is used when constructing [`Commands`] from a [`DeferredWorld`](crate::world::DeferredWorld). /// /// # Safety /// /// * Caller ensures that `queue` must outlive `'w` pub(crate) unsafe fn new_raw_from_entities( queue: RawCommandQueue, allocator: &'w EntityAllocator, entities: &'w Entities, ) -> Self { Self { queue: InternalQueue::RawCommandQueue(queue), allocator, entities, } } /// Returns a [`Commands`] with a smaller lifetime. /// /// This is useful if you have `&mut Commands` but need `Commands`. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// fn my_system(mut commands: Commands) { /// // We do our initialization in a separate function, /// // which expects an owned `Commands`. /// do_initialization(commands.reborrow()); /// /// // Since we only reborrowed the commands instead of moving them, we can still use them. /// commands.spawn_empty(); /// } /// # /// # fn do_initialization(_: Commands) {} /// ``` pub fn reborrow(&mut self) -> Commands<'w, '_> { Commands { queue: match &mut self.queue { InternalQueue::CommandQueue(queue) => InternalQueue::CommandQueue(queue.reborrow()), InternalQueue::RawCommandQueue(queue) => { InternalQueue::RawCommandQueue(queue.clone()) } }, allocator: self.allocator, entities: self.entities, } } /// Take all commands from `other` and append them to `self`, leaving `other` empty. pub fn append(&mut self, other: &mut CommandQueue) { match &mut self.queue { InternalQueue::CommandQueue(queue) => queue.bytes.append(&mut other.bytes), InternalQueue::RawCommandQueue(queue) => { // SAFETY: Pointers in `RawCommandQueue` are never null unsafe { queue.bytes.as_mut() }.append(&mut other.bytes); } } } /// Spawns a new empty [`Entity`] and returns its corresponding [`EntityCommands`]. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// #[derive(Component)] /// struct Label(&'static str); /// #[derive(Component)] /// struct Strength(u32); /// #[derive(Component)] /// struct Agility(u32); /// /// fn example_system(mut commands: Commands) { /// // Create a new empty entity. /// commands.spawn_empty(); /// /// // Create another empty entity. /// commands.spawn_empty() /// // Add a new component bundle to the entity. /// .insert((Strength(1), Agility(2))) /// // Add a single component to the entity. /// .insert(Label("hello world")); /// } /// # bevy_ecs::system::assert_is_system(example_system); /// ``` /// /// # See also /// /// - [`spawn`](Self::spawn) to spawn an entity with components. /// - [`spawn_batch`](Self::spawn_batch) to spawn many entities /// with the same combination of components. #[track_caller] pub fn spawn_empty(&mut self) -> EntityCommands<'_> { let entity = self.allocator.alloc(); let caller = MaybeLocation::caller(); self.queue(move |world: &mut World| { world.spawn_empty_at_with_caller(entity, caller).map(|_| ()) }); self.entity(entity) } /// Spawns a new [`Entity`] with the given components /// and returns the entity's corresponding [`EntityCommands`]. /// /// To spawn many entities with the same combination of components, /// [`spawn_batch`](Self::spawn_batch) can be used for better performance. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// #[derive(Component)] /// struct ComponentA(u32); /// #[derive(Component)] /// struct ComponentB(u32); /// /// #[derive(Bundle)] /// struct ExampleBundle { /// a: ComponentA, /// b: ComponentB, /// } /// /// fn example_system(mut commands: Commands) { /// // Create a new entity with a single component. /// commands.spawn(ComponentA(1)); /// /// // Create a new entity with two components using a "tuple bundle". /// commands.spawn((ComponentA(2), ComponentB(1))); /// /// // Create a new entity with a component bundle. /// commands.spawn(ExampleBundle { /// a: ComponentA(3), /// b: ComponentB(2), /// }); /// } /// # bevy_ecs::system::assert_is_system(example_system); /// ``` /// /// # See also /// /// - [`spawn_empty`](Self::spawn_empty) to spawn an entity without any components. /// - [`spawn_batch`](Self::spawn_batch) to spawn many entities /// with the same combination of components. #[track_caller] pub fn spawn<T: Bundle>(&mut self, bundle: T) -> EntityCommands<'_> { let entity = self.allocator.alloc(); let caller = MaybeLocation::caller(); self.queue(move |world: &mut World| { move_as_ptr!(bundle); world .spawn_at_with_caller(entity, bundle, caller) .map(|_| ()) }); self.entity(entity) } /// Returns the [`EntityCommands`] for the given [`Entity`]. /// /// This method does not guarantee that commands queued by the returned `EntityCommands` /// will be successful, since the entity could be despawned before they are executed. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// #[derive(Resource)] /// struct PlayerEntity { /// entity: Entity /// } /// /// #[derive(Component)] /// struct Label(&'static str); /// /// fn example_system(mut commands: Commands, player: Res<PlayerEntity>) { /// // Get the entity and add a component. /// commands.entity(player.entity).insert(Label("hello world")); /// } /// # bevy_ecs::system::assert_is_system(example_system); /// ``` /// /// # See also /// /// - [`get_entity`](Self::get_entity) for the fallible version. #[inline] #[track_caller] pub fn entity(&mut self, entity: Entity) -> EntityCommands<'_> { EntityCommands { entity, commands: self.reborrow(), } } /// Returns the [`EntityCommands`] for the requested [`Entity`] if it is valid. /// This method does not guarantee that commands queued by the returned `EntityCommands` /// will be successful, since the entity could be despawned before they are executed. /// This also does not error when the entity has not been spawned. /// For that behavior, see [`get_spawned_entity`](Self::get_spawned_entity), /// which should be preferred for accessing entities you expect to already be spawned, like those found from a query. /// For details on entity spawning vs validity, see [`entity`](crate::entity) module docs. /// /// # Errors /// /// Returns [`InvalidEntityError`] if the requested entity does not exist. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// #[derive(Resource)] /// struct PlayerEntity { /// entity: Entity /// } /// /// #[derive(Component)] /// struct Label(&'static str); /// /// fn example_system(mut commands: Commands, player: Res<PlayerEntity>) -> Result { /// // Get the entity if it still exists and store the `EntityCommands`. /// // If it doesn't exist, the `?` operator will propagate the returned error /// // to the system, and the system will pass it to an error handler. /// let mut entity_commands = commands.get_entity(player.entity)?; /// /// // Add a component to the entity. /// entity_commands.insert(Label("hello world")); /// /// // Return from the system successfully. /// Ok(()) /// } /// # bevy_ecs::system::assert_is_system::<(), (), _>(example_system); /// ``` /// /// # See also /// /// - [`entity`](Self::entity) for the infallible version. #[inline] #[track_caller] pub fn get_entity(&mut self, entity: Entity) -> Result<EntityCommands<'_>, InvalidEntityError> { let _location = self.entities.get(entity)?; Ok(EntityCommands { entity, commands: self.reborrow(), }) } /// Returns the [`EntityCommands`] for the requested [`Entity`] if it spawned in the world *now*. /// Note that for entities that have not been spawned *yet*, like ones from [`spawn`](Self::spawn), this will error. /// If that is not desired, try [`get_entity`](Self::get_entity). /// This should be used over [`get_entity`](Self::get_entity) when you expect the entity to already be spawned in the world. /// If the entity is valid but not yet spawned, this will error that information, where [`get_entity`](Self::get_entity) would succeed, leading to potentially surprising results. /// For details on entity spawning vs validity, see [`entity`](crate::entity) module docs. /// /// This method does not guarantee that commands queued by the returned `EntityCommands` /// will be successful, since the entity could be despawned before they are executed. /// /// # Errors /// /// Returns [`EntityNotSpawnedError`] if the requested entity does not exist. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// #[derive(Resource)] /// struct PlayerEntity { /// entity: Entity /// } /// /// #[derive(Component)] /// struct Label(&'static str); /// /// fn example_system(mut commands: Commands, player: Res<PlayerEntity>) -> Result { /// // Get the entity if it still exists and store the `EntityCommands`. /// // If it doesn't exist, the `?` operator will propagate the returned error /// // to the system, and the system will pass it to an error handler. /// let mut entity_commands = commands.get_spawned_entity(player.entity)?; /// /// // Add a component to the entity. /// entity_commands.insert(Label("hello world")); /// /// // Return from the system successfully. /// Ok(()) /// } /// # bevy_ecs::system::assert_is_system::<(), (), _>(example_system); /// ``` /// /// # See also /// /// - [`entity`](Self::entity) for the infallible version. #[inline] #[track_caller] pub fn get_spawned_entity( &mut self, entity: Entity, ) -> Result<EntityCommands<'_>, EntityNotSpawnedError> { let _location = self.entities.get_spawned(entity)?; Ok(EntityCommands { entity, commands: self.reborrow(), }) } /// Spawns multiple entities with the same combination of components, /// based on a batch of [`Bundles`](Bundle). /// /// A batch can be any type that implements [`IntoIterator`] and contains bundles, /// such as a [`Vec<Bundle>`](alloc::vec::Vec) or an array `[Bundle; N]`. /// /// This method is equivalent to iterating the batch /// and calling [`spawn`](Self::spawn) for each bundle, /// but is faster by pre-allocating memory and having exclusive [`World`] access. /// /// # Example /// /// ``` /// use bevy_ecs::prelude::*; /// /// #[derive(Component)] /// struct Score(u32); /// /// fn example_system(mut commands: Commands) { /// commands.spawn_batch([ /// (Name::new("Alice"), Score(0)), /// (Name::new("Bob"), Score(0)), /// ]); /// } /// # bevy_ecs::system::assert_is_system(example_system); /// ``` /// /// # See also /// /// - [`spawn`](Self::spawn) to spawn an entity with components. /// - [`spawn_empty`](Self::spawn_empty) to spawn an entity without components. #[track_caller] pub fn spawn_batch<I>(&mut self, batch: I) where I: IntoIterator + Send + Sync + 'static, I::Item: Bundle<Effect: NoBundleEffect>, { self.queue(command::spawn_batch(batch)); } /// Pushes a generic [`Command`] to the command queue. /// /// If the [`Command`] returns a [`Result`], /// it will be handled using the [default error handler](crate::error::DefaultErrorHandler). /// /// To use a custom error handler, see [`Commands::queue_handled`]. /// /// The command can be: /// - A custom struct that implements [`Command`]. /// - A closure or function that matches one of the following signatures: /// - [`(&mut World)`](World) /// - A built-in command from the [`command`] module. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// #[derive(Resource, Default)] /// struct Counter(u64); /// /// struct AddToCounter(String); /// /// impl Command<Result> for AddToCounter { /// fn apply(self, world: &mut World) -> Result { /// let mut counter = world.get_resource_or_insert_with(Counter::default); /// let amount: u64 = self.0.parse()?; /// counter.0 += amount; /// Ok(()) /// } /// } /// /// fn add_three_to_counter_system(mut commands: Commands) { /// commands.queue(AddToCounter("3".to_string())); /// } /// /// fn add_twenty_five_to_counter_system(mut commands: Commands) { /// commands.queue(|world: &mut World| { /// let mut counter = world.get_resource_or_insert_with(Counter::default); /// counter.0 += 25; /// }); /// } /// # bevy_ecs::system::assert_is_system(add_three_to_counter_system); /// # bevy_ecs::system::assert_is_system(add_twenty_five_to_counter_system); /// ``` pub fn queue<C: Command<T> + HandleError<T>, T>(&mut self, command: C) { self.queue_internal(command.handle_error()); } /// Pushes a generic [`Command`] to the command queue. /// /// If the [`Command`] returns a [`Result`], /// the given `error_handler` will be used to handle error cases. /// /// To implicitly use the default error handler, see [`Commands::queue`]. /// /// The command can be: /// - A custom struct that implements [`Command`]. /// - A closure or function that matches one of the following signatures: /// - [`(&mut World)`](World) /// - [`(&mut World)`](World) `->` [`Result`] /// - A built-in command from the [`command`] module. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// use bevy_ecs::error::warn; /// /// #[derive(Resource, Default)] /// struct Counter(u64); /// /// struct AddToCounter(String); /// /// impl Command<Result> for AddToCounter { /// fn apply(self, world: &mut World) -> Result { /// let mut counter = world.get_resource_or_insert_with(Counter::default); /// let amount: u64 = self.0.parse()?; /// counter.0 += amount; /// Ok(()) /// } /// } /// /// fn add_three_to_counter_system(mut commands: Commands) { /// commands.queue_handled(AddToCounter("3".to_string()), warn); /// } /// /// fn add_twenty_five_to_counter_system(mut commands: Commands) { /// commands.queue(|world: &mut World| { /// let mut counter = world.get_resource_or_insert_with(Counter::default); /// counter.0 += 25; /// }); /// } /// # bevy_ecs::system::assert_is_system(add_three_to_counter_system); /// # bevy_ecs::system::assert_is_system(add_twenty_five_to_counter_system); /// ``` pub fn queue_handled<C: Command<T> + HandleError<T>, T>( &mut self, command: C, error_handler: fn(BevyError, ErrorContext), ) { self.queue_internal(command.handle_error_with(error_handler)); } /// Pushes a generic [`Command`] to the queue like [`Commands::queue_handled`], but instead silently ignores any errors. pub fn queue_silenced<C: Command<T> + HandleError<T>, T>(&mut self, command: C) { self.queue_internal(command.ignore_error()); } fn queue_internal(&mut self, command: impl Command) { match &mut self.queue { InternalQueue::CommandQueue(queue) => { queue.push(command); } InternalQueue::RawCommandQueue(queue) => { // SAFETY: `RawCommandQueue` is only every constructed in `Commands::new_raw_from_entities` // where the caller of that has ensured that `queue` outlives `self` unsafe { queue.push(command); } } } } /// Adds a series of [`Bundles`](Bundle) to each [`Entity`] they are paired with, /// based on a batch of `(Entity, Bundle)` pairs. /// /// A batch can be any type that implements [`IntoIterator`] /// and contains `(Entity, Bundle)` tuples, /// such as a [`Vec<(Entity, Bundle)>`](alloc::vec::Vec) /// or an array `[(Entity, Bundle); N]`. /// /// This will overwrite any pre-existing components shared by the [`Bundle`] type. /// Use [`Commands::insert_batch_if_new`] to keep the pre-existing components instead. /// /// This method is equivalent to iterating the batch /// and calling [`insert`](EntityCommands::insert) for each pair, /// but is faster by caching data that is shared between entities. /// /// # Fallible /// /// This command will fail if any of the given entities do not exist. /// /// It will internally return a [`TryInsertBatchError`](crate::world::error::TryInsertBatchError), /// which will be handled by the [default error handler](crate::error::DefaultErrorHandler). #[track_caller] pub fn insert_batch<I, B>(&mut self, batch: I) where I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static, B: Bundle<Effect: NoBundleEffect>, { self.queue(command::insert_batch(batch, InsertMode::Replace)); } /// Adds a series of [`Bundles`](Bundle) to each [`Entity`] they are paired with, /// based on a batch of `(Entity, Bundle)` pairs. /// /// A batch can be any type that implements [`IntoIterator`] /// and contains `(Entity, Bundle)` tuples, /// such as a [`Vec<(Entity, Bundle)>`](alloc::vec::Vec) /// or an array `[(Entity, Bundle); N]`. /// /// This will keep any pre-existing components shared by the [`Bundle`] type /// and discard the new values. /// Use [`Commands::insert_batch`] to overwrite the pre-existing components instead. /// /// This method is equivalent to iterating the batch /// and calling [`insert_if_new`](EntityCommands::insert_if_new) for each pair, /// but is faster by caching data that is shared between entities. /// /// # Fallible /// /// This command will fail if any of the given entities do not exist. /// /// It will internally return a [`TryInsertBatchError`](crate::world::error::TryInsertBatchError), /// which will be handled by the [default error handler](crate::error::DefaultErrorHandler). #[track_caller] pub fn insert_batch_if_new<I, B>(&mut self, batch: I) where I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static, B: Bundle<Effect: NoBundleEffect>, { self.queue(command::insert_batch(batch, InsertMode::Keep)); } /// Adds a series of [`Bundles`](Bundle) to each [`Entity`] they are paired with, /// based on a batch of `(Entity, Bundle)` pairs. /// /// A batch can be any type that implements [`IntoIterator`] /// and contains `(Entity, Bundle)` tuples, /// such as a [`Vec<(Entity, Bundle)>`](alloc::vec::Vec) /// or an array `[(Entity, Bundle); N]`. /// /// This will overwrite any pre-existing components shared by the [`Bundle`] type. /// Use [`Commands::try_insert_batch_if_new`] to keep the pre-existing components instead. /// /// This method is equivalent to iterating the batch /// and calling [`insert`](EntityCommands::insert) for each pair, /// but is faster by caching data that is shared between entities. /// /// # Fallible /// /// This command will fail if any of the given entities do not exist. /// /// It will internally return a [`TryInsertBatchError`](crate::world::error::TryInsertBatchError), /// which will be handled by [logging the error at the `warn` level](warn). #[track_caller] pub fn try_insert_batch<I, B>(&mut self, batch: I) where I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static, B: Bundle<Effect: NoBundleEffect>, { self.queue(command::insert_batch(batch, InsertMode::Replace).handle_error_with(warn)); } /// Adds a series of [`Bundles`](Bundle) to each [`Entity`] they are paired with, /// based on a batch of `(Entity, Bundle)` pairs. /// /// A batch can be any type that implements [`IntoIterator`] /// and contains `(Entity, Bundle)` tuples, /// such as a [`Vec<(Entity, Bundle)>`](alloc::vec::Vec) /// or an array `[(Entity, Bundle); N]`. /// /// This will keep any pre-existing components shared by the [`Bundle`] type /// and discard the new values. /// Use [`Commands::try_insert_batch`] to overwrite the pre-existing components instead. /// /// This method is equivalent to iterating the batch /// and calling [`insert_if_new`](EntityCommands::insert_if_new) for each pair, /// but is faster by caching data that is shared between entities. /// /// # Fallible /// /// This command will fail if any of the given entities do not exist. /// /// It will internally return a [`TryInsertBatchError`](crate::world::error::TryInsertBatchError), /// which will be handled by [logging the error at the `warn` level](warn). #[track_caller] pub fn try_insert_batch_if_new<I, B>(&mut self, batch: I) where I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static, B: Bundle<Effect: NoBundleEffect>, { self.queue(command::insert_batch(batch, InsertMode::Keep).handle_error_with(warn)); } /// Inserts a [`Resource`] into the [`World`] with an inferred value. /// /// The inferred value is determined by the [`FromWorld`] trait of the resource. /// Note that any resource with the [`Default`] trait automatically implements [`FromWorld`], /// and those default values will be used. /// /// If the resource already exists when the command is applied, nothing happens. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// #[derive(Resource, Default)] /// struct Scoreboard { /// current_score: u32, /// high_score: u32, /// } /// /// fn initialize_scoreboard(mut commands: Commands) { /// commands.init_resource::<Scoreboard>(); /// } /// # bevy_ecs::system::assert_is_system(initialize_scoreboard); /// ``` #[track_caller] pub fn init_resource<R: Resource + FromWorld>(&mut self) { self.queue(command::init_resource::<R>()); } /// Inserts a [`Resource`] into the [`World`] with a specific value. /// /// This will overwrite any previous value of the same resource type. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// #[derive(Resource)] /// struct Scoreboard { /// current_score: u32, /// high_score: u32, /// } /// /// fn system(mut commands: Commands) { /// commands.insert_resource(Scoreboard { /// current_score: 0, /// high_score: 0, /// }); /// } /// # bevy_ecs::system::assert_is_system(system); /// ``` #[track_caller] pub fn insert_resource<R: Resource>(&mut self, resource: R) { self.queue(command::insert_resource(resource)); } /// Removes a [`Resource`] from the [`World`]. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// #[derive(Resource)]
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/system/commands/parallel_scope.rs
crates/bevy_ecs/src/system/commands/parallel_scope.rs
use bevy_utils::Parallel; use crate::{ entity::{Entities, EntityAllocator}, prelude::World, system::{Deferred, SystemBuffer, SystemMeta, SystemParam}, }; use super::{CommandQueue, Commands}; #[derive(Default)] struct ParallelCommandQueue { thread_queues: Parallel<CommandQueue>, } /// An alternative to [`Commands`] that can be used in parallel contexts, such as those /// in [`Query::par_iter`](crate::system::Query::par_iter). /// /// For cases where multiple non-computation-heavy (lightweight) bundles of the same /// [`Bundle`](crate::prelude::Bundle) type need to be spawned, consider using /// [`Commands::spawn_batch`] for better performance. /// /// # Note /// /// Because command application order will depend on how many threads are ran, /// non-commutative commands may result in non-deterministic results. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_tasks::ComputeTaskPool; /// # /// # #[derive(Component)] /// # struct Velocity; /// # impl Velocity { fn magnitude(&self) -> f32 { 42.0 } } /// fn parallel_command_system( /// mut query: Query<(Entity, &Velocity)>, /// par_commands: ParallelCommands /// ) { /// query.par_iter().for_each(|(entity, velocity)| { /// if velocity.magnitude() > 10.0 { /// par_commands.command_scope(|mut commands| { /// commands.entity(entity).despawn(); /// }); /// } /// }); /// } /// # bevy_ecs::system::assert_is_system(parallel_command_system); /// ``` #[derive(SystemParam)] pub struct ParallelCommands<'w, 's> { state: Deferred<'s, ParallelCommandQueue>, allocator: &'w EntityAllocator, entities: &'w Entities, } impl SystemBuffer for ParallelCommandQueue { #[inline] fn apply(&mut self, _system_meta: &SystemMeta, world: &mut World) { #[cfg(feature = "trace")] let _system_span = _system_meta.commands_span.enter(); for cq in self.thread_queues.iter_mut() { cq.apply(world); } } } impl<'w, 's> ParallelCommands<'w, 's> { /// Temporarily provides access to the [`Commands`] for the current thread. /// /// For an example, see the type-level documentation for [`ParallelCommands`]. pub fn command_scope<R>(&self, f: impl FnOnce(Commands) -> R) -> R { self.state.thread_queues.scope(|queue| { let commands = Commands::new_from_entities(queue, self.allocator, self.entities); f(commands) }) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/query/par_iter.rs
crates/bevy_ecs/src/query/par_iter.rs
use crate::{ batching::BatchingStrategy, change_detection::Tick, entity::{EntityEquivalent, UniqueEntityEquivalentVec}, world::unsafe_world_cell::UnsafeWorldCell, }; use super::{QueryData, QueryFilter, QueryItem, QueryState, ReadOnlyQueryData}; use alloc::vec::Vec; /// A parallel iterator over query results of a [`Query`](crate::system::Query). /// /// This struct is created by the [`Query::par_iter`](crate::system::Query::par_iter) and /// [`Query::par_iter_mut`](crate::system::Query::par_iter_mut) methods. pub struct QueryParIter<'w, 's, D: QueryData, F: QueryFilter> { pub(crate) world: UnsafeWorldCell<'w>, pub(crate) state: &'s QueryState<D, F>, pub(crate) last_run: Tick, pub(crate) this_run: Tick, pub(crate) batching_strategy: BatchingStrategy, } impl<'w, 's, D: QueryData, F: QueryFilter> QueryParIter<'w, 's, D, F> { /// Changes the batching strategy used when iterating. /// /// For more information on how this affects the resultant iteration, see /// [`BatchingStrategy`]. pub fn batching_strategy(mut self, strategy: BatchingStrategy) -> Self { self.batching_strategy = strategy; self } /// Runs `func` on each query result in parallel. /// /// # Panics /// If the [`ComputeTaskPool`] is not initialized. If using this from a query that is being /// initialized and run from the ECS scheduler, this should never panic. /// /// [`ComputeTaskPool`]: bevy_tasks::ComputeTaskPool #[inline] pub fn for_each<FN: Fn(QueryItem<'w, 's, D>) + Send + Sync + Clone>(self, func: FN) { self.for_each_init(|| {}, |_, item| func(item)); } /// Runs `func` on each query result in parallel on a value returned by `init`. /// /// `init` may be called multiple times per thread, and the values returned may be discarded between tasks on any given thread. /// Callers should avoid using this function as if it were a parallel version /// of [`Iterator::fold`]. /// /// # Example /// /// ``` /// use bevy_utils::Parallel; /// use crate::{bevy_ecs::prelude::Component, bevy_ecs::system::Query}; /// #[derive(Component)] /// struct T; /// fn system(query: Query<&T>){ /// let mut queue: Parallel<usize> = Parallel::default(); /// // queue.borrow_local_mut() will get or create a thread_local queue for each task/thread; /// query.par_iter().for_each_init(|| queue.borrow_local_mut(),|local_queue, item| { /// **local_queue += 1; /// }); /// /// // collect value from every thread /// let entity_count: usize = queue.iter_mut().map(|v| *v).sum(); /// } /// ``` /// /// # Panics /// If the [`ComputeTaskPool`] is not initialized. If using this from a query that is being /// initialized and run from the ECS scheduler, this should never panic. /// /// [`ComputeTaskPool`]: bevy_tasks::ComputeTaskPool #[inline] pub fn for_each_init<FN, INIT, T>(self, init: INIT, func: FN) where FN: Fn(&mut T, QueryItem<'w, 's, D>) + Send + Sync + Clone, INIT: Fn() -> T + Sync + Send + Clone, { let func = |mut init, item| { func(&mut init, item); init }; #[cfg(any(target_arch = "wasm32", not(feature = "multi_threaded")))] { let init = init(); // SAFETY: // This method can only be called once per instance of QueryParIter, // which ensures that mutable queries cannot be executed multiple times at once. // Mutable instances of QueryParIter can only be created via an exclusive borrow of a // Query or a World, which ensures that multiple aliasing QueryParIters cannot exist // at the same time. unsafe { self.state .query_unchecked_manual_with_ticks(self.world, self.last_run, self.this_run) .into_iter() .fold(init, func); } } #[cfg(all(not(target_arch = "wasm32"), feature = "multi_threaded"))] { let thread_count = bevy_tasks::ComputeTaskPool::get().thread_num(); if thread_count <= 1 { let init = init(); // SAFETY: See the safety comment above. unsafe { self.state .query_unchecked_manual_with_ticks(self.world, self.last_run, self.this_run) .into_iter() .fold(init, func); } } else { // Need a batch size of at least 1. let batch_size = self.get_batch_size(thread_count).max(1); // SAFETY: See the safety comment above. unsafe { self.state.par_fold_init_unchecked_manual( init, self.world, batch_size, func, self.last_run, self.this_run, ); } } } } #[cfg(all(not(target_arch = "wasm32"), feature = "multi_threaded"))] fn get_batch_size(&self, thread_count: usize) -> u32 { let max_items = || { let id_iter = self.state.matched_storage_ids.iter(); if self.state.is_dense { // SAFETY: We only access table metadata. let tables = unsafe { &self.world.world_metadata().storages().tables }; id_iter // SAFETY: The if check ensures that matched_storage_ids stores TableIds .map(|id| unsafe { tables[id.table_id].entity_count() }) .max() } else { let archetypes = &self.world.archetypes(); id_iter // SAFETY: The if check ensures that matched_storage_ids stores ArchetypeIds .map(|id| unsafe { archetypes[id.archetype_id].len() }) .max() } .map(|v| v as usize) .unwrap_or(0) }; self.batching_strategy .calc_batch_size(max_items, thread_count) as u32 } } /// A parallel iterator over the unique query items generated from an [`Entity`] list. /// /// This struct is created by the [`Query::par_iter_many`] method. /// /// [`Entity`]: crate::entity::Entity /// [`Query::par_iter_many`]: crate::system::Query::par_iter_many pub struct QueryParManyIter<'w, 's, D: QueryData, F: QueryFilter, E: EntityEquivalent> { pub(crate) world: UnsafeWorldCell<'w>, pub(crate) state: &'s QueryState<D, F>, pub(crate) entity_list: Vec<E>, pub(crate) last_run: Tick, pub(crate) this_run: Tick, pub(crate) batching_strategy: BatchingStrategy, } impl<'w, 's, D: ReadOnlyQueryData, F: QueryFilter, E: EntityEquivalent + Sync> QueryParManyIter<'w, 's, D, F, E> { /// Changes the batching strategy used when iterating. /// /// For more information on how this affects the resultant iteration, see /// [`BatchingStrategy`]. pub fn batching_strategy(mut self, strategy: BatchingStrategy) -> Self { self.batching_strategy = strategy; self } /// Runs `func` on each query result in parallel. /// /// # Panics /// If the [`ComputeTaskPool`] is not initialized. If using this from a query that is being /// initialized and run from the ECS scheduler, this should never panic. /// /// [`ComputeTaskPool`]: bevy_tasks::ComputeTaskPool #[inline] pub fn for_each<FN: Fn(QueryItem<'w, 's, D>) + Send + Sync + Clone>(self, func: FN) { self.for_each_init(|| {}, |_, item| func(item)); } /// Runs `func` on each query result in parallel on a value returned by `init`. /// /// `init` may be called multiple times per thread, and the values returned may be discarded between tasks on any given thread. /// Callers should avoid using this function as if it were a parallel version /// of [`Iterator::fold`]. /// /// # Example /// /// ``` /// use bevy_utils::Parallel; /// use crate::{bevy_ecs::prelude::{Component, Res, Resource, Entity}, bevy_ecs::system::Query}; /// # use core::slice; /// use bevy_platform::prelude::Vec; /// # fn some_expensive_operation(_item: &T) -> usize { /// # 0 /// # } /// /// #[derive(Component)] /// struct T; /// /// #[derive(Resource)] /// struct V(Vec<Entity>); /// /// impl<'a> IntoIterator for &'a V { /// // ... /// # type Item = &'a Entity; /// # type IntoIter = slice::Iter<'a, Entity>; /// # /// # fn into_iter(self) -> Self::IntoIter { /// # self.0.iter() /// # } /// } /// /// fn system(query: Query<&T>, entities: Res<V>){ /// let mut queue: Parallel<usize> = Parallel::default(); /// // queue.borrow_local_mut() will get or create a thread_local queue for each task/thread; /// query.par_iter_many(&entities).for_each_init(|| queue.borrow_local_mut(),|local_queue, item| { /// **local_queue += some_expensive_operation(item); /// }); /// /// // collect value from every thread /// let final_value: usize = queue.iter_mut().map(|v| *v).sum(); /// } /// ``` /// /// # Panics /// If the [`ComputeTaskPool`] is not initialized. If using this from a query that is being /// initialized and run from the ECS scheduler, this should never panic. /// /// [`ComputeTaskPool`]: bevy_tasks::ComputeTaskPool #[inline] pub fn for_each_init<FN, INIT, T>(self, init: INIT, func: FN) where FN: Fn(&mut T, QueryItem<'w, 's, D>) + Send + Sync + Clone, INIT: Fn() -> T + Sync + Send + Clone, { let func = |mut init, item| { func(&mut init, item); init }; #[cfg(any(target_arch = "wasm32", not(feature = "multi_threaded")))] { let init = init(); // SAFETY: // This method can only be called once per instance of QueryParManyIter, // which ensures that mutable queries cannot be executed multiple times at once. // Mutable instances of QueryParManyUniqueIter can only be created via an exclusive borrow of a // Query or a World, which ensures that multiple aliasing QueryParManyIters cannot exist // at the same time. unsafe { self.state .query_unchecked_manual_with_ticks(self.world, self.last_run, self.this_run) .iter_many_inner(&self.entity_list) .fold(init, func); } } #[cfg(all(not(target_arch = "wasm32"), feature = "multi_threaded"))] { let thread_count = bevy_tasks::ComputeTaskPool::get().thread_num(); if thread_count <= 1 { let init = init(); // SAFETY: See the safety comment above. unsafe { self.state .query_unchecked_manual_with_ticks(self.world, self.last_run, self.this_run) .iter_many_inner(&self.entity_list) .fold(init, func); } } else { // Need a batch size of at least 1. let batch_size = self.get_batch_size(thread_count).max(1); // SAFETY: See the safety comment above. unsafe { self.state.par_many_fold_init_unchecked_manual( init, self.world, &self.entity_list, batch_size, func, self.last_run, self.this_run, ); } } } } #[cfg(all(not(target_arch = "wasm32"), feature = "multi_threaded"))] fn get_batch_size(&self, thread_count: usize) -> u32 { self.batching_strategy .calc_batch_size(|| self.entity_list.len(), thread_count) as u32 } } /// A parallel iterator over the unique query items generated from an [`EntitySet`]. /// /// This struct is created by the [`Query::par_iter_many_unique`] and [`Query::par_iter_many_unique_mut`] methods. /// /// [`EntitySet`]: crate::entity::EntitySet /// [`Query::par_iter_many_unique`]: crate::system::Query::par_iter_many_unique /// [`Query::par_iter_many_unique_mut`]: crate::system::Query::par_iter_many_unique_mut pub struct QueryParManyUniqueIter<'w, 's, D: QueryData, F: QueryFilter, E: EntityEquivalent + Sync> { pub(crate) world: UnsafeWorldCell<'w>, pub(crate) state: &'s QueryState<D, F>, pub(crate) entity_list: UniqueEntityEquivalentVec<E>, pub(crate) last_run: Tick, pub(crate) this_run: Tick, pub(crate) batching_strategy: BatchingStrategy, } impl<'w, 's, D: QueryData, F: QueryFilter, E: EntityEquivalent + Sync> QueryParManyUniqueIter<'w, 's, D, F, E> { /// Changes the batching strategy used when iterating. /// /// For more information on how this affects the resultant iteration, see /// [`BatchingStrategy`]. pub fn batching_strategy(mut self, strategy: BatchingStrategy) -> Self { self.batching_strategy = strategy; self } /// Runs `func` on each query result in parallel. /// /// # Panics /// If the [`ComputeTaskPool`] is not initialized. If using this from a query that is being /// initialized and run from the ECS scheduler, this should never panic. /// /// [`ComputeTaskPool`]: bevy_tasks::ComputeTaskPool #[inline] pub fn for_each<FN: Fn(QueryItem<'w, 's, D>) + Send + Sync + Clone>(self, func: FN) { self.for_each_init(|| {}, |_, item| func(item)); } /// Runs `func` on each query result in parallel on a value returned by `init`. /// /// `init` may be called multiple times per thread, and the values returned may be discarded between tasks on any given thread. /// Callers should avoid using this function as if it were a parallel version /// of [`Iterator::fold`]. /// /// # Example /// /// ``` /// use bevy_utils::Parallel; /// use crate::{bevy_ecs::{prelude::{Component, Res, Resource, Entity}, entity::UniqueEntityVec, system::Query}}; /// # use core::slice; /// # use crate::bevy_ecs::entity::UniqueEntityIter; /// # fn some_expensive_operation(_item: &T) -> usize { /// # 0 /// # } /// /// #[derive(Component)] /// struct T; /// /// #[derive(Resource)] /// struct V(UniqueEntityVec); /// /// impl<'a> IntoIterator for &'a V { /// // ... /// # type Item = &'a Entity; /// # type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>; /// # /// # fn into_iter(self) -> Self::IntoIter { /// # self.0.iter() /// # } /// } /// /// fn system(query: Query<&T>, entities: Res<V>){ /// let mut queue: Parallel<usize> = Parallel::default(); /// // queue.borrow_local_mut() will get or create a thread_local queue for each task/thread; /// query.par_iter_many_unique(&entities).for_each_init(|| queue.borrow_local_mut(),|local_queue, item| { /// **local_queue += some_expensive_operation(item); /// }); /// /// // collect value from every thread /// let final_value: usize = queue.iter_mut().map(|v| *v).sum(); /// } /// ``` /// /// # Panics /// If the [`ComputeTaskPool`] is not initialized. If using this from a query that is being /// initialized and run from the ECS scheduler, this should never panic. /// /// [`ComputeTaskPool`]: bevy_tasks::ComputeTaskPool #[inline] pub fn for_each_init<FN, INIT, T>(self, init: INIT, func: FN) where FN: Fn(&mut T, QueryItem<'w, 's, D>) + Send + Sync + Clone, INIT: Fn() -> T + Sync + Send + Clone, { let func = |mut init, item| { func(&mut init, item); init }; #[cfg(any(target_arch = "wasm32", not(feature = "multi_threaded")))] { let init = init(); // SAFETY: // This method can only be called once per instance of QueryParManyUniqueIter, // which ensures that mutable queries cannot be executed multiple times at once. // Mutable instances of QueryParManyUniqueIter can only be created via an exclusive borrow of a // Query or a World, which ensures that multiple aliasing QueryParManyUniqueIters cannot exist // at the same time. unsafe { self.state .query_unchecked_manual_with_ticks(self.world, self.last_run, self.this_run) .iter_many_unique_inner(self.entity_list) .fold(init, func); } } #[cfg(all(not(target_arch = "wasm32"), feature = "multi_threaded"))] { let thread_count = bevy_tasks::ComputeTaskPool::get().thread_num(); if thread_count <= 1 { let init = init(); // SAFETY: See the safety comment above. unsafe { self.state .query_unchecked_manual_with_ticks(self.world, self.last_run, self.this_run) .iter_many_unique_inner(self.entity_list) .fold(init, func); } } else { // Need a batch size of at least 1. let batch_size = self.get_batch_size(thread_count).max(1); // SAFETY: See the safety comment above. unsafe { self.state.par_many_unique_fold_init_unchecked_manual( init, self.world, &self.entity_list, batch_size, func, self.last_run, self.this_run, ); } } } } #[cfg(all(not(target_arch = "wasm32"), feature = "multi_threaded"))] fn get_batch_size(&self, thread_count: usize) -> u32 { self.batching_strategy .calc_batch_size(|| self.entity_list.len(), thread_count) as u32 } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/query/builder.rs
crates/bevy_ecs/src/query/builder.rs
use core::marker::PhantomData; use crate::{ component::{ComponentId, StorageType}, prelude::*, }; use super::{FilteredAccess, QueryData, QueryFilter}; /// Builder struct to create [`QueryState`] instances at runtime. /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct A; /// # /// # #[derive(Component)] /// # struct B; /// # /// # #[derive(Component)] /// # struct C; /// # /// let mut world = World::new(); /// let entity_a = world.spawn((A, B)).id(); /// let entity_b = world.spawn((A, C)).id(); /// /// // Instantiate the builder using the type signature of the iterator you will consume /// let mut query = QueryBuilder::<(Entity, &B)>::new(&mut world) /// // Add additional terms through builder methods /// .with::<A>() /// .without::<C>() /// .build(); /// /// // Consume the QueryState /// let (entity, b) = query.single(&world).unwrap(); /// ``` pub struct QueryBuilder<'w, D: QueryData = (), F: QueryFilter = ()> { access: FilteredAccess, world: &'w mut World, or: bool, first: bool, _marker: PhantomData<(D, F)>, } impl<'w, D: QueryData, F: QueryFilter> QueryBuilder<'w, D, F> { /// Creates a new builder with the accesses required for `Q` and `F` pub fn new(world: &'w mut World) -> Self { let fetch_state = D::init_state(world); let filter_state = F::init_state(world); let mut access = FilteredAccess::default(); D::update_component_access(&fetch_state, &mut access); // Use a temporary empty FilteredAccess for filters. This prevents them from conflicting with the // main Query's `fetch_state` access. Filters are allowed to conflict with the main query fetch // because they are evaluated *before* a specific reference is constructed. let mut filter_access = FilteredAccess::default(); F::update_component_access(&filter_state, &mut filter_access); // Merge the temporary filter access with the main access. This ensures that filter access is // properly considered in a global "cross-query" context (both within systems and across systems). access.extend(&filter_access); Self { access, world, or: false, first: false, _marker: PhantomData, } } pub(super) fn is_dense(&self) -> bool { // Note: `component_id` comes from the user in safe code, so we cannot trust it to // exist. If it doesn't exist we pessimistically assume it's sparse. let is_dense = |component_id| { self.world() .components() .get_info(component_id) .is_some_and(|info| info.storage_type() == StorageType::Table) }; // Use dense iteration if possible, but fall back to sparse if we need to. // Both `D` and `F` must allow dense iteration, just as for queries without dynamic filters. // All `with` and `without` filters must be dense to ensure that we match all archetypes in a table. // We also need to ensure that any sparse set components in `access.required` cause sparse iteration, // but anything that adds a `required` component also adds a `with` filter. // // Note that `EntityRef` and `EntityMut` types, including `FilteredEntityRef` and `FilteredEntityMut`, have `D::IS_DENSE = true`. // Calling `builder.data::<&Sparse>()` will add a filter and force sparse iteration, // but calling `builder.data::<Option<&Sparse>>()` will still allow them to use dense iteration! D::IS_DENSE && F::IS_DENSE && self.access.with_filters().all(is_dense) && self.access.without_filters().all(is_dense) } /// Returns a reference to the world passed to [`Self::new`]. pub fn world(&self) -> &World { self.world } /// Returns a mutable reference to the world passed to [`Self::new`]. pub fn world_mut(&mut self) -> &mut World { self.world } /// Adds access to self's underlying [`FilteredAccess`] respecting [`Self::or`] and [`Self::and`] pub fn extend_access(&mut self, mut access: FilteredAccess) { if self.or { if self.first { access.required.clear(); self.access.extend(&access); self.first = false; } else { self.access.append_or(&access); } } else { self.access.extend(&access); } } /// Adds accesses required for `T` to self. pub fn data<T: QueryData>(&mut self) -> &mut Self { let state = T::init_state(self.world); let mut access = FilteredAccess::default(); T::update_component_access(&state, &mut access); self.extend_access(access); self } /// Adds filter from `T` to self. pub fn filter<T: QueryFilter>(&mut self) -> &mut Self { let state = T::init_state(self.world); let mut access = FilteredAccess::default(); T::update_component_access(&state, &mut access); self.extend_access(access); self } /// Adds [`With<T>`] to the [`FilteredAccess`] of self. pub fn with<T: Component>(&mut self) -> &mut Self { self.filter::<With<T>>(); self } /// Adds [`With<T>`] to the [`FilteredAccess`] of self from a runtime [`ComponentId`]. pub fn with_id(&mut self, id: ComponentId) -> &mut Self { let mut access = FilteredAccess::default(); access.and_with(id); self.extend_access(access); self } /// Adds [`Without<T>`] to the [`FilteredAccess`] of self. pub fn without<T: Component>(&mut self) -> &mut Self { self.filter::<Without<T>>(); self } /// Adds [`Without<T>`] to the [`FilteredAccess`] of self from a runtime [`ComponentId`]. pub fn without_id(&mut self, id: ComponentId) -> &mut Self { let mut access = FilteredAccess::default(); access.and_without(id); self.extend_access(access); self } /// Adds `&T` to the [`FilteredAccess`] of self. pub fn ref_id(&mut self, id: ComponentId) -> &mut Self { self.with_id(id); self.access.add_component_read(id); self } /// Adds `&mut T` to the [`FilteredAccess`] of self. pub fn mut_id(&mut self, id: ComponentId) -> &mut Self { self.with_id(id); self.access.add_component_write(id); self } /// Takes a function over mutable access to a [`QueryBuilder`], calls that function /// on an empty builder and then adds all accesses from that builder to self as optional. pub fn optional(&mut self, f: impl Fn(&mut QueryBuilder)) -> &mut Self { let mut builder = QueryBuilder::new(self.world); f(&mut builder); self.access.extend_access(builder.access()); self } /// Takes a function over mutable access to a [`QueryBuilder`], calls that function /// on an empty builder and then adds all accesses from that builder to self. /// /// Primarily used when inside a [`Self::or`] closure to group several terms. pub fn and(&mut self, f: impl Fn(&mut QueryBuilder)) -> &mut Self { let mut builder = QueryBuilder::new(self.world); f(&mut builder); let access = builder.access().clone(); self.extend_access(access); self } /// Takes a function over mutable access to a [`QueryBuilder`], calls that function /// on an empty builder, all accesses added to that builder will become terms in an or expression. /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct A; /// # /// # #[derive(Component)] /// # struct B; /// # /// # let mut world = World::new(); /// # /// QueryBuilder::<Entity>::new(&mut world).or(|builder| { /// builder.with::<A>(); /// builder.with::<B>(); /// }); /// // is equivalent to /// QueryBuilder::<Entity>::new(&mut world).filter::<Or<(With<A>, With<B>)>>(); /// ``` pub fn or(&mut self, f: impl Fn(&mut QueryBuilder)) -> &mut Self { let mut builder = QueryBuilder::new(self.world); builder.or = true; builder.first = true; f(&mut builder); self.access.extend(builder.access()); self } /// Returns a reference to the [`FilteredAccess`] that will be provided to the built [`Query`]. pub fn access(&self) -> &FilteredAccess { &self.access } /// Transmute the existing builder adding required accesses. /// This will maintain all existing accesses. /// /// If including a filter type see [`Self::transmute_filtered`] pub fn transmute<NewD: QueryData>(&mut self) -> &mut QueryBuilder<'w, NewD> { self.transmute_filtered::<NewD, ()>() } /// Transmute the existing builder adding required accesses. /// This will maintain all existing accesses. pub fn transmute_filtered<NewD: QueryData, NewF: QueryFilter>( &mut self, ) -> &mut QueryBuilder<'w, NewD, NewF> { let fetch_state = NewD::init_state(self.world); let filter_state = NewF::init_state(self.world); let mut access = FilteredAccess::default(); NewD::update_component_access(&fetch_state, &mut access); NewF::update_component_access(&filter_state, &mut access); self.extend_access(access); // SAFETY: // - We have included all required accesses for NewQ and NewF // - The layout of all QueryBuilder instances is the same unsafe { core::mem::transmute(self) } } /// Create a [`QueryState`] with the accesses of the builder. /// /// Takes `&mut self` to access the inner world reference while initializing /// state for the new [`QueryState`] pub fn build(&mut self) -> QueryState<D, F> { QueryState::<D, F>::from_builder(self) } } #[cfg(test)] mod tests { use crate::{ prelude::*, world::{EntityMutExcept, EntityRefExcept, FilteredEntityMut, FilteredEntityRef}, }; use std::dbg; #[derive(Component, PartialEq, Debug)] struct A(usize); #[derive(Component, PartialEq, Debug)] struct B(usize); #[derive(Component, PartialEq, Debug)] struct C(usize); #[derive(Component)] struct D; #[test] fn builder_with_without_static() { let mut world = World::new(); let entity_a = world.spawn((A(0), B(0))).id(); let entity_b = world.spawn((A(0), C(0))).id(); let mut query_a = QueryBuilder::<Entity>::new(&mut world) .with::<A>() .without::<C>() .build(); assert_eq!(entity_a, query_a.single(&world).unwrap()); let mut query_b = QueryBuilder::<Entity>::new(&mut world) .with::<A>() .without::<B>() .build(); assert_eq!(entity_b, query_b.single(&world).unwrap()); } #[test] fn builder_with_without_dynamic() { let mut world = World::new(); let entity_a = world.spawn((A(0), B(0))).id(); let entity_b = world.spawn((A(0), C(0))).id(); let component_id_a = world.register_component::<A>(); let component_id_b = world.register_component::<B>(); let component_id_c = world.register_component::<C>(); let mut query_a = QueryBuilder::<Entity>::new(&mut world) .with_id(component_id_a) .without_id(component_id_c) .build(); assert_eq!(entity_a, query_a.single(&world).unwrap()); let mut query_b = QueryBuilder::<Entity>::new(&mut world) .with_id(component_id_a) .without_id(component_id_b) .build(); assert_eq!(entity_b, query_b.single(&world).unwrap()); } #[test] fn builder_or() { let mut world = World::new(); world.spawn((A(0), B(0), D)); world.spawn((B(0), D)); world.spawn((C(0), D)); let mut query_a = QueryBuilder::<&D>::new(&mut world) .or(|builder| { builder.with::<A>(); builder.with::<B>(); }) .build(); assert_eq!(2, query_a.iter(&world).count()); let mut query_b = QueryBuilder::<&D>::new(&mut world) .or(|builder| { builder.with::<A>(); builder.without::<B>(); }) .build(); dbg!(&query_b.component_access); assert_eq!(2, query_b.iter(&world).count()); let mut query_c = QueryBuilder::<&D>::new(&mut world) .or(|builder| { builder.with::<A>(); builder.with::<B>(); builder.with::<C>(); }) .build(); assert_eq!(3, query_c.iter(&world).count()); } #[test] fn builder_transmute() { let mut world = World::new(); world.spawn(A(0)); world.spawn((A(1), B(0))); let mut query = QueryBuilder::<()>::new(&mut world) .with::<B>() .transmute::<&A>() .build(); query.iter(&world).for_each(|a| assert_eq!(a.0, 1)); } #[test] fn builder_static_components() { let mut world = World::new(); let entity = world.spawn((A(0), B(1))).id(); let mut query = QueryBuilder::<FilteredEntityRef>::new(&mut world) .data::<&A>() .data::<&B>() .build(); let entity_ref = query.single(&world).unwrap(); assert_eq!(entity, entity_ref.id()); let a = entity_ref.get::<A>().unwrap(); let b = entity_ref.get::<B>().unwrap(); assert_eq!(0, a.0); assert_eq!(1, b.0); } #[test] fn builder_dynamic_components() { let mut world = World::new(); let entity = world.spawn((A(0), B(1))).id(); let component_id_a = world.register_component::<A>(); let component_id_b = world.register_component::<B>(); let mut query = QueryBuilder::<FilteredEntityRef>::new(&mut world) .ref_id(component_id_a) .ref_id(component_id_b) .build(); let entity_ref = query.single(&world).unwrap(); assert_eq!(entity, entity_ref.id()); let a = entity_ref.get_by_id(component_id_a).unwrap(); let b = entity_ref.get_by_id(component_id_b).unwrap(); // SAFETY: We set these pointers to point to these components unsafe { assert_eq!(0, a.deref::<A>().0); assert_eq!(1, b.deref::<B>().0); } } #[test] fn builder_provide_access() { let mut world = World::new(); world.spawn((A(0), B(1), D)); let mut query = QueryBuilder::<(Entity, FilteredEntityRef, FilteredEntityMut), With<D>>::new( &mut world, ) .data::<&mut A>() .data::<&B>() .build(); // The `FilteredEntityRef` only has read access, so the `FilteredEntityMut` can have read access without conflicts let (_entity, entity_ref_1, mut entity_ref_2) = query.single_mut(&mut world).unwrap(); assert!(entity_ref_1.get::<A>().is_some()); assert!(entity_ref_1.get::<B>().is_some()); assert!(entity_ref_2.get::<A>().is_some()); assert!(entity_ref_2.get_mut::<A>().is_none()); assert!(entity_ref_2.get::<B>().is_some()); assert!(entity_ref_2.get_mut::<B>().is_none()); let mut query = QueryBuilder::<(Entity, FilteredEntityMut, FilteredEntityMut), With<D>>::new( &mut world, ) .data::<&mut A>() .data::<&B>() .build(); // The first `FilteredEntityMut` has write access to A, so the second one cannot have write access let (_entity, mut entity_ref_1, mut entity_ref_2) = query.single_mut(&mut world).unwrap(); assert!(entity_ref_1.get::<A>().is_some()); assert!(entity_ref_1.get_mut::<A>().is_some()); assert!(entity_ref_1.get::<B>().is_some()); assert!(entity_ref_1.get_mut::<B>().is_none()); assert!(entity_ref_2.get::<A>().is_none()); assert!(entity_ref_2.get_mut::<A>().is_none()); assert!(entity_ref_2.get::<B>().is_some()); assert!(entity_ref_2.get_mut::<B>().is_none()); let mut query = QueryBuilder::<(FilteredEntityMut, &mut A, &B), With<D>>::new(&mut world) .data::<&mut A>() .data::<&mut B>() .build(); // Any `A` access would conflict with `&mut A`, and write access to `B` would conflict with `&B`. let (mut entity_ref, _a, _b) = query.single_mut(&mut world).unwrap(); assert!(entity_ref.get::<A>().is_none()); assert!(entity_ref.get_mut::<A>().is_none()); assert!(entity_ref.get::<B>().is_some()); assert!(entity_ref.get_mut::<B>().is_none()); let mut query = QueryBuilder::<(FilteredEntityMut, &mut A, &B), With<D>>::new(&mut world) .data::<EntityMut>() .build(); // Same as above, but starting from "all" access let (mut entity_ref, _a, _b) = query.single_mut(&mut world).unwrap(); assert!(entity_ref.get::<A>().is_none()); assert!(entity_ref.get_mut::<A>().is_none()); assert!(entity_ref.get::<B>().is_some()); assert!(entity_ref.get_mut::<B>().is_none()); let mut query = QueryBuilder::<(FilteredEntityMut, EntityMutExcept<A>), With<D>>::new(&mut world) .data::<EntityMut>() .build(); // Removing `EntityMutExcept<A>` just leaves A let (mut entity_ref_1, _entity_ref_2) = query.single_mut(&mut world).unwrap(); assert!(entity_ref_1.get::<A>().is_some()); assert!(entity_ref_1.get_mut::<A>().is_some()); assert!(entity_ref_1.get::<B>().is_none()); assert!(entity_ref_1.get_mut::<B>().is_none()); let mut query = QueryBuilder::<(FilteredEntityMut, EntityRefExcept<A>), With<D>>::new(&mut world) .data::<EntityMut>() .build(); // Removing `EntityRefExcept<A>` just leaves A, plus read access let (mut entity_ref_1, _entity_ref_2) = query.single_mut(&mut world).unwrap(); assert!(entity_ref_1.get::<A>().is_some()); assert!(entity_ref_1.get_mut::<A>().is_some()); assert!(entity_ref_1.get::<B>().is_some()); assert!(entity_ref_1.get_mut::<B>().is_none()); } /// Regression test for issue #14348 #[test] fn builder_static_dense_dynamic_sparse() { #[derive(Component)] struct Dense; #[derive(Component)] #[component(storage = "SparseSet")] struct Sparse; let mut world = World::new(); world.spawn(Dense); world.spawn((Dense, Sparse)); let mut query = QueryBuilder::<&Dense>::new(&mut world) .with::<Sparse>() .build(); let matched = query.iter(&world).count(); assert_eq!(matched, 1); } #[test] fn builder_dynamic_can_be_dense() { #[derive(Component)] #[component(storage = "SparseSet")] struct Sparse; let mut world = World::new(); // FilteredEntityRef and FilteredEntityMut are dense by default let query = QueryBuilder::<FilteredEntityRef>::new(&mut world).build(); assert!(query.is_dense); let query = QueryBuilder::<FilteredEntityMut>::new(&mut world).build(); assert!(query.is_dense); // Adding a required sparse term makes the query sparse let query = QueryBuilder::<FilteredEntityRef>::new(&mut world) .data::<&Sparse>() .build(); assert!(!query.is_dense); // Adding an optional sparse term lets it remain dense let query = QueryBuilder::<FilteredEntityRef>::new(&mut world) .data::<Option<&Sparse>>() .build(); assert!(query.is_dense); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/query/filter.rs
crates/bevy_ecs/src/query/filter.rs
use crate::{ archetype::Archetype, change_detection::Tick, component::{Component, ComponentId, Components, StorageType}, entity::{Entities, Entity}, query::{DebugCheckedUnwrap, FilteredAccess, StorageSwitch, WorldQuery}, storage::{ComponentSparseSet, Table, TableRow}, world::{unsafe_world_cell::UnsafeWorldCell, World}, }; use bevy_ptr::{ThinSlicePtr, UnsafeCellDeref}; use bevy_utils::prelude::DebugName; use core::{cell::UnsafeCell, marker::PhantomData}; use variadics_please::all_tuples; /// Types that filter the results of a [`Query`]. /// /// There are many types that natively implement this trait: /// - **Component filters.** /// [`With`] and [`Without`] filters can be applied to check if the queried entity does or does not contain a particular component. /// - **Change detection filters.** /// [`Added`] and [`Changed`] filters can be applied to detect component changes to an entity. /// - **Spawned filter.** /// [`Spawned`] filter can be applied to check if the queried entity was spawned recently. /// - **`QueryFilter` tuples.** /// If every element of a tuple implements `QueryFilter`, then the tuple itself also implements the same trait. /// This enables a single `Query` to filter over multiple conditions. /// Due to the current lack of variadic generics in Rust, the trait has been implemented for tuples from 0 to 15 elements, /// but nesting of tuples allows infinite `QueryFilter`s. /// - **Filter disjunction operator.** /// By default, tuples compose query filters in such a way that all conditions must be satisfied to generate a query item for a given entity. /// Wrapping a tuple inside an [`Or`] operator will relax the requirement to just one condition. /// /// Implementing the trait manually can allow for a fundamentally new type of behavior. /// /// Query design can be easily structured by deriving `QueryFilter` for custom types. /// Despite the added complexity, this approach has several advantages over using `QueryFilter` tuples. /// The most relevant improvements are: /// /// - Reusability across multiple systems. /// - Filters can be composed together to create a more complex filter. /// /// This trait can only be derived for structs if each field also implements `QueryFilter`. /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_ecs::{query::QueryFilter, component::Component}; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # #[derive(Component)] /// # struct ComponentB; /// # #[derive(Component)] /// # struct ComponentC; /// # #[derive(Component)] /// # struct ComponentD; /// # #[derive(Component)] /// # struct ComponentE; /// # /// #[derive(QueryFilter)] /// struct MyFilter<T: Component, P: Component> { /// // Field names are not relevant, since they are never manually accessed. /// with_a: With<ComponentA>, /// or_filter: Or<(With<ComponentC>, Added<ComponentB>)>, /// generic_tuple: (With<T>, Without<P>), /// } /// /// fn my_system(query: Query<Entity, MyFilter<ComponentD, ComponentE>>) { /// // ... /// } /// # bevy_ecs::system::assert_is_system(my_system); /// ``` /// /// [`Query`]: crate::system::Query /// /// # Safety /// /// The [`WorldQuery`] implementation must not take any mutable access. /// This is the same safety requirement as [`ReadOnlyQueryData`](crate::query::ReadOnlyQueryData). #[diagnostic::on_unimplemented( message = "`{Self}` is not a valid `Query` filter", label = "invalid `Query` filter", note = "a `QueryFilter` typically uses a combination of `With<T>` and `Without<T>` statements" )] pub unsafe trait QueryFilter: WorldQuery { /// Returns true if (and only if) this Filter relies strictly on archetypes to limit which /// components are accessed by the Query. /// /// This enables optimizations for [`QueryIter`](`crate::query::QueryIter`) that rely on knowing exactly how /// many elements are being iterated (such as `Iterator::collect()`). /// /// If this is `true`, then [`QueryFilter::filter_fetch`] must always return true. const IS_ARCHETYPAL: bool; /// Returns true if the provided [`Entity`] and [`TableRow`] should be included in the query results. /// If false, the entity will be skipped. /// /// Note that this is called after already restricting the matched [`Table`]s and [`Archetype`]s to the /// ones that are compatible with the Filter's access. /// /// Implementors of this method will generally either have a trivial `true` body (required for archetypal filters), /// or access the necessary data within this function to make the final decision on filter inclusion. /// /// # Safety /// /// Must always be called _after_ [`WorldQuery::set_table`] or [`WorldQuery::set_archetype`]. `entity` and /// `table_row` must be in the range of the current table and archetype. unsafe fn filter_fetch( state: &Self::State, fetch: &mut Self::Fetch<'_>, entity: Entity, table_row: TableRow, ) -> bool; } /// Filter that selects entities with a component `T`. /// /// This can be used in a [`Query`](crate::system::Query) if entities are required to have the /// component `T` but you don't actually care about components value. /// /// This is the negation of [`Without`]. /// /// # Examples /// /// ``` /// # use bevy_ecs::component::Component; /// # use bevy_ecs::query::With; /// # use bevy_ecs::system::IntoSystem; /// # use bevy_ecs::system::Query; /// # /// # #[derive(Component)] /// # struct IsBeautiful; /// # #[derive(Component)] /// # struct Name { name: &'static str }; /// # /// fn compliment_entity_system(query: Query<&Name, With<IsBeautiful>>) { /// for name in &query { /// println!("{} is looking lovely today!", name.name); /// } /// } /// # bevy_ecs::system::assert_is_system(compliment_entity_system); /// ``` pub struct With<T>(PhantomData<T>); /// SAFETY: /// `update_component_access` does not add any accesses. /// This is sound because [`QueryFilter::filter_fetch`] does not access any components. /// `update_component_access` adds a `With` filter for `T`. /// This is sound because `matches_component_set` returns whether the set contains the component. unsafe impl<T: Component> WorldQuery for With<T> { type Fetch<'w> = (); type State = ComponentId; fn shrink_fetch<'wlong: 'wshort, 'wshort>(_: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {} #[inline] unsafe fn init_fetch( _world: UnsafeWorldCell, _state: &ComponentId, _last_run: Tick, _this_run: Tick, ) { } const IS_DENSE: bool = { match T::STORAGE_TYPE { StorageType::Table => true, StorageType::SparseSet => false, } }; #[inline] unsafe fn set_archetype( _fetch: &mut (), _state: &ComponentId, _archetype: &Archetype, _table: &Table, ) { } #[inline] unsafe fn set_table(_fetch: &mut (), _state: &ComponentId, _table: &Table) {} #[inline] fn update_component_access(&id: &ComponentId, access: &mut FilteredAccess) { access.and_with(id); } fn init_state(world: &mut World) -> ComponentId { world.register_component::<T>() } fn get_state(components: &Components) -> Option<Self::State> { components.component_id::<T>() } fn matches_component_set( &id: &ComponentId, set_contains_id: &impl Fn(ComponentId) -> bool, ) -> bool { set_contains_id(id) } } // SAFETY: WorldQuery impl performs no access at all unsafe impl<T: Component> QueryFilter for With<T> { const IS_ARCHETYPAL: bool = true; #[inline(always)] unsafe fn filter_fetch( _state: &Self::State, _fetch: &mut Self::Fetch<'_>, _entity: Entity, _table_row: TableRow, ) -> bool { true } } /// Filter that selects entities without a component `T`. /// /// This is the negation of [`With`]. /// /// # Examples /// /// ``` /// # use bevy_ecs::component::Component; /// # use bevy_ecs::query::Without; /// # use bevy_ecs::system::IntoSystem; /// # use bevy_ecs::system::Query; /// # /// # #[derive(Component)] /// # struct Permit; /// # #[derive(Component)] /// # struct Name { name: &'static str }; /// # /// fn no_permit_system(query: Query<&Name, Without<Permit>>) { /// for name in &query{ /// println!("{} has no permit!", name.name); /// } /// } /// # bevy_ecs::system::assert_is_system(no_permit_system); /// ``` pub struct Without<T>(PhantomData<T>); /// SAFETY: /// `update_component_access` does not add any accesses. /// This is sound because [`QueryFilter::filter_fetch`] does not access any components. /// `update_component_access` adds a `Without` filter for `T`. /// This is sound because `matches_component_set` returns whether the set does not contain the component. unsafe impl<T: Component> WorldQuery for Without<T> { type Fetch<'w> = (); type State = ComponentId; fn shrink_fetch<'wlong: 'wshort, 'wshort>(_: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {} #[inline] unsafe fn init_fetch( _world: UnsafeWorldCell, _state: &ComponentId, _last_run: Tick, _this_run: Tick, ) { } const IS_DENSE: bool = { match T::STORAGE_TYPE { StorageType::Table => true, StorageType::SparseSet => false, } }; #[inline] unsafe fn set_archetype( _fetch: &mut (), _state: &ComponentId, _archetype: &Archetype, _table: &Table, ) { } #[inline] unsafe fn set_table(_fetch: &mut (), _state: &Self::State, _table: &Table) {} #[inline] fn update_component_access(&id: &ComponentId, access: &mut FilteredAccess) { access.and_without(id); } fn init_state(world: &mut World) -> ComponentId { world.register_component::<T>() } fn get_state(components: &Components) -> Option<Self::State> { components.component_id::<T>() } fn matches_component_set( &id: &ComponentId, set_contains_id: &impl Fn(ComponentId) -> bool, ) -> bool { !set_contains_id(id) } } // SAFETY: WorldQuery impl performs no access at all unsafe impl<T: Component> QueryFilter for Without<T> { const IS_ARCHETYPAL: bool = true; #[inline(always)] unsafe fn filter_fetch( _state: &Self::State, _fetch: &mut Self::Fetch<'_>, _entity: Entity, _table_row: TableRow, ) -> bool { true } } /// A filter that tests if any of the given filters apply. /// /// This is useful for example if a system with multiple components in a query only wants to run /// when one or more of the components have changed. /// /// The `And` equivalent to this filter is a [`prim@tuple`] testing that all the contained filters /// apply instead. /// /// # Examples /// /// ``` /// # use bevy_ecs::component::Component; /// # use bevy_ecs::entity::Entity; /// # use bevy_ecs::query::Changed; /// # use bevy_ecs::query::Or; /// # use bevy_ecs::system::IntoSystem; /// # use bevy_ecs::system::Query; /// # /// # #[derive(Component, Debug)] /// # struct Color {}; /// # #[derive(Component)] /// # struct Node {}; /// # /// fn print_cool_entity_system(query: Query<Entity, Or<(Changed<Color>, Changed<Node>)>>) { /// for entity in &query { /// println!("Entity {} got a new style or color", entity); /// } /// } /// # bevy_ecs::system::assert_is_system(print_cool_entity_system); /// ``` pub struct Or<T>(PhantomData<T>); #[doc(hidden)] pub struct OrFetch<'w, T: WorldQuery> { fetch: T::Fetch<'w>, matches: bool, } impl<T: WorldQuery> Clone for OrFetch<'_, T> { fn clone(&self) -> Self { Self { fetch: self.fetch.clone(), matches: self.matches, } } } macro_rules! impl_or_query_filter { ($(#[$meta:meta])* $(($filter: ident, $state: ident)),*) => { $(#[$meta])* #[expect( clippy::allow_attributes, reason = "This is a tuple-related macro; as such the lints below may not always apply." )] #[allow( non_snake_case, reason = "The names of some variables are provided by the macro's caller, not by us." )] #[allow( unused_variables, reason = "Zero-length tuples won't use any of the parameters." )] #[allow( clippy::unused_unit, reason = "Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case." )] /// SAFETY: /// [`QueryFilter::filter_fetch`] accesses are a subset of the subqueries' accesses /// This is sound because `update_component_access` adds accesses according to the implementations of all the subqueries. /// `update_component_access` replace the filters with a disjunction where every element is a conjunction of the previous filters and the filters of one of the subqueries. /// This is sound because `matches_component_set` returns a disjunction of the results of the subqueries' implementations. unsafe impl<$($filter: QueryFilter),*> WorldQuery for Or<($($filter,)*)> { type Fetch<'w> = ($(OrFetch<'w, $filter>,)*); type State = ($($filter::State,)*); fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> { let ($($filter,)*) = fetch; ($( OrFetch { fetch: $filter::shrink_fetch($filter.fetch), matches: $filter.matches }, )*) } const IS_DENSE: bool = true $(&& $filter::IS_DENSE)*; #[inline] unsafe fn init_fetch<'w, 's>(world: UnsafeWorldCell<'w>, state: &'s Self::State, last_run: Tick, this_run: Tick) -> Self::Fetch<'w> { let ($($filter,)*) = state; ($(OrFetch { // SAFETY: The invariants are upheld by the caller. fetch: unsafe { $filter::init_fetch(world, $filter, last_run, this_run) }, matches: false, },)*) } #[inline] unsafe fn set_table<'w, 's>(fetch: &mut Self::Fetch<'w>, state: &'s Self::State, table: &'w Table) { // If this is an archetypal query, then it is guaranteed to match all entities, // so `filter_fetch` will ignore `$filter.matches` and we don't need to initialize it. if Self::IS_ARCHETYPAL { return; } let ($($filter,)*) = fetch; let ($($state,)*) = state; $( $filter.matches = $filter::matches_component_set($state, &|id| table.has_column(id)); if $filter.matches { // SAFETY: The invariants are upheld by the caller. unsafe { $filter::set_table(&mut $filter.fetch, $state, table); } } )* } #[inline] unsafe fn set_archetype<'w, 's>( fetch: &mut Self::Fetch<'w>, state: &'s Self::State, archetype: &'w Archetype, table: &'w Table ) { // If this is an archetypal query, then it is guaranteed to match all entities, // so `filter_fetch` will ignore `$filter.matches` and we don't need to initialize it. if Self::IS_ARCHETYPAL { return; } let ($($filter,)*) = fetch; let ($($state,)*) = &state; $( $filter.matches = $filter::matches_component_set($state, &|id| archetype.contains(id)); if $filter.matches { // SAFETY: The invariants are upheld by the caller. unsafe { $filter::set_archetype(&mut $filter.fetch, $state, archetype, table); } } )* } fn update_component_access(state: &Self::State, access: &mut FilteredAccess) { let ($($filter,)*) = state; let mut new_access = FilteredAccess::matches_nothing(); $( // Create an intermediate because `access`'s value needs to be preserved // for the next filter, and `_new_access` has to be modified only by `append_or` to it. let mut intermediate = access.clone(); $filter::update_component_access($filter, &mut intermediate); new_access.append_or(&intermediate); // Also extend the accesses required to compute the filter. This is required because // otherwise a `Query<(), Or<(Changed<Foo>,)>` won't conflict with `Query<&mut Foo>`. new_access.extend_access(&intermediate); )* // The required components remain the same as the original `access`. new_access.required = core::mem::take(&mut access.required); *access = new_access; } fn init_state(world: &mut World) -> Self::State { ($($filter::init_state(world),)*) } fn get_state(components: &Components) -> Option<Self::State> { Some(($($filter::get_state(components)?,)*)) } fn matches_component_set(state: &Self::State, set_contains_id: &impl Fn(ComponentId) -> bool) -> bool { let ($($filter,)*) = state; false $(|| $filter::matches_component_set($filter, set_contains_id))* } } #[expect( clippy::allow_attributes, reason = "This is a tuple-related macro; as such the lints below may not always apply." )] #[allow( non_snake_case, reason = "The names of some variables are provided by the macro's caller, not by us." )] #[allow( unused_variables, reason = "Zero-length tuples won't use any of the parameters." )] $(#[$meta])* // SAFETY: This only performs access that subqueries perform, and they impl `QueryFilter` and so perform no mutable access. unsafe impl<$($filter: QueryFilter),*> QueryFilter for Or<($($filter,)*)> { const IS_ARCHETYPAL: bool = true $(&& $filter::IS_ARCHETYPAL)*; #[inline(always)] unsafe fn filter_fetch( state: &Self::State, fetch: &mut Self::Fetch<'_>, entity: Entity, table_row: TableRow ) -> bool { let ($($state,)*) = state; let ($($filter,)*) = fetch; // If this is an archetypal query, then it is guaranteed to return true, // and we can help the compiler remove branches by checking the const `IS_ARCHETYPAL` first. (Self::IS_ARCHETYPAL // SAFETY: The invariants are upheld by the caller. $(|| ($filter.matches && unsafe { $filter::filter_fetch($state, &mut $filter.fetch, entity, table_row) }))* // If *none* of the subqueries matched the archetype, then this archetype was added in a transmute. // We must treat those as matching in order to be consistent with `size_hint` for archetypal queries, // so we treat them as matching for non-archetypal queries, as well. || !(false $(|| $filter.matches)*)) } } }; } macro_rules! impl_tuple_query_filter { ($(#[$meta:meta])* $(($name: ident, $state: ident)),*) => { #[expect( clippy::allow_attributes, reason = "This is a tuple-related macro; as such the lints below may not always apply." )] #[allow( non_snake_case, reason = "The names of some variables are provided by the macro's caller, not by us." )] #[allow( unused_variables, reason = "Zero-length tuples won't use any of the parameters." )] $(#[$meta])* // SAFETY: This only performs access that subqueries perform, and they impl `QueryFilter` and so perform no mutable access. unsafe impl<$($name: QueryFilter),*> QueryFilter for ($($name,)*) { const IS_ARCHETYPAL: bool = true $(&& $name::IS_ARCHETYPAL)*; #[inline(always)] unsafe fn filter_fetch( state: &Self::State, fetch: &mut Self::Fetch<'_>, entity: Entity, table_row: TableRow ) -> bool { let ($($state,)*) = state; let ($($name,)*) = fetch; // SAFETY: The invariants are upheld by the caller. true $(&& unsafe { $name::filter_fetch($state, $name, entity, table_row) })* } } }; } all_tuples!( #[doc(fake_variadic)] impl_tuple_query_filter, 0, 15, F, S ); all_tuples!( #[doc(fake_variadic)] impl_or_query_filter, 0, 15, F, S ); /// Allows a query to contain entities with the component `T`, bypassing [`DefaultQueryFilters`]. /// /// [`DefaultQueryFilters`]: crate::entity_disabling::DefaultQueryFilters pub struct Allow<T>(PhantomData<T>); /// SAFETY: /// `update_component_access` does not add any accesses. /// This is sound because [`QueryFilter::filter_fetch`] does not access any components. /// `update_component_access` adds an archetypal filter for `T`. /// This is sound because it doesn't affect the query unsafe impl<T: Component> WorldQuery for Allow<T> { type Fetch<'w> = (); type State = ComponentId; fn shrink_fetch<'wlong: 'wshort, 'wshort>(_: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {} #[inline] unsafe fn init_fetch(_: UnsafeWorldCell, _: &ComponentId, _: Tick, _: Tick) {} // Even if the component is sparse, this implementation doesn't do anything with it const IS_DENSE: bool = true; #[inline] unsafe fn set_archetype(_: &mut (), _: &ComponentId, _: &Archetype, _: &Table) {} #[inline] unsafe fn set_table(_: &mut (), _: &ComponentId, _: &Table) {} #[inline] fn update_component_access(&id: &ComponentId, access: &mut FilteredAccess) { access.access_mut().add_archetypal(id); } fn init_state(world: &mut World) -> ComponentId { world.register_component::<T>() } fn get_state(components: &Components) -> Option<Self::State> { components.component_id::<T>() } fn matches_component_set(_: &ComponentId, _: &impl Fn(ComponentId) -> bool) -> bool { // Allow<T> always matches true } } // SAFETY: WorldQuery impl performs no access at all unsafe impl<T: Component> QueryFilter for Allow<T> { const IS_ARCHETYPAL: bool = true; #[inline(always)] unsafe fn filter_fetch( _: &Self::State, _: &mut Self::Fetch<'_>, _: Entity, _: TableRow, ) -> bool { true } } /// A filter on a component that only retains results the first time after they have been added. /// /// A common use for this filter is one-time initialization. /// /// To retain all results without filtering but still check whether they were added after the /// system last ran, use [`Ref<T>`](crate::change_detection::Ref). /// /// **Note** that this includes changes that happened before the first time this `Query` was run. /// /// # Deferred /// /// Note, that entity modifications issued with [`Commands`](crate::system::Commands) /// are visible only after deferred operations are applied, typically after the system /// that queued them. /// /// # Time complexity /// /// `Added` is not [`ArchetypeFilter`], which practically means that /// if the query (with `T` component filter) matches a million entities, /// `Added<T>` filter will iterate over all of them even if none of them were just added. /// /// For example, these two systems are roughly equivalent in terms of performance: /// /// ``` /// # use bevy_ecs::change_detection::{DetectChanges, Ref}; /// # use bevy_ecs::entity::Entity; /// # use bevy_ecs::query::Added; /// # use bevy_ecs::system::Query; /// # use bevy_ecs_macros::Component; /// # #[derive(Component)] /// # struct MyComponent; /// # #[derive(Component)] /// # struct Transform; /// /// fn system1(q: Query<&MyComponent, Added<Transform>>) { /// for item in &q { /* component added */ } /// } /// /// fn system2(q: Query<(&MyComponent, Ref<Transform>)>) { /// for item in &q { /// if item.1.is_added() { /* component added */ } /// } /// } /// ``` /// /// # Examples /// /// ``` /// # use bevy_ecs::component::Component; /// # use bevy_ecs::query::Added; /// # use bevy_ecs::system::IntoSystem; /// # use bevy_ecs::system::Query; /// # /// # #[derive(Component, Debug)] /// # struct Name {}; /// /// fn print_add_name_component(query: Query<&Name, Added<Name>>) { /// for name in &query { /// println!("Named entity created: {:?}", name) /// } /// } /// /// # bevy_ecs::system::assert_is_system(print_add_name_component); /// ``` pub struct Added<T>(PhantomData<T>); #[doc(hidden)] pub struct AddedFetch<'w, T: Component> { ticks: StorageSwitch< T, // T::STORAGE_TYPE = StorageType::Table Option<ThinSlicePtr<'w, UnsafeCell<Tick>>>, // T::STORAGE_TYPE = StorageType::SparseSet // Can be `None` when the component has never been inserted Option<&'w ComponentSparseSet>, >, last_run: Tick, this_run: Tick, } impl<T: Component> Clone for AddedFetch<'_, T> { fn clone(&self) -> Self { Self { ticks: self.ticks, last_run: self.last_run, this_run: self.this_run, } } } /// SAFETY: /// [`QueryFilter::filter_fetch`] accesses a single component in a readonly way. /// This is sound because `update_component_access` adds read access for that component and panics when appropriate. /// `update_component_access` adds a `With` filter for a component. /// This is sound because `matches_component_set` returns whether the set contains that component. unsafe impl<T: Component> WorldQuery for Added<T> { type Fetch<'w> = AddedFetch<'w, T>; type State = ComponentId; fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> { fetch } #[inline] unsafe fn init_fetch<'w, 's>( world: UnsafeWorldCell<'w>, &id: &'s ComponentId, last_run: Tick, this_run: Tick, ) -> Self::Fetch<'w> { Self::Fetch::<'w> { ticks: StorageSwitch::new( || None, || { // SAFETY: The underlying type associated with `component_id` is `T`, // which we are allowed to access since we registered it in `update_component_access`. // Note that we do not actually access any components' ticks in this function, we just get a shared // reference to the sparse set, which is used to access the components' ticks in `Self::fetch`. unsafe { world.storages().sparse_sets.get(id) } }, ), last_run, this_run, } } const IS_DENSE: bool = { match T::STORAGE_TYPE { StorageType::Table => true, StorageType::SparseSet => false, } }; #[inline] unsafe fn set_archetype<'w, 's>( fetch: &mut Self::Fetch<'w>, component_id: &'s ComponentId, _archetype: &'w Archetype, table: &'w Table, ) { if Self::IS_DENSE { // SAFETY: `set_archetype`'s safety rules are a super set of the `set_table`'s ones. unsafe { Self::set_table(fetch, component_id, table); } } } #[inline] unsafe fn set_table<'w, 's>( fetch: &mut Self::Fetch<'w>, &component_id: &'s ComponentId, table: &'w Table, ) { let table_ticks = Some( table .get_added_ticks_slice_for(component_id) .debug_checked_unwrap() .into(), ); // SAFETY: set_table is only called when T::STORAGE_TYPE = StorageType::Table unsafe { fetch.ticks.set_table(table_ticks) }; } #[inline] fn update_component_access(&id: &ComponentId, access: &mut FilteredAccess) { if access.access().has_component_write(id) { panic!("$state_name<{}> conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.", DebugName::type_name::<T>()); } access.add_component_read(id); } fn init_state(world: &mut World) -> ComponentId { world.register_component::<T>() } fn get_state(components: &Components) -> Option<ComponentId> { components.component_id::<T>() } fn matches_component_set( &id: &ComponentId, set_contains_id: &impl Fn(ComponentId) -> bool, ) -> bool { set_contains_id(id) } } // SAFETY: WorldQuery impl performs only read access on ticks unsafe impl<T: Component> QueryFilter for Added<T> { const IS_ARCHETYPAL: bool = false; #[inline(always)] unsafe fn filter_fetch( _state: &Self::State, fetch: &mut Self::Fetch<'_>, entity: Entity, table_row: TableRow, ) -> bool { // SAFETY: The invariants are upheld by the caller. fetch.ticks.extract( |table| { // SAFETY: set_table was previously called let table = unsafe { table.debug_checked_unwrap() }; // SAFETY: The caller ensures `table_row` is in range. let tick = unsafe { table.get_unchecked(table_row.index()) }; tick.deref().is_newer_than(fetch.last_run, fetch.this_run) }, |sparse_set| { // SAFETY: The caller ensures `entity` is in range. let tick = unsafe { sparse_set .debug_checked_unwrap() .get_added_tick(entity) .debug_checked_unwrap() }; tick.deref().is_newer_than(fetch.last_run, fetch.this_run) }, ) } } /// A filter on a component that only retains results the first time after they have been added or mutably dereferenced. /// /// A common use for this filter is avoiding redundant work when values have not changed. /// /// **Note** that simply *mutably dereferencing* a component is considered a change ([`DerefMut`](std::ops::DerefMut)). /// Bevy does not compare components to their previous values. /// /// To retain all results without filtering but still check whether they were changed after the /// system last ran, use [`Ref<T>`](crate::change_detection::Ref). /// /// **Note** that this includes changes that happened before the first time this `Query` was run. /// /// # Deferred /// /// Note, that entity modifications issued with [`Commands`](crate::system::Commands) /// (like entity creation or entity component addition or removal) are visible only /// after deferred operations are applied, typically after the system that queued them. /// /// # Time complexity /// /// `Changed` is not [`ArchetypeFilter`], which practically means that /// if query (with `T` component filter) matches million entities, /// `Changed<T>` filter will iterate over all of them even if none of them were changed. /// /// For example, these two systems are roughly equivalent in terms of performance: /// /// ``` /// # use bevy_ecs::change_detection::DetectChanges; /// # use bevy_ecs::entity::Entity; /// # use bevy_ecs::query::Changed; /// # use bevy_ecs::system::Query; /// # use bevy_ecs::world::Ref; /// # use bevy_ecs_macros::Component; /// # #[derive(Component)] /// # struct MyComponent; /// # #[derive(Component)] /// # struct Transform; /// /// fn system1(q: Query<&MyComponent, Changed<Transform>>) { /// for item in &q { /* component changed */ } /// } /// /// fn system2(q: Query<(&MyComponent, Ref<Transform>)>) { /// for item in &q {
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/query/state.rs
crates/bevy_ecs/src/query/state.rs
use crate::{ archetype::{Archetype, ArchetypeGeneration, ArchetypeId}, change_detection::Tick, component::ComponentId, entity::{Entity, EntityEquivalent, EntitySet, UniqueEntityArray}, entity_disabling::DefaultQueryFilters, prelude::FromWorld, query::{FilteredAccess, QueryCombinationIter, QueryIter, QueryParIter, WorldQuery}, storage::{SparseSetIndex, TableId}, system::Query, world::{unsafe_world_cell::UnsafeWorldCell, World, WorldId}, }; #[cfg(all(not(target_arch = "wasm32"), feature = "multi_threaded"))] use crate::entity::UniqueEntityEquivalentSlice; use alloc::vec::Vec; use bevy_utils::prelude::DebugName; use core::{fmt, ptr}; use fixedbitset::FixedBitSet; use log::warn; #[cfg(feature = "trace")] use tracing::Span; use super::{ NopWorldQuery, QueryBuilder, QueryData, QueryEntityError, QueryFilter, QueryManyIter, QueryManyUniqueIter, QuerySingleError, ROQueryItem, ReadOnlyQueryData, }; /// An ID for either a table or an archetype. Used for Query iteration. /// /// Query iteration is exclusively dense (over tables) or archetypal (over archetypes) based on whether /// the query filters are dense or not. This is represented by the [`QueryState::is_dense`] field. /// /// Note that `D::IS_DENSE` and `F::IS_DENSE` have no relationship with `QueryState::is_dense` and /// any combination of their values can happen. /// /// This is a union instead of an enum as the usage is determined at compile time, as all [`StorageId`]s for /// a [`QueryState`] will be all [`TableId`]s or all [`ArchetypeId`]s, and not a mixture of both. This /// removes the need for discriminator to minimize memory usage and branching during iteration, but requires /// a safety invariant be verified when disambiguating them. /// /// # Safety /// Must be initialized and accessed as a [`TableId`], if both generic parameters to the query are dense. /// Must be initialized and accessed as an [`ArchetypeId`] otherwise. #[derive(Clone, Copy)] pub(super) union StorageId { pub(super) table_id: TableId, pub(super) archetype_id: ArchetypeId, } /// Provides scoped access to a [`World`] state according to a given [`QueryData`] and [`QueryFilter`]. /// /// This data is cached between system runs, and is used to: /// - store metadata about which [`Table`] or [`Archetype`] are matched by the query. "Matched" means /// that the query will iterate over the data in the matched table/archetype. /// - cache the [`State`] needed to compute the [`Fetch`] struct used to retrieve data /// from a specific [`Table`] or [`Archetype`] /// - build iterators that can iterate over the query results /// /// [`State`]: crate::query::world_query::WorldQuery::State /// [`Fetch`]: crate::query::world_query::WorldQuery::Fetch /// [`Table`]: crate::storage::Table #[repr(C)] // SAFETY NOTE: // Do not add any new fields that use the `D` or `F` generic parameters as this may // make `QueryState::as_transmuted_state` unsound if not done with care. pub struct QueryState<D: QueryData, F: QueryFilter = ()> { world_id: WorldId, pub(crate) archetype_generation: ArchetypeGeneration, /// Metadata about the [`Table`](crate::storage::Table)s matched by this query. pub(crate) matched_tables: FixedBitSet, /// Metadata about the [`Archetype`]s matched by this query. pub(crate) matched_archetypes: FixedBitSet, /// [`FilteredAccess`] computed by combining the `D` and `F` access. Used to check which other queries /// this query can run in parallel with. /// Note that because we do a zero-cost reference conversion in `Query::as_readonly`, /// the access for a read-only query may include accesses for the original mutable version, /// but the `Query` does not have exclusive access to those components. pub(crate) component_access: FilteredAccess, // NOTE: we maintain both a bitset and a vec because iterating the vec is faster pub(super) matched_storage_ids: Vec<StorageId>, // Represents whether this query iteration is dense or not. When this is true // `matched_storage_ids` stores `TableId`s, otherwise it stores `ArchetypeId`s. pub(super) is_dense: bool, pub(crate) fetch_state: D::State, pub(crate) filter_state: F::State, #[cfg(feature = "trace")] par_iter_span: Span, } impl<D: QueryData, F: QueryFilter> fmt::Debug for QueryState<D, F> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("QueryState") .field("world_id", &self.world_id) .field("matched_table_count", &self.matched_tables.count_ones(..)) .field( "matched_archetype_count", &self.matched_archetypes.count_ones(..), ) .finish_non_exhaustive() } } impl<D: QueryData, F: QueryFilter> FromWorld for QueryState<D, F> { fn from_world(world: &mut World) -> Self { world.query_filtered() } } impl<D: QueryData, F: QueryFilter> QueryState<D, F> { /// Converts this `QueryState` reference to a `QueryState` that does not access anything mutably. pub fn as_readonly(&self) -> &QueryState<D::ReadOnly, F> { // SAFETY: invariant on `WorldQuery` trait upholds that `D::ReadOnly` and `F::ReadOnly` // have a subset of the access, and match the exact same archetypes/tables as `D`/`F` respectively. unsafe { self.as_transmuted_state::<D::ReadOnly, F>() } } /// Converts this `QueryState` reference to a `QueryState` that does not return any data /// which can be faster. /// /// This doesn't use `NopWorldQuery` as it loses filter functionality, for example /// `NopWorldQuery<Changed<T>>` is functionally equivalent to `With<T>`. pub(crate) fn as_nop(&self) -> &QueryState<NopWorldQuery<D>, F> { // SAFETY: `NopWorldQuery` doesn't have any accesses and defers to // `D` for table/archetype matching unsafe { self.as_transmuted_state::<NopWorldQuery<D>, F>() } } /// Converts this `QueryState` reference to any other `QueryState` with /// the same `WorldQuery::State` associated types. /// /// Consider using `as_readonly` or `as_nop` instead which are safe functions. /// /// # Safety /// /// `NewD` must have a subset of the access that `D` does and match the exact same archetypes/tables /// `NewF` must have a subset of the access that `F` does and match the exact same archetypes/tables pub(crate) unsafe fn as_transmuted_state< NewD: ReadOnlyQueryData<State = D::State>, NewF: QueryFilter<State = F::State>, >( &self, ) -> &QueryState<NewD, NewF> { &*ptr::from_ref(self).cast::<QueryState<NewD, NewF>>() } /// Returns the components accessed by this query. pub fn component_access(&self) -> &FilteredAccess { &self.component_access } /// Returns the tables matched by this query. pub fn matched_tables(&self) -> impl Iterator<Item = TableId> + '_ { self.matched_tables.ones().map(TableId::from_usize) } /// Returns the archetypes matched by this query. pub fn matched_archetypes(&self) -> impl Iterator<Item = ArchetypeId> + '_ { self.matched_archetypes.ones().map(ArchetypeId::new) } /// Creates a new [`QueryState`] from a given [`World`] and inherits the result of `world.id()`. pub fn new(world: &mut World) -> Self { let mut state = Self::new_uninitialized(world); state.update_archetypes(world); state } /// Creates a new [`QueryState`] from an immutable [`World`] reference and inherits the result of `world.id()`. /// /// This function may fail if, for example, /// the components that make up this query have not been registered into the world. pub fn try_new(world: &World) -> Option<Self> { let mut state = Self::try_new_uninitialized(world)?; state.update_archetypes(world); Some(state) } /// Creates a new [`QueryState`] but does not populate it with the matched results from the World yet /// /// `new_archetype` and its variants must be called on all of the World's archetypes before the /// state can return valid query results. fn new_uninitialized(world: &mut World) -> Self { let fetch_state = D::init_state(world); let filter_state = F::init_state(world); Self::from_states_uninitialized(world, fetch_state, filter_state) } /// Creates a new [`QueryState`] but does not populate it with the matched results from the World yet /// /// `new_archetype` and its variants must be called on all of the World's archetypes before the /// state can return valid query results. fn try_new_uninitialized(world: &World) -> Option<Self> { let fetch_state = D::get_state(world.components())?; let filter_state = F::get_state(world.components())?; Some(Self::from_states_uninitialized( world, fetch_state, filter_state, )) } /// Creates a new [`QueryState`] but does not populate it with the matched results from the World yet /// /// `new_archetype` and its variants must be called on all of the World's archetypes before the /// state can return valid query results. fn from_states_uninitialized( world: &World, fetch_state: <D as WorldQuery>::State, filter_state: <F as WorldQuery>::State, ) -> Self { let mut component_access = FilteredAccess::default(); D::update_component_access(&fetch_state, &mut component_access); // Use a temporary empty FilteredAccess for filters. This prevents them from conflicting with the // main Query's `fetch_state` access. Filters are allowed to conflict with the main query fetch // because they are evaluated *before* a specific reference is constructed. let mut filter_component_access = FilteredAccess::default(); F::update_component_access(&filter_state, &mut filter_component_access); // Merge the temporary filter access with the main access. This ensures that filter access is // properly considered in a global "cross-query" context (both within systems and across systems). component_access.extend(&filter_component_access); // For queries without dynamic filters the dense-ness of the query is equal to the dense-ness // of its static type parameters. let mut is_dense = D::IS_DENSE && F::IS_DENSE; if let Some(default_filters) = world.get_resource::<DefaultQueryFilters>() { default_filters.modify_access(&mut component_access); is_dense &= default_filters.is_dense(world.components()); } Self { world_id: world.id(), archetype_generation: ArchetypeGeneration::initial(), matched_storage_ids: Vec::new(), is_dense, fetch_state, filter_state, component_access, matched_tables: Default::default(), matched_archetypes: Default::default(), #[cfg(feature = "trace")] par_iter_span: tracing::info_span!( "par_for_each", query = core::any::type_name::<D>(), filter = core::any::type_name::<F>(), ), } } /// Creates a new [`QueryState`] from a given [`QueryBuilder`] and inherits its [`FilteredAccess`]. pub fn from_builder(builder: &mut QueryBuilder<D, F>) -> Self { let mut fetch_state = D::init_state(builder.world_mut()); let filter_state = F::init_state(builder.world_mut()); let mut component_access = FilteredAccess::default(); D::update_component_access(&fetch_state, &mut component_access); D::provide_extra_access( &mut fetch_state, component_access.access_mut(), builder.access().access(), ); let mut component_access = builder.access().clone(); // For dynamic queries the dense-ness is given by the query builder. let mut is_dense = builder.is_dense(); if let Some(default_filters) = builder.world().get_resource::<DefaultQueryFilters>() { default_filters.modify_access(&mut component_access); is_dense &= default_filters.is_dense(builder.world().components()); } let mut state = Self { world_id: builder.world().id(), archetype_generation: ArchetypeGeneration::initial(), matched_storage_ids: Vec::new(), is_dense, fetch_state, filter_state, component_access, matched_tables: Default::default(), matched_archetypes: Default::default(), #[cfg(feature = "trace")] par_iter_span: tracing::info_span!( "par_for_each", data = core::any::type_name::<D>(), filter = core::any::type_name::<F>(), ), }; state.update_archetypes(builder.world()); state } /// Creates a [`Query`] from the given [`QueryState`] and [`World`]. /// /// This will create read-only queries, see [`Self::query_mut`] for mutable queries. pub fn query<'w, 's>(&'s mut self, world: &'w World) -> Query<'w, 's, D::ReadOnly, F> { self.update_archetypes(world); self.query_manual(world) } /// Creates a [`Query`] from the given [`QueryState`] and [`World`]. /// /// This method is slightly more efficient than [`QueryState::query`] in some situations, since /// it does not update this instance's internal cache. The resulting query may skip an entity that /// belongs to an archetype that has not been cached. /// /// To ensure that the cache is up to date, call [`QueryState::update_archetypes`] before this method. /// The cache is also updated in [`QueryState::new`], [`QueryState::get`], or any method with mutable /// access to `self`. /// /// This will create read-only queries, see [`Self::query_mut`] for mutable queries. pub fn query_manual<'w, 's>(&'s self, world: &'w World) -> Query<'w, 's, D::ReadOnly, F> { self.validate_world(world.id()); // SAFETY: // - We have read access to the entire world, and we call `as_readonly()` so the query only performs read access. // - We called `validate_world`. unsafe { self.as_readonly() .query_unchecked_manual(world.as_unsafe_world_cell_readonly()) } } /// Creates a [`Query`] from the given [`QueryState`] and [`World`]. pub fn query_mut<'w, 's>(&'s mut self, world: &'w mut World) -> Query<'w, 's, D, F> { let last_run = world.last_change_tick(); let this_run = world.change_tick(); // SAFETY: We have exclusive access to the entire world. unsafe { self.query_unchecked_with_ticks(world.as_unsafe_world_cell(), last_run, this_run) } } /// Creates a [`Query`] from the given [`QueryState`] and [`World`]. /// /// # Safety /// /// This does not check for mutable query correctness. To be safe, make sure mutable queries /// have unique access to the components they query. pub unsafe fn query_unchecked<'w, 's>( &'s mut self, world: UnsafeWorldCell<'w>, ) -> Query<'w, 's, D, F> { self.update_archetypes_unsafe_world_cell(world); // SAFETY: Caller ensures we have the required access unsafe { self.query_unchecked_manual(world) } } /// Creates a [`Query`] from the given [`QueryState`] and [`World`]. /// /// This method is slightly more efficient than [`QueryState::query_unchecked`] in some situations, since /// it does not update this instance's internal cache. The resulting query may skip an entity that /// belongs to an archetype that has not been cached. /// /// To ensure that the cache is up to date, call [`QueryState::update_archetypes`] before this method. /// The cache is also updated in [`QueryState::new`], [`QueryState::get`], or any method with mutable /// access to `self`. /// /// # Safety /// /// This does not check for mutable query correctness. To be safe, make sure mutable queries /// have unique access to the components they query. /// This does not validate that `world.id()` matches `self.world_id`. Calling this on a `world` /// with a mismatched [`WorldId`] is unsound. pub unsafe fn query_unchecked_manual<'w, 's>( &'s self, world: UnsafeWorldCell<'w>, ) -> Query<'w, 's, D, F> { let last_run = world.last_change_tick(); let this_run = world.change_tick(); // SAFETY: // - The caller ensured we have the correct access to the world. // - The caller ensured that the world matches. unsafe { self.query_unchecked_manual_with_ticks(world, last_run, this_run) } } /// Creates a [`Query`] from the given [`QueryState`] and [`World`]. /// /// # Safety /// /// This does not check for mutable query correctness. To be safe, make sure mutable queries /// have unique access to the components they query. pub unsafe fn query_unchecked_with_ticks<'w, 's>( &'s mut self, world: UnsafeWorldCell<'w>, last_run: Tick, this_run: Tick, ) -> Query<'w, 's, D, F> { self.update_archetypes_unsafe_world_cell(world); // SAFETY: // - The caller ensured we have the correct access to the world. // - We called `update_archetypes_unsafe_world_cell`, which calls `validate_world`. unsafe { self.query_unchecked_manual_with_ticks(world, last_run, this_run) } } /// Creates a [`Query`] from the given [`QueryState`] and [`World`]. /// /// This method is slightly more efficient than [`QueryState::query_unchecked_with_ticks`] in some situations, since /// it does not update this instance's internal cache. The resulting query may skip an entity that /// belongs to an archetype that has not been cached. /// /// To ensure that the cache is up to date, call [`QueryState::update_archetypes`] before this method. /// The cache is also updated in [`QueryState::new`], [`QueryState::get`], or any method with mutable /// access to `self`. /// /// # Safety /// /// This does not check for mutable query correctness. To be safe, make sure mutable queries /// have unique access to the components they query. /// This does not validate that `world.id()` matches `self.world_id`. Calling this on a `world` /// with a mismatched [`WorldId`] is unsound. pub unsafe fn query_unchecked_manual_with_ticks<'w, 's>( &'s self, world: UnsafeWorldCell<'w>, last_run: Tick, this_run: Tick, ) -> Query<'w, 's, D, F> { // SAFETY: // - The caller ensured we have the correct access to the world. // - The caller ensured that the world matches. unsafe { Query::new(world, self, last_run, this_run) } } /// Checks if the query is empty for the given [`World`], where the last change and current tick are given. /// /// This is equivalent to `self.iter().next().is_none()`, and thus the worst case runtime will be `O(n)` /// where `n` is the number of *potential* matches. This can be notably expensive for queries that rely /// on non-archetypal filters such as [`Added`], [`Changed`] or [`Spawned`] which must individually check /// each query result for a match. /// /// # Panics /// /// If `world` does not match the one used to call `QueryState::new` for this instance. /// /// [`Added`]: crate::query::Added /// [`Changed`]: crate::query::Changed /// [`Spawned`]: crate::query::Spawned #[inline] pub fn is_empty(&self, world: &World, last_run: Tick, this_run: Tick) -> bool { self.validate_world(world.id()); // SAFETY: // - We have read access to the entire world, and `is_empty()` only performs read access. // - We called `validate_world`. unsafe { self.query_unchecked_manual_with_ticks( world.as_unsafe_world_cell_readonly(), last_run, this_run, ) } .is_empty() } /// Returns `true` if the given [`Entity`] matches the query. /// /// This is always guaranteed to run in `O(1)` time. #[inline] pub fn contains(&self, entity: Entity, world: &World, last_run: Tick, this_run: Tick) -> bool { self.validate_world(world.id()); // SAFETY: // - We have read access to the entire world, and `is_empty()` only performs read access. // - We called `validate_world`. unsafe { self.query_unchecked_manual_with_ticks( world.as_unsafe_world_cell_readonly(), last_run, this_run, ) } .contains(entity) } /// Updates the state's internal view of the [`World`]'s archetypes. If this is not called before querying data, /// the results may not accurately reflect what is in the `world`. /// /// This is only required if a `manual` method (such as [`Self::get_manual`]) is being called, and it only needs to /// be called if the `world` has been structurally mutated (i.e. added/removed a component or resource). Users using /// non-`manual` methods such as [`QueryState::get`] do not need to call this as it will be automatically called for them. /// /// If you have an [`UnsafeWorldCell`] instead of `&World`, consider using [`QueryState::update_archetypes_unsafe_world_cell`]. /// /// # Panics /// /// If `world` does not match the one used to call `QueryState::new` for this instance. #[inline] pub fn update_archetypes(&mut self, world: &World) { self.update_archetypes_unsafe_world_cell(world.as_unsafe_world_cell_readonly()); } /// Updates the state's internal view of the `world`'s archetypes. If this is not called before querying data, /// the results may not accurately reflect what is in the `world`. /// /// This is only required if a `manual` method (such as [`Self::get_manual`]) is being called, and it only needs to /// be called if the `world` has been structurally mutated (i.e. added/removed a component or resource). Users using /// non-`manual` methods such as [`QueryState::get`] do not need to call this as it will be automatically called for them. /// /// # Note /// /// This method only accesses world metadata. /// /// # Panics /// /// If `world` does not match the one used to call `QueryState::new` for this instance. pub fn update_archetypes_unsafe_world_cell(&mut self, world: UnsafeWorldCell) { self.validate_world(world.id()); if self.component_access.required.is_empty() { let archetypes = world.archetypes(); let old_generation = core::mem::replace(&mut self.archetype_generation, archetypes.generation()); for archetype in &archetypes[old_generation..] { // SAFETY: The validate_world call ensures that the world is the same the QueryState // was initialized from. unsafe { self.new_archetype(archetype); } } } else { // skip if we are already up to date if self.archetype_generation == world.archetypes().generation() { return; } // if there are required components, we can optimize by only iterating through archetypes // that contain at least one of the required components let potential_archetypes = self .component_access .required .ones() .filter_map(|idx| { let component_id = ComponentId::get_sparse_set_index(idx); world .archetypes() .component_index() .get(&component_id) .map(|index| index.keys()) }) // select the component with the fewest archetypes .min_by_key(ExactSizeIterator::len); if let Some(archetypes) = potential_archetypes { for archetype_id in archetypes { // exclude archetypes that have already been processed if archetype_id < &self.archetype_generation.0 { continue; } // SAFETY: get_potential_archetypes only returns archetype ids that are valid for the world let archetype = &world.archetypes()[*archetype_id]; // SAFETY: The validate_world call ensures that the world is the same the QueryState // was initialized from. unsafe { self.new_archetype(archetype); } } } self.archetype_generation = world.archetypes().generation(); } } /// # Panics /// /// If `world_id` does not match the [`World`] used to call `QueryState::new` for this instance. /// /// Many unsafe query methods require the world to match for soundness. This function is the easiest /// way of ensuring that it matches. #[inline] #[track_caller] pub fn validate_world(&self, world_id: WorldId) { #[inline(never)] #[track_caller] #[cold] fn panic_mismatched(this: WorldId, other: WorldId) -> ! { panic!("Encountered a mismatched World. This QueryState was created from {this:?}, but a method was called using {other:?}."); } if self.world_id != world_id { panic_mismatched(self.world_id, world_id); } } /// Update the current [`QueryState`] with information from the provided [`Archetype`] /// (if applicable, i.e. if the archetype has any intersecting [`ComponentId`] with the current [`QueryState`]). /// /// # Safety /// `archetype` must be from the `World` this state was initialized from. pub unsafe fn new_archetype(&mut self, archetype: &Archetype) { if D::matches_component_set(&self.fetch_state, &|id| archetype.contains(id)) && F::matches_component_set(&self.filter_state, &|id| archetype.contains(id)) && self.matches_component_set(&|id| archetype.contains(id)) { let archetype_index = archetype.id().index(); if !self.matched_archetypes.contains(archetype_index) { self.matched_archetypes.grow_and_insert(archetype_index); if !self.is_dense { self.matched_storage_ids.push(StorageId { archetype_id: archetype.id(), }); } } let table_index = archetype.table_id().as_usize(); if !self.matched_tables.contains(table_index) { self.matched_tables.grow_and_insert(table_index); if self.is_dense { self.matched_storage_ids.push(StorageId { table_id: archetype.table_id(), }); } } } } /// Returns `true` if this query matches a set of components. Otherwise, returns `false`. pub fn matches_component_set(&self, set_contains_id: &impl Fn(ComponentId) -> bool) -> bool { self.component_access.filter_sets.iter().any(|set| { set.with .ones() .all(|index| set_contains_id(ComponentId::get_sparse_set_index(index))) && set .without .ones() .all(|index| !set_contains_id(ComponentId::get_sparse_set_index(index))) }) } /// Use this to transform a [`QueryState`] into a more generic [`QueryState`]. /// This can be useful for passing to another function that might take the more general form. /// See [`Query::transmute_lens`](crate::system::Query::transmute_lens) for more details. /// /// You should not call [`update_archetypes`](Self::update_archetypes) on the returned [`QueryState`] as the result will be unpredictable. /// You might end up with a mix of archetypes that only matched the original query + archetypes that only match /// the new [`QueryState`]. Most of the safe methods on [`QueryState`] call [`QueryState::update_archetypes`] internally, so this /// best used through a [`Query`] pub fn transmute<'a, NewD: QueryData>( &self, world: impl Into<UnsafeWorldCell<'a>>, ) -> QueryState<NewD> { self.transmute_filtered::<NewD, ()>(world.into()) } /// Creates a new [`QueryState`] with the same underlying [`FilteredAccess`], matched tables and archetypes /// as self but with a new type signature. /// /// Panics if `NewD` or `NewF` require accesses that this query does not have. pub fn transmute_filtered<'a, NewD: QueryData, NewF: QueryFilter>( &self, world: impl Into<UnsafeWorldCell<'a>>, ) -> QueryState<NewD, NewF> { let world = world.into(); self.validate_world(world.id()); let mut component_access = FilteredAccess::default(); let mut fetch_state = NewD::get_state(world.components()).expect("Could not create fetch_state, Please initialize all referenced components before transmuting."); let filter_state = NewF::get_state(world.components()).expect("Could not create filter_state, Please initialize all referenced components before transmuting."); let mut self_access = self.component_access.clone(); if D::IS_READ_ONLY { // The current state was transmuted from a mutable // `QueryData` to a read-only one. // Ignore any write access in the current state. self_access.access_mut().clear_writes(); } NewD::update_component_access(&fetch_state, &mut component_access); NewD::provide_extra_access( &mut fetch_state, component_access.access_mut(), self_access.access(), ); let mut filter_component_access = FilteredAccess::default(); NewF::update_component_access(&filter_state, &mut filter_component_access); component_access.extend(&filter_component_access); assert!( component_access.is_subset(&self_access), "Transmuted state for {} attempts to access terms that are not allowed by original state {}.", DebugName::type_name::<(NewD, NewF)>(), DebugName::type_name::<(D, F)>() ); // For transmuted queries, the dense-ness of the query is equal to the dense-ness of the original query. // // We ensure soundness using `FilteredAccess::required`. // // Any `WorldQuery` implementations that rely on a query being sparse for soundness, // including `&`, `&mut`, `Ref`, and `Mut`, will add a sparse set component to the `required` set. // (`Option<&Sparse>` and `Has<Sparse>` will incorrectly report a component as never being present // when doing dense iteration, but are not unsound. See https://github.com/bevyengine/bevy/issues/16397) // // And any query with a sparse set component in the `required` set must have `is_dense = false`. // For static queries, the `WorldQuery` implementations ensure this. // For dynamic queries, anything that adds a `required` component also adds a `with` filter. // // The `component_access.is_subset()` check ensures that if the new query has a sparse set component in the `required` set, // then the original query must also have had that component in the `required` set. // Therefore, if the `WorldQuery` implementations rely on a query being sparse for soundness, // then there was a sparse set component in the `required` set, and the query has `is_dense = false`. let is_dense = self.is_dense; QueryState { world_id: self.world_id, archetype_generation: self.archetype_generation, matched_storage_ids: self.matched_storage_ids.clone(), is_dense, fetch_state, filter_state, component_access: self_access, matched_tables: self.matched_tables.clone(),
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/query/error.rs
crates/bevy_ecs/src/query/error.rs
use bevy_utils::prelude::DebugName; use crate::{ archetype::ArchetypeId, entity::{Entity, EntityNotSpawnedError}, }; /// An error that occurs when retrieving a specific [`Entity`]'s query result from [`Query`](crate::system::Query) or [`QueryState`](crate::query::QueryState). // TODO: return the type_name as part of this error #[derive(thiserror::Error, Clone, Copy, Debug, PartialEq, Eq)] pub enum QueryEntityError { /// The given [`Entity`]'s components do not match the query. /// /// Either it does not have a requested component, or it has a component which the query filters out. #[error("The query does not match entity {0}")] QueryDoesNotMatch(Entity, ArchetypeId), /// The given [`Entity`] is not spawned. #[error("{0}")] NotSpawned(#[from] EntityNotSpawnedError), /// The [`Entity`] was requested mutably more than once. /// /// See [`Query::get_many_mut`](crate::system::Query::get_many_mut) for an example. #[error("The entity with ID {0} was requested mutably more than once")] AliasedMutability(Entity), } /// An error that occurs when evaluating a [`Query`](crate::system::Query) or [`QueryState`](crate::query::QueryState) as a single expected result via /// [`single`](crate::system::Query::single) or [`single_mut`](crate::system::Query::single_mut). #[derive(Debug, thiserror::Error)] pub enum QuerySingleError { /// No entity fits the query. #[error("No entities fit the query {0}")] NoEntities(DebugName), /// Multiple entities fit the query. #[error("Multiple entities fit the query {0}")] MultipleEntities(DebugName), } #[cfg(test)] mod test { use crate::{prelude::World, query::QueryEntityError}; use bevy_ecs_macros::Component; #[test] fn query_does_not_match() { let mut world = World::new(); #[derive(Component)] struct Present1; #[derive(Component)] struct Present2; #[derive(Component, Debug, PartialEq)] struct NotPresent; let entity = world.spawn((Present1, Present2)); let (entity, archetype_id) = (entity.id(), entity.archetype().id()); let result = world.query::<&NotPresent>().get(&world, entity); assert_eq!( result, Err(QueryEntityError::QueryDoesNotMatch(entity, archetype_id)) ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/query/fetch.rs
crates/bevy_ecs/src/query/fetch.rs
use crate::{ archetype::{Archetype, Archetypes}, bundle::Bundle, change_detection::{ComponentTicksMut, ComponentTicksRef, MaybeLocation, Tick}, component::{Component, ComponentId, Components, Mutable, StorageType}, entity::{Entities, Entity, EntityLocation}, query::{ access_iter::{EcsAccessLevel, EcsAccessType}, Access, DebugCheckedUnwrap, FilteredAccess, WorldQuery, }, storage::{ComponentSparseSet, Table, TableRow}, world::{ unsafe_world_cell::UnsafeWorldCell, EntityMut, EntityMutExcept, EntityRef, EntityRefExcept, FilteredEntityMut, FilteredEntityRef, Mut, Ref, World, }, }; use bevy_ptr::{ThinSlicePtr, UnsafeCellDeref}; use bevy_utils::prelude::DebugName; use core::{cell::UnsafeCell, iter, marker::PhantomData, panic::Location}; use variadics_please::all_tuples; /// Types that can be fetched from a [`World`] using a [`Query`]. /// /// There are many types that natively implement this trait: /// /// - **Component references. (&T and &mut T)** /// Fetches a component by reference (immutably or mutably). /// - **`QueryData` tuples.** /// If every element of a tuple implements `QueryData`, then the tuple itself also implements the same trait. /// This enables a single `Query` to access multiple components. /// Due to the current lack of variadic generics in Rust, the trait has been implemented for tuples from 0 to 15 elements, /// but nesting of tuples allows infinite `WorldQuery`s. /// - **[`Entity`].** /// Gets the identifier of the queried entity. /// - **[`EntityLocation`].** /// Gets the location metadata of the queried entity. /// - **[`SpawnDetails`].** /// Gets the tick the entity was spawned at. /// - **[`EntityRef`].** /// Read-only access to arbitrary components on the queried entity. /// - **[`EntityMut`].** /// Mutable access to arbitrary components on the queried entity. /// - **[`&Archetype`](Archetype).** /// Read-only access to the archetype-level metadata of the queried entity. /// - **[`Option`].** /// By default, a world query only tests entities that have the matching component types. /// Wrapping it into an `Option` will increase the query search space, and it will return `None` if an entity doesn't satisfy the `WorldQuery`. /// - **[`AnyOf`].** /// Equivalent to wrapping each world query inside it into an `Option`. /// - **[`Ref`].** /// Similar to change detection filters but it is used as a query fetch parameter. /// It exposes methods to check for changes to the wrapped component. /// - **[`Mut`].** /// Mutable component access, with change detection data. /// - **[`Has`].** /// Returns a bool indicating whether the entity has the specified component. /// /// Implementing the trait manually can allow for a fundamentally new type of behavior. /// /// # Trait derivation /// /// Query design can be easily structured by deriving `QueryData` for custom types. /// Despite the added complexity, this approach has several advantages over using `QueryData` tuples. /// The most relevant improvements are: /// /// - Reusability across multiple systems. /// - There is no need to destructure a tuple since all fields are named. /// - Subqueries can be composed together to create a more complex query. /// - Methods can be implemented for the query items. /// - There is no hardcoded limit on the number of elements. /// /// This trait can only be derived for structs, if each field also implements `QueryData`. /// /// ``` /// # use bevy_ecs::prelude::*; /// use bevy_ecs::query::QueryData; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # #[derive(Component)] /// # struct ComponentB; /// /// #[derive(QueryData)] /// struct MyQuery { /// entity: Entity, /// // It is required that all reference lifetimes are explicitly annotated, just like in any /// // struct. Each lifetime should be 'static. /// component_a: &'static ComponentA, /// component_b: &'static ComponentB, /// } /// /// fn my_system(query: Query<MyQuery>) { /// for q in &query { /// q.component_a; /// } /// } /// # bevy_ecs::system::assert_is_system(my_system); /// ``` /// /// ## Macro expansion /// /// Expanding the macro will declare one or three additional structs, depending on whether or not the struct is marked as mutable. /// For a struct named `X`, the additional structs will be: /// /// |Struct name|`mutable` only|Description| /// |:---:|:---:|---| /// |`XItem`|---|The type of the query item for `X`| /// |`XReadOnlyItem`|✓|The type of the query item for `XReadOnly`| /// |`XReadOnly`|✓|[`ReadOnly`] variant of `X`| /// /// ## Adding mutable references /// /// Simply adding mutable references to a derived `QueryData` will result in a compilation error: /// /// ```compile_fail /// # use bevy_ecs::prelude::*; /// # use bevy_ecs::query::QueryData; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # /// #[derive(QueryData)] /// struct CustomQuery { /// component_a: &'static mut ComponentA, /// } /// ``` /// /// To grant mutable access to components, the struct must be marked with the `#[query_data(mutable)]` attribute. /// This will also create three more structs that will be used for accessing the query immutably (see table above). /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_ecs::query::QueryData; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # /// #[derive(QueryData)] /// #[query_data(mutable)] /// struct CustomQuery { /// component_a: &'static mut ComponentA, /// } /// ``` /// /// ## Adding methods to query items /// /// It is possible to add methods to query items in order to write reusable logic about related components. /// This will often make systems more readable because low level logic is moved out from them. /// It is done by adding `impl` blocks with methods for the `-Item` or `-ReadOnlyItem` generated structs. /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_ecs::query::QueryData; /// # /// #[derive(Component)] /// struct Health(f32); /// /// #[derive(Component)] /// struct Buff(f32); /// /// #[derive(QueryData)] /// #[query_data(mutable)] /// struct HealthQuery { /// health: &'static mut Health, /// buff: Option<&'static mut Buff>, /// } /// /// // `HealthQueryItem` is only available when accessing the query with mutable methods. /// impl<'w, 's> HealthQueryItem<'w, 's> { /// fn damage(&mut self, value: f32) { /// self.health.0 -= value; /// } /// /// fn total(&self) -> f32 { /// self.health.0 + self.buff.as_deref().map_or(0.0, |Buff(buff)| *buff) /// } /// } /// /// // `HealthQueryReadOnlyItem` is only available when accessing the query with immutable methods. /// impl<'w, 's> HealthQueryReadOnlyItem<'w, 's> { /// fn total(&self) -> f32 { /// self.health.0 + self.buff.map_or(0.0, |Buff(buff)| *buff) /// } /// } /// /// fn my_system(mut health_query: Query<HealthQuery>) { /// // The item returned by the iterator is of type `HealthQueryReadOnlyItem`. /// for health in health_query.iter() { /// println!("Total: {}", health.total()); /// } /// // The item returned by the iterator is of type `HealthQueryItem`. /// for mut health in &mut health_query { /// health.damage(1.0); /// println!("Total (mut): {}", health.total()); /// } /// } /// # bevy_ecs::system::assert_is_system(my_system); /// ``` /// /// ## Deriving traits for query items /// /// The `QueryData` derive macro does not automatically implement the traits of the struct to the query item types. /// Something similar can be done by using the `#[query_data(derive(...))]` attribute. /// This will apply the listed derivable traits to the query item structs. /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_ecs::query::QueryData; /// # /// # #[derive(Component, Debug)] /// # struct ComponentA; /// # /// #[derive(QueryData)] /// #[query_data(mutable, derive(Debug))] /// struct CustomQuery { /// component_a: &'static ComponentA, /// } /// /// // This function statically checks that `T` implements `Debug`. /// fn assert_debug<T: std::fmt::Debug>() {} /// /// assert_debug::<CustomQueryItem>(); /// assert_debug::<CustomQueryReadOnlyItem>(); /// ``` /// /// ## Query composition /// /// It is possible to use any `QueryData` as a field of another one. /// This means that a `QueryData` can also be used as a subquery, potentially in multiple places. /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_ecs::query::QueryData; /// # /// # #[derive(Component)] /// # struct ComponentA; /// # #[derive(Component)] /// # struct ComponentB; /// # #[derive(Component)] /// # struct ComponentC; /// # /// #[derive(QueryData)] /// struct SubQuery { /// component_a: &'static ComponentA, /// component_b: &'static ComponentB, /// } /// /// #[derive(QueryData)] /// struct MyQuery { /// subquery: SubQuery, /// component_c: &'static ComponentC, /// } /// ``` /// /// # Generic Queries /// /// When writing generic code, it is often necessary to use [`PhantomData`] /// to constrain type parameters. Since `QueryData` is implemented for all /// `PhantomData<T>` types, this pattern can be used with this macro. /// /// ``` /// # use bevy_ecs::{prelude::*, query::QueryData}; /// # use std::marker::PhantomData; /// #[derive(QueryData)] /// pub struct GenericQuery<T> { /// id: Entity, /// marker: PhantomData<T>, /// } /// # fn my_system(q: Query<GenericQuery<()>>) {} /// # bevy_ecs::system::assert_is_system(my_system); /// ``` /// /// # Safety /// /// - Component access of `Self::ReadOnly` must be a subset of `Self` /// and `Self::ReadOnly` must match exactly the same archetypes/tables as `Self` /// - `IS_READ_ONLY` must be `true` if and only if `Self: ReadOnlyQueryData` /// /// [`Query`]: crate::system::Query /// [`ReadOnly`]: Self::ReadOnly #[diagnostic::on_unimplemented( message = "`{Self}` is not valid to request as data in a `Query`", label = "invalid `Query` data", note = "if `{Self}` is a component type, try using `&{Self}` or `&mut {Self}`" )] pub unsafe trait QueryData: WorldQuery { /// True if this query is read-only and may not perform mutable access. const IS_READ_ONLY: bool; /// Returns true if (and only if) this query data relies strictly on archetypes to limit which /// entities are accessed by the Query. /// /// This enables optimizations for [`QueryIter`](`crate::query::QueryIter`) that rely on knowing exactly how /// many elements are being iterated (such as `Iterator::collect()`). /// /// If this is `true`, then [`QueryData::fetch`] must always return `Some`. const IS_ARCHETYPAL: bool; /// The read-only variant of this [`QueryData`], which satisfies the [`ReadOnlyQueryData`] trait. type ReadOnly: ReadOnlyQueryData<State = <Self as WorldQuery>::State>; /// The item returned by this [`WorldQuery`] /// This will be the data retrieved by the query, /// and is visible to the end user when calling e.g. `Query<Self>::get`. type Item<'w, 's>; /// This function manually implements subtyping for the query items. fn shrink<'wlong: 'wshort, 'wshort, 's>( item: Self::Item<'wlong, 's>, ) -> Self::Item<'wshort, 's>; /// Offers additional access above what we requested in `update_component_access`. /// Implementations may add additional access that is a subset of `available_access` /// and does not conflict with anything in `access`, /// and must update `access` to include that access. /// /// This is used by [`WorldQuery`] types like [`FilteredEntityRef`] /// and [`FilteredEntityMut`] to support dynamic access. /// /// Called when constructing a [`QueryLens`](crate::system::QueryLens) or calling [`QueryState::from_builder`](super::QueryState::from_builder) fn provide_extra_access( _state: &mut Self::State, _access: &mut Access, _available_access: &Access, ) { } /// Fetch [`Self::Item`](`QueryData::Item`) for either the given `entity` in the current [`Table`], /// or for the given `entity` in the current [`Archetype`]. This must always be called after /// [`WorldQuery::set_table`] with a `table_row` in the range of the current [`Table`] or after /// [`WorldQuery::set_archetype`] with an `entity` in the current archetype. /// Accesses components registered in [`WorldQuery::update_component_access`]. /// /// This method returns `None` if the entity does not match the query. /// If `Self` implements [`ArchetypeQueryData`], this must always return `Some`. /// /// # Safety /// /// - Must always be called _after_ [`WorldQuery::set_table`] or [`WorldQuery::set_archetype`]. `entity` and /// `table_row` must be in the range of the current table and archetype. /// - There must not be simultaneous conflicting component access registered in `update_component_access`. unsafe fn fetch<'w, 's>( state: &'s Self::State, fetch: &mut Self::Fetch<'w>, entity: Entity, table_row: TableRow, ) -> Option<Self::Item<'w, 's>>; /// Returns an iterator over the access needed by [`QueryData::fetch`]. Access conflicts are usually /// checked in [`WorldQuery::update_component_access`], but in certain cases this method can be useful to implement /// a way of checking for access conflicts in a non-allocating way. fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>>; } /// A [`QueryData`] that is read only. /// /// # Safety /// /// This must only be implemented for read-only [`QueryData`]'s. pub unsafe trait ReadOnlyQueryData: QueryData<ReadOnly = Self> {} /// The item type returned when a [`WorldQuery`] is iterated over pub type QueryItem<'w, 's, Q> = <Q as QueryData>::Item<'w, 's>; /// The read-only variant of the item type returned when a [`QueryData`] is iterated over immutably pub type ROQueryItem<'w, 's, D> = QueryItem<'w, 's, <D as QueryData>::ReadOnly>; /// A [`QueryData`] that does not borrow from its [`QueryState`](crate::query::QueryState). /// /// This is implemented by most `QueryData` types. /// The main exceptions are [`FilteredEntityRef`], [`FilteredEntityMut`], [`EntityRefExcept`], and [`EntityMutExcept`], /// which borrow an access list from their query state. /// Consider using a full [`EntityRef`] or [`EntityMut`] if you would need those. pub trait ReleaseStateQueryData: QueryData { /// Releases the borrow from the query state by converting an item to have a `'static` state lifetime. fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static>; } /// A marker trait to indicate that the query data filters at an archetype level. /// /// This is needed to implement [`ExactSizeIterator`] for /// [`QueryIter`](crate::query::QueryIter) that contains archetype-level filters. /// /// The trait must only be implemented for query data where its corresponding [`QueryData::IS_ARCHETYPAL`] is [`prim@true`]. pub trait ArchetypeQueryData: QueryData {} /// SAFETY: /// `update_component_access` does nothing. /// This is sound because `fetch` does not access components. unsafe impl WorldQuery for Entity { type Fetch<'w> = (); type State = (); fn shrink_fetch<'wlong: 'wshort, 'wshort>(_: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {} unsafe fn init_fetch<'w, 's>( _world: UnsafeWorldCell<'w>, _state: &'s Self::State, _last_run: Tick, _this_run: Tick, ) -> Self::Fetch<'w> { } const IS_DENSE: bool = true; #[inline] unsafe fn set_archetype<'w, 's>( _fetch: &mut Self::Fetch<'w>, _state: &'s Self::State, _archetype: &'w Archetype, _table: &Table, ) { } #[inline] unsafe fn set_table<'w, 's>( _fetch: &mut Self::Fetch<'w>, _state: &'s Self::State, _table: &'w Table, ) { } fn update_component_access(_state: &Self::State, _access: &mut FilteredAccess) {} fn init_state(_world: &mut World) {} fn get_state(_components: &Components) -> Option<()> { Some(()) } fn matches_component_set( _state: &Self::State, _set_contains_id: &impl Fn(ComponentId) -> bool, ) -> bool { true } } /// SAFETY: `Self` is the same as `Self::ReadOnly` unsafe impl QueryData for Entity { const IS_READ_ONLY: bool = true; const IS_ARCHETYPAL: bool = true; type ReadOnly = Self; type Item<'w, 's> = Entity; fn shrink<'wlong: 'wshort, 'wshort, 's>( item: Self::Item<'wlong, 's>, ) -> Self::Item<'wshort, 's> { item } #[inline(always)] unsafe fn fetch<'w, 's>( _state: &'s Self::State, _fetch: &mut Self::Fetch<'w>, entity: Entity, _table_row: TableRow, ) -> Option<Self::Item<'w, 's>> { Some(entity) } fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> { iter::empty() } } /// SAFETY: access is read only unsafe impl ReadOnlyQueryData for Entity {} impl ReleaseStateQueryData for Entity { fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> { item } } impl ArchetypeQueryData for Entity {} /// SAFETY: /// `update_component_access` does nothing. /// This is sound because `fetch` does not access components. unsafe impl WorldQuery for EntityLocation { type Fetch<'w> = &'w Entities; type State = (); fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> { fetch } unsafe fn init_fetch<'w, 's>( world: UnsafeWorldCell<'w>, _state: &'s Self::State, _last_run: Tick, _this_run: Tick, ) -> Self::Fetch<'w> { world.entities() } // This is set to true to avoid forcing archetypal iteration in compound queries, is likely to be slower // in most practical use case. const IS_DENSE: bool = true; #[inline] unsafe fn set_archetype<'w, 's>( _fetch: &mut Self::Fetch<'w>, _state: &'s Self::State, _archetype: &'w Archetype, _table: &Table, ) { } #[inline] unsafe fn set_table<'w, 's>( _fetch: &mut Self::Fetch<'w>, _state: &'s Self::State, _table: &'w Table, ) { } fn update_component_access(_state: &Self::State, _access: &mut FilteredAccess) {} fn init_state(_world: &mut World) {} fn get_state(_components: &Components) -> Option<()> { Some(()) } fn matches_component_set( _state: &Self::State, _set_contains_id: &impl Fn(ComponentId) -> bool, ) -> bool { true } } /// SAFETY: `Self` is the same as `Self::ReadOnly` unsafe impl QueryData for EntityLocation { const IS_READ_ONLY: bool = true; const IS_ARCHETYPAL: bool = true; type ReadOnly = Self; type Item<'w, 's> = EntityLocation; fn shrink<'wlong: 'wshort, 'wshort, 's>( item: Self::Item<'wlong, 's>, ) -> Self::Item<'wshort, 's> { item } #[inline(always)] unsafe fn fetch<'w, 's>( _state: &'s Self::State, fetch: &mut Self::Fetch<'w>, entity: Entity, _table_row: TableRow, ) -> Option<Self::Item<'w, 's>> { // SAFETY: `fetch` must be called with an entity that exists in the world Some(unsafe { fetch.get_spawned(entity).debug_checked_unwrap() }) } fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> { iter::empty() } } /// SAFETY: access is read only unsafe impl ReadOnlyQueryData for EntityLocation {} impl ReleaseStateQueryData for EntityLocation { fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> { item } } impl ArchetypeQueryData for EntityLocation {} /// The `SpawnDetails` query parameter fetches the [`Tick`] the entity was spawned at. /// /// To evaluate whether the spawn happened since the last time the system ran, the system /// param [`SystemChangeTick`](bevy_ecs::system::SystemChangeTick) needs to be used. /// /// If the query should filter for spawned entities instead, use the /// [`Spawned`](bevy_ecs::query::Spawned) query filter instead. /// /// # Examples /// /// ``` /// # use bevy_ecs::component::Component; /// # use bevy_ecs::entity::Entity; /// # use bevy_ecs::system::Query; /// # use bevy_ecs::query::Spawned; /// # use bevy_ecs::query::SpawnDetails; /// /// fn print_spawn_details(query: Query<(Entity, SpawnDetails)>) { /// for (entity, spawn_details) in &query { /// if spawn_details.is_spawned() { /// print!("new "); /// } /// print!( /// "entity {:?} spawned at {:?}", /// entity, /// spawn_details.spawn_tick() /// ); /// match spawn_details.spawned_by().into_option() { /// Some(location) => println!(" by {:?}", location), /// None => println!() /// } /// } /// } /// /// # bevy_ecs::system::assert_is_system(print_spawn_details); /// ``` #[derive(Clone, Copy, Debug)] pub struct SpawnDetails { spawned_by: MaybeLocation, spawn_tick: Tick, last_run: Tick, this_run: Tick, } impl SpawnDetails { /// Returns `true` if the entity spawned since the last time this system ran. /// Otherwise, returns `false`. pub fn is_spawned(self) -> bool { self.spawn_tick.is_newer_than(self.last_run, self.this_run) } /// Returns the `Tick` this entity spawned at. pub fn spawn_tick(self) -> Tick { self.spawn_tick } /// Returns the source code location from which this entity has been spawned. pub fn spawned_by(self) -> MaybeLocation { self.spawned_by } } #[doc(hidden)] #[derive(Clone)] pub struct SpawnDetailsFetch<'w> { entities: &'w Entities, last_run: Tick, this_run: Tick, } // SAFETY: // No components are accessed. unsafe impl WorldQuery for SpawnDetails { type Fetch<'w> = SpawnDetailsFetch<'w>; type State = (); fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> { fetch } unsafe fn init_fetch<'w, 's>( world: UnsafeWorldCell<'w>, _state: &'s Self::State, last_run: Tick, this_run: Tick, ) -> Self::Fetch<'w> { SpawnDetailsFetch { entities: world.entities(), last_run, this_run, } } const IS_DENSE: bool = true; #[inline] unsafe fn set_archetype<'w, 's>( _fetch: &mut Self::Fetch<'w>, _state: &'s Self::State, _archetype: &'w Archetype, _table: &'w Table, ) { } #[inline] unsafe fn set_table<'w, 's>( _fetch: &mut Self::Fetch<'w>, _state: &'s Self::State, _table: &'w Table, ) { } fn update_component_access(_state: &Self::State, _access: &mut FilteredAccess) {} fn init_state(_world: &mut World) {} fn get_state(_components: &Components) -> Option<()> { Some(()) } fn matches_component_set( _state: &Self::State, _set_contains_id: &impl Fn(ComponentId) -> bool, ) -> bool { true } } // SAFETY: // No components are accessed. // Is its own ReadOnlyQueryData. unsafe impl QueryData for SpawnDetails { const IS_READ_ONLY: bool = true; const IS_ARCHETYPAL: bool = true; type ReadOnly = Self; type Item<'w, 's> = Self; fn shrink<'wlong: 'wshort, 'wshort, 's>( item: Self::Item<'wlong, 's>, ) -> Self::Item<'wshort, 's> { item } #[inline(always)] unsafe fn fetch<'w, 's>( _state: &'s Self::State, fetch: &mut Self::Fetch<'w>, entity: Entity, _table_row: TableRow, ) -> Option<Self::Item<'w, 's>> { // SAFETY: only living entities are queried let (spawned_by, spawn_tick) = unsafe { fetch .entities .entity_get_spawned_or_despawned_unchecked(entity) }; Some(Self { spawned_by, spawn_tick, last_run: fetch.last_run, this_run: fetch.this_run, }) } fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> { iter::empty() } } /// SAFETY: access is read only unsafe impl ReadOnlyQueryData for SpawnDetails {} impl ReleaseStateQueryData for SpawnDetails { fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> { item } } impl ArchetypeQueryData for SpawnDetails {} /// The [`WorldQuery::Fetch`] type for WorldQueries that can fetch multiple components from an entity /// ([`EntityRef`], [`EntityMut`], etc.) #[derive(Copy, Clone)] #[doc(hidden)] pub struct EntityFetch<'w> { world: UnsafeWorldCell<'w>, last_run: Tick, this_run: Tick, } /// SAFETY: /// `fetch` accesses all components in a readonly way. /// This is sound because `update_component_access` sets read access for all components and panic when appropriate. /// Filters are unchanged. unsafe impl<'a> WorldQuery for EntityRef<'a> { type Fetch<'w> = EntityFetch<'w>; type State = (); fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> { fetch } unsafe fn init_fetch<'w, 's>( world: UnsafeWorldCell<'w>, _state: &'s Self::State, last_run: Tick, this_run: Tick, ) -> Self::Fetch<'w> { EntityFetch { world, last_run, this_run, } } const IS_DENSE: bool = true; #[inline] unsafe fn set_archetype<'w, 's>( _fetch: &mut Self::Fetch<'w>, _state: &'s Self::State, _archetype: &'w Archetype, _table: &Table, ) { } #[inline] unsafe fn set_table<'w, 's>( _fetch: &mut Self::Fetch<'w>, _state: &'s Self::State, _table: &'w Table, ) { } fn update_component_access(_state: &Self::State, access: &mut FilteredAccess) { assert!( !access.access().has_any_component_write(), "EntityRef conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.", ); access.read_all_components(); } fn init_state(_world: &mut World) {} fn get_state(_components: &Components) -> Option<()> { Some(()) } fn matches_component_set( _state: &Self::State, _set_contains_id: &impl Fn(ComponentId) -> bool, ) -> bool { true } } /// SAFETY: `Self` is the same as `Self::ReadOnly` unsafe impl<'a> QueryData for EntityRef<'a> { const IS_READ_ONLY: bool = true; const IS_ARCHETYPAL: bool = true; type ReadOnly = Self; type Item<'w, 's> = EntityRef<'w>; fn shrink<'wlong: 'wshort, 'wshort, 's>( item: Self::Item<'wlong, 's>, ) -> Self::Item<'wshort, 's> { item } #[inline(always)] unsafe fn fetch<'w, 's>( _state: &'s Self::State, fetch: &mut Self::Fetch<'w>, entity: Entity, _table_row: TableRow, ) -> Option<Self::Item<'w, 's>> { // SAFETY: `fetch` must be called with an entity that exists in the world let cell = unsafe { fetch .world .get_entity_with_ticks(entity, fetch.last_run, fetch.this_run) .debug_checked_unwrap() }; // SAFETY: Read-only access to every component has been registered. Some(unsafe { EntityRef::new(cell) }) } fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> { iter::once(EcsAccessType::Component(EcsAccessLevel::ReadAll)) } } /// SAFETY: access is read only unsafe impl ReadOnlyQueryData for EntityRef<'_> {} impl ReleaseStateQueryData for EntityRef<'_> { fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> { item } } impl ArchetypeQueryData for EntityRef<'_> {} /// SAFETY: The accesses of `Self::ReadOnly` are a subset of the accesses of `Self` unsafe impl<'a> WorldQuery for EntityMut<'a> { type Fetch<'w> = EntityFetch<'w>; type State = (); fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> { fetch } unsafe fn init_fetch<'w, 's>( world: UnsafeWorldCell<'w>, _state: &'s Self::State, last_run: Tick, this_run: Tick, ) -> Self::Fetch<'w> { EntityFetch { world, last_run, this_run, } } const IS_DENSE: bool = true; #[inline] unsafe fn set_archetype<'w, 's>( _fetch: &mut Self::Fetch<'w>, _state: &'s Self::State, _archetype: &'w Archetype, _table: &Table, ) { } #[inline] unsafe fn set_table<'w, 's>( _fetch: &mut Self::Fetch<'w>, _state: &'s Self::State, _table: &'w Table, ) { } fn update_component_access(_state: &Self::State, access: &mut FilteredAccess) { assert!( !access.access().has_any_component_read(), "EntityMut conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses.", ); access.write_all_components(); } fn init_state(_world: &mut World) {} fn get_state(_components: &Components) -> Option<()> { Some(()) } fn matches_component_set( _state: &Self::State, _set_contains_id: &impl Fn(ComponentId) -> bool, ) -> bool { true } } /// SAFETY: access of `EntityRef` is a subset of `EntityMut` unsafe impl<'a> QueryData for EntityMut<'a> { const IS_READ_ONLY: bool = false; const IS_ARCHETYPAL: bool = true; type ReadOnly = EntityRef<'a>; type Item<'w, 's> = EntityMut<'w>; fn shrink<'wlong: 'wshort, 'wshort, 's>( item: Self::Item<'wlong, 's>, ) -> Self::Item<'wshort, 's> { item } #[inline(always)] unsafe fn fetch<'w, 's>( _state: &'s Self::State, fetch: &mut Self::Fetch<'w>, entity: Entity, _table_row: TableRow, ) -> Option<Self::Item<'w, 's>> { // SAFETY: `fetch` must be called with an entity that exists in the world let cell = unsafe { fetch .world .get_entity_with_ticks(entity, fetch.last_run, fetch.this_run) .debug_checked_unwrap() }; // SAFETY: mutable access to every component has been registered. Some(unsafe { EntityMut::new(cell) }) } fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> { iter::once(EcsAccessType::Component(EcsAccessLevel::WriteAll)) } } impl ReleaseStateQueryData for EntityMut<'_> { fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> { item } } impl ArchetypeQueryData for EntityMut<'_> {} /// SAFETY: The accesses of `Self::ReadOnly` are a subset of the accesses of `Self` unsafe impl WorldQuery for FilteredEntityRef<'_, '_> { type Fetch<'w> = EntityFetch<'w>; type State = Access; fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> { fetch } const IS_DENSE: bool = true; unsafe fn init_fetch<'w, 's>( world: UnsafeWorldCell<'w>, _state: &'s Self::State, last_run: Tick, this_run: Tick, ) -> Self::Fetch<'w> { EntityFetch { world, last_run, this_run, } } #[inline] unsafe fn set_archetype<'w, 's>( _fetch: &mut Self::Fetch<'w>, _state: &'s Self::State, _: &'w Archetype, _table: &Table, ) { } #[inline] unsafe fn set_table<'w, 's>( _fetch: &mut Self::Fetch<'w>, _state: &'s Self::State, _: &'w Table, ) { } fn update_component_access(state: &Self::State, filtered_access: &mut FilteredAccess) { assert!( filtered_access.access().is_compatible(state), "FilteredEntityRef conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses.", ); filtered_access.access.extend(state); } fn init_state(_world: &mut World) -> Self::State { Access::default() } fn get_state(_components: &Components) -> Option<Self::State> { Some(Access::default()) } fn matches_component_set( _state: &Self::State,
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/query/access.rs
crates/bevy_ecs/src/query/access.rs
use crate::component::ComponentId; use crate::world::World; use alloc::{format, string::String, vec, vec::Vec}; use core::{fmt, fmt::Debug}; use derive_more::From; use fixedbitset::FixedBitSet; use thiserror::Error; /// A wrapper struct to make Debug representations of [`FixedBitSet`] easier /// to read. /// /// Instead of the raw integer representation of the `FixedBitSet`, the list of /// indexes are shown. /// /// Normal `FixedBitSet` `Debug` output: /// ```text /// read_and_writes: FixedBitSet { data: [ 160 ], length: 8 } /// ``` /// /// Which, unless you are a computer, doesn't help much understand what's in /// the set. With `FormattedBitSet`, we convert the present set entries into /// what they stand for, it is much clearer what is going on: /// ```text /// read_and_writes: [ 5, 7 ] /// ``` struct FormattedBitSet<'a> { bit_set: &'a FixedBitSet, } impl<'a> FormattedBitSet<'a> { fn new(bit_set: &'a FixedBitSet) -> Self { Self { bit_set } } } impl<'a> Debug for FormattedBitSet<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().entries(self.bit_set.ones()).finish() } } /// Tracks read and write access to specific elements in a collection. /// /// Used internally to ensure soundness during system initialization and execution. /// See the [`is_compatible`](Access::is_compatible) and [`get_conflicts`](Access::get_conflicts) functions. #[derive(Eq, PartialEq, Default)] pub struct Access { /// All accessed components, or forbidden components if /// `Self::component_read_and_writes_inverted` is set. component_read_and_writes: FixedBitSet, /// All exclusively-accessed components, or components that may not be /// exclusively accessed if `Self::component_writes_inverted` is set. component_writes: FixedBitSet, /// All accessed resources. resource_read_and_writes: FixedBitSet, /// The exclusively-accessed resources. resource_writes: FixedBitSet, /// Is `true` if this component can read all components *except* those /// present in `Self::component_read_and_writes`. component_read_and_writes_inverted: bool, /// Is `true` if this component can write to all components *except* those /// present in `Self::component_writes`. component_writes_inverted: bool, /// Is `true` if this has access to all resources. /// This field is a performance optimization for `&World` (also harder to mess up for soundness). reads_all_resources: bool, /// Is `true` if this has mutable access to all resources. /// If this is true, then `reads_all` must also be true. writes_all_resources: bool, // Components that are not accessed, but whose presence in an archetype affect query results. archetypal: FixedBitSet, } // This is needed since `#[derive(Clone)]` does not generate optimized `clone_from`. impl Clone for Access { fn clone(&self) -> Self { Self { component_read_and_writes: self.component_read_and_writes.clone(), component_writes: self.component_writes.clone(), resource_read_and_writes: self.resource_read_and_writes.clone(), resource_writes: self.resource_writes.clone(), component_read_and_writes_inverted: self.component_read_and_writes_inverted, component_writes_inverted: self.component_writes_inverted, reads_all_resources: self.reads_all_resources, writes_all_resources: self.writes_all_resources, archetypal: self.archetypal.clone(), } } fn clone_from(&mut self, source: &Self) { self.component_read_and_writes .clone_from(&source.component_read_and_writes); self.component_writes.clone_from(&source.component_writes); self.resource_read_and_writes .clone_from(&source.resource_read_and_writes); self.resource_writes.clone_from(&source.resource_writes); self.component_read_and_writes_inverted = source.component_read_and_writes_inverted; self.component_writes_inverted = source.component_writes_inverted; self.reads_all_resources = source.reads_all_resources; self.writes_all_resources = source.writes_all_resources; self.archetypal.clone_from(&source.archetypal); } } impl Debug for Access { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Access") .field( "component_read_and_writes", &FormattedBitSet::new(&self.component_read_and_writes), ) .field( "component_writes", &FormattedBitSet::new(&self.component_writes), ) .field( "resource_read_and_writes", &FormattedBitSet::new(&self.resource_read_and_writes), ) .field( "resource_writes", &FormattedBitSet::new(&self.resource_writes), ) .field( "component_read_and_writes_inverted", &self.component_read_and_writes_inverted, ) .field("component_writes_inverted", &self.component_writes_inverted) .field("reads_all_resources", &self.reads_all_resources) .field("writes_all_resources", &self.writes_all_resources) .field("archetypal", &FormattedBitSet::new(&self.archetypal)) .finish() } } impl Access { /// Creates an empty [`Access`] collection. pub const fn new() -> Self { Self { reads_all_resources: false, writes_all_resources: false, component_read_and_writes_inverted: false, component_writes_inverted: false, component_read_and_writes: FixedBitSet::new(), component_writes: FixedBitSet::new(), resource_read_and_writes: FixedBitSet::new(), resource_writes: FixedBitSet::new(), archetypal: FixedBitSet::new(), } } /// Creates an [`Access`] with read access to all components. /// This is equivalent to calling `read_all()` on `Access::new()`, /// but is available in a `const` context. pub(crate) const fn new_read_all() -> Self { let mut access = Self::new(); access.reads_all_resources = true; // Note that we cannot use `read_all_components()` // because `FixedBitSet::clear()` is not `const`. access.component_read_and_writes_inverted = true; access } /// Creates an [`Access`] with read access to all components. /// This is equivalent to calling `read_all()` on `Access::new()`, /// but is available in a `const` context. pub(crate) const fn new_write_all() -> Self { let mut access = Self::new(); access.reads_all_resources = true; access.writes_all_resources = true; // Note that we cannot use `write_all_components()` // because `FixedBitSet::clear()` is not `const`. access.component_read_and_writes_inverted = true; access.component_writes_inverted = true; access } fn add_component_sparse_set_index_read(&mut self, index: usize) { if !self.component_read_and_writes_inverted { self.component_read_and_writes.grow_and_insert(index); } else if index < self.component_read_and_writes.len() { self.component_read_and_writes.remove(index); } } fn add_component_sparse_set_index_write(&mut self, index: usize) { if !self.component_writes_inverted { self.component_writes.grow_and_insert(index); } else if index < self.component_writes.len() { self.component_writes.remove(index); } } /// Adds access to the component given by `index`. pub fn add_component_read(&mut self, index: ComponentId) { let sparse_set_index = index.index(); self.add_component_sparse_set_index_read(sparse_set_index); } /// Adds exclusive access to the component given by `index`. pub fn add_component_write(&mut self, index: ComponentId) { let sparse_set_index = index.index(); self.add_component_sparse_set_index_read(sparse_set_index); self.add_component_sparse_set_index_write(sparse_set_index); } /// Adds access to the resource given by `index`. pub fn add_resource_read(&mut self, index: ComponentId) { self.resource_read_and_writes.grow_and_insert(index.index()); } /// Adds exclusive access to the resource given by `index`. pub fn add_resource_write(&mut self, index: ComponentId) { self.resource_read_and_writes.grow_and_insert(index.index()); self.resource_writes.grow_and_insert(index.index()); } fn remove_component_sparse_set_index_read(&mut self, index: usize) { if self.component_read_and_writes_inverted { self.component_read_and_writes.grow_and_insert(index); } else if index < self.component_read_and_writes.len() { self.component_read_and_writes.remove(index); } } fn remove_component_sparse_set_index_write(&mut self, index: usize) { if self.component_writes_inverted { self.component_writes.grow_and_insert(index); } else if index < self.component_writes.len() { self.component_writes.remove(index); } } /// Removes both read and write access to the component given by `index`. /// /// Because this method corresponds to the set difference operator ∖, it can /// create complicated logical formulas that you should verify correctness /// of. For example, A ∪ (B ∖ A) isn't equivalent to (A ∪ B) ∖ A, so you /// can't replace a call to `remove_component_read` followed by a call to /// `extend` with a call to `extend` followed by a call to /// `remove_component_read`. pub fn remove_component_read(&mut self, index: ComponentId) { let sparse_set_index = index.index(); self.remove_component_sparse_set_index_write(sparse_set_index); self.remove_component_sparse_set_index_read(sparse_set_index); } /// Removes write access to the component given by `index`. /// /// Because this method corresponds to the set difference operator ∖, it can /// create complicated logical formulas that you should verify correctness /// of. For example, A ∪ (B ∖ A) isn't equivalent to (A ∪ B) ∖ A, so you /// can't replace a call to `remove_component_write` followed by a call to /// `extend` with a call to `extend` followed by a call to /// `remove_component_write`. pub fn remove_component_write(&mut self, index: ComponentId) { let sparse_set_index = index.index(); self.remove_component_sparse_set_index_write(sparse_set_index); } /// Adds an archetypal (indirect) access to the component given by `index`. /// /// This is for components whose values are not accessed (and thus will never cause conflicts), /// but whose presence in an archetype may affect query results. /// /// Currently, this is only used for [`Has<T>`] and [`Allow<T>`]. /// /// [`Has<T>`]: crate::query::Has /// [`Allow<T>`]: crate::query::filter::Allow pub fn add_archetypal(&mut self, index: ComponentId) { self.archetypal.grow_and_insert(index.index()); } /// Returns `true` if this can access the component given by `index`. pub fn has_component_read(&self, index: ComponentId) -> bool { self.component_read_and_writes_inverted ^ self.component_read_and_writes.contains(index.index()) } /// Returns `true` if this can access any component. pub fn has_any_component_read(&self) -> bool { self.component_read_and_writes_inverted || !self.component_read_and_writes.is_clear() } /// Returns `true` if this can exclusively access the component given by `index`. pub fn has_component_write(&self, index: ComponentId) -> bool { self.component_writes_inverted ^ self.component_writes.contains(index.index()) } /// Returns `true` if this accesses any component mutably. pub fn has_any_component_write(&self) -> bool { self.component_writes_inverted || !self.component_writes.is_clear() } /// Returns `true` if this can access the resource given by `index`. pub fn has_resource_read(&self, index: ComponentId) -> bool { self.reads_all_resources || self.resource_read_and_writes.contains(index.index()) } /// Returns `true` if this can access any resource. pub fn has_any_resource_read(&self) -> bool { self.reads_all_resources || !self.resource_read_and_writes.is_clear() } /// Returns `true` if this can exclusively access the resource given by `index`. pub fn has_resource_write(&self, index: ComponentId) -> bool { self.writes_all_resources || self.resource_writes.contains(index.index()) } /// Returns `true` if this accesses any resource mutably. pub fn has_any_resource_write(&self) -> bool { self.writes_all_resources || !self.resource_writes.is_clear() } /// Returns `true` if this accesses any resources or components. pub fn has_any_read(&self) -> bool { self.has_any_component_read() || self.has_any_resource_read() } /// Returns `true` if this accesses any resources or components mutably. pub fn has_any_write(&self) -> bool { self.has_any_component_write() || self.has_any_resource_write() } /// Returns true if this has an archetypal (indirect) access to the component given by `index`. /// /// This is a component whose value is not accessed (and thus will never cause conflicts), /// but whose presence in an archetype may affect query results. /// /// Currently, this is only used for [`Has<T>`]. /// /// [`Has<T>`]: crate::query::Has pub fn has_archetypal(&self, index: ComponentId) -> bool { self.archetypal.contains(index.index()) } /// Sets this as having access to all components (i.e. `EntityRef`). #[inline] pub fn read_all_components(&mut self) { self.component_read_and_writes_inverted = true; self.component_read_and_writes.clear(); } /// Sets this as having mutable access to all components (i.e. `EntityMut`). #[inline] pub fn write_all_components(&mut self) { self.read_all_components(); self.component_writes_inverted = true; self.component_writes.clear(); } /// Sets this as having access to all resources (i.e. `&World`). #[inline] pub const fn read_all_resources(&mut self) { self.reads_all_resources = true; } /// Sets this as having mutable access to all resources (i.e. `&mut World`). #[inline] pub const fn write_all_resources(&mut self) { self.reads_all_resources = true; self.writes_all_resources = true; } /// Sets this as having access to all indexed elements (i.e. `&World`). #[inline] pub fn read_all(&mut self) { self.read_all_components(); self.read_all_resources(); } /// Sets this as having mutable access to all indexed elements (i.e. `&mut World`). #[inline] pub fn write_all(&mut self) { self.write_all_components(); self.write_all_resources(); } /// Returns `true` if this has access to all components (i.e. `EntityRef`). #[inline] pub fn has_read_all_components(&self) -> bool { self.component_read_and_writes_inverted && self.component_read_and_writes.is_clear() } /// Returns `true` if this has write access to all components (i.e. `EntityMut`). #[inline] pub fn has_write_all_components(&self) -> bool { self.component_writes_inverted && self.component_writes.is_clear() } /// Returns `true` if this has access to all resources (i.e. `EntityRef`). #[inline] pub fn has_read_all_resources(&self) -> bool { self.reads_all_resources } /// Returns `true` if this has write access to all resources (i.e. `EntityMut`). #[inline] pub fn has_write_all_resources(&self) -> bool { self.writes_all_resources } /// Returns `true` if this has access to all indexed elements (i.e. `&World`). pub fn has_read_all(&self) -> bool { self.has_read_all_components() && self.has_read_all_resources() } /// Returns `true` if this has write access to all indexed elements (i.e. `&mut World`). pub fn has_write_all(&self) -> bool { self.has_write_all_components() && self.has_write_all_resources() } /// Removes all writes. pub fn clear_writes(&mut self) { self.writes_all_resources = false; self.component_writes_inverted = false; self.component_writes.clear(); self.resource_writes.clear(); } /// Removes all accesses. pub fn clear(&mut self) { self.reads_all_resources = false; self.writes_all_resources = false; self.component_read_and_writes_inverted = false; self.component_writes_inverted = false; self.component_read_and_writes.clear(); self.component_writes.clear(); self.resource_read_and_writes.clear(); self.resource_writes.clear(); } /// Adds all access from `other`. pub fn extend(&mut self, other: &Access) { invertible_union_with( &mut self.component_read_and_writes, &mut self.component_read_and_writes_inverted, &other.component_read_and_writes, other.component_read_and_writes_inverted, ); invertible_union_with( &mut self.component_writes, &mut self.component_writes_inverted, &other.component_writes, other.component_writes_inverted, ); self.reads_all_resources = self.reads_all_resources || other.reads_all_resources; self.writes_all_resources = self.writes_all_resources || other.writes_all_resources; self.resource_read_and_writes .union_with(&other.resource_read_and_writes); self.resource_writes.union_with(&other.resource_writes); self.archetypal.union_with(&other.archetypal); } /// Removes any access from `self` that would conflict with `other`. /// This removes any reads and writes for any component written by `other`, /// and removes any writes for any component read by `other`. pub fn remove_conflicting_access(&mut self, other: &Access) { invertible_difference_with( &mut self.component_read_and_writes, &mut self.component_read_and_writes_inverted, &other.component_writes, other.component_writes_inverted, ); invertible_difference_with( &mut self.component_writes, &mut self.component_writes_inverted, &other.component_read_and_writes, other.component_read_and_writes_inverted, ); if other.reads_all_resources { self.writes_all_resources = false; self.resource_writes.clear(); } if other.writes_all_resources { self.reads_all_resources = false; self.resource_read_and_writes.clear(); } self.resource_read_and_writes .difference_with(&other.resource_writes); self.resource_writes .difference_with(&other.resource_read_and_writes); } /// Returns `true` if the access and `other` can be active at the same time, /// only looking at their component access. /// /// [`Access`] instances are incompatible if one can write /// an element that the other can read or write. pub fn is_components_compatible(&self, other: &Access) -> bool { // We have a conflict if we write and they read or write, or if they // write and we read or write. for ( lhs_writes, rhs_reads_and_writes, lhs_writes_inverted, rhs_reads_and_writes_inverted, ) in [ ( &self.component_writes, &other.component_read_and_writes, self.component_writes_inverted, other.component_read_and_writes_inverted, ), ( &other.component_writes, &self.component_read_and_writes, other.component_writes_inverted, self.component_read_and_writes_inverted, ), ] { match (lhs_writes_inverted, rhs_reads_and_writes_inverted) { (true, true) => return false, (false, true) => { if !lhs_writes.is_subset(rhs_reads_and_writes) { return false; } } (true, false) => { if !rhs_reads_and_writes.is_subset(lhs_writes) { return false; } } (false, false) => { if !lhs_writes.is_disjoint(rhs_reads_and_writes) { return false; } } } } true } /// Returns `true` if the access and `other` can be active at the same time, /// only looking at their resource access. /// /// [`Access`] instances are incompatible if one can write /// an element that the other can read or write. pub fn is_resources_compatible(&self, other: &Access) -> bool { if self.writes_all_resources { return !other.has_any_resource_read(); } if other.writes_all_resources { return !self.has_any_resource_read(); } if self.reads_all_resources { return !other.has_any_resource_write(); } if other.reads_all_resources { return !self.has_any_resource_write(); } self.resource_writes .is_disjoint(&other.resource_read_and_writes) && other .resource_writes .is_disjoint(&self.resource_read_and_writes) } /// Returns `true` if the access and `other` can be active at the same time. /// /// [`Access`] instances are incompatible if one can write /// an element that the other can read or write. pub fn is_compatible(&self, other: &Access) -> bool { self.is_components_compatible(other) && self.is_resources_compatible(other) } /// Returns `true` if the set's component access is a subset of another, i.e. `other`'s component access /// contains at least all the values in `self`. pub fn is_subset_components(&self, other: &Access) -> bool { for ( our_components, their_components, our_components_inverted, their_components_inverted, ) in [ ( &self.component_read_and_writes, &other.component_read_and_writes, self.component_read_and_writes_inverted, other.component_read_and_writes_inverted, ), ( &self.component_writes, &other.component_writes, self.component_writes_inverted, other.component_writes_inverted, ), ] { match (our_components_inverted, their_components_inverted) { (true, true) => { if !their_components.is_subset(our_components) { return false; } } (true, false) => { return false; } (false, true) => { if !our_components.is_disjoint(their_components) { return false; } } (false, false) => { if !our_components.is_subset(their_components) { return false; } } } } true } /// Returns `true` if the set's resource access is a subset of another, i.e. `other`'s resource access /// contains at least all the values in `self`. pub fn is_subset_resources(&self, other: &Access) -> bool { if self.writes_all_resources { return other.writes_all_resources; } if other.writes_all_resources { return true; } if self.reads_all_resources { return other.reads_all_resources; } if other.reads_all_resources { return self.resource_writes.is_subset(&other.resource_writes); } self.resource_read_and_writes .is_subset(&other.resource_read_and_writes) && self.resource_writes.is_subset(&other.resource_writes) } /// Returns `true` if the set is a subset of another, i.e. `other` contains /// at least all the values in `self`. pub fn is_subset(&self, other: &Access) -> bool { self.is_subset_components(other) && self.is_subset_resources(other) } fn get_component_conflicts(&self, other: &Access) -> AccessConflicts { let mut conflicts = FixedBitSet::new(); // We have a conflict if we write and they read or write, or if they // write and we read or write. for ( lhs_writes, rhs_reads_and_writes, lhs_writes_inverted, rhs_reads_and_writes_inverted, ) in [ ( &self.component_writes, &other.component_read_and_writes, self.component_writes_inverted, other.component_read_and_writes_inverted, ), ( &other.component_writes, &self.component_read_and_writes, other.component_writes_inverted, self.component_read_and_writes_inverted, ), ] { // There's no way that I can see to do this without a temporary. // Neither CNF nor DNF allows us to avoid one. let temp_conflicts: FixedBitSet = match (lhs_writes_inverted, rhs_reads_and_writes_inverted) { (true, true) => return AccessConflicts::All, (false, true) => lhs_writes.difference(rhs_reads_and_writes).collect(), (true, false) => rhs_reads_and_writes.difference(lhs_writes).collect(), (false, false) => lhs_writes.intersection(rhs_reads_and_writes).collect(), }; conflicts.union_with(&temp_conflicts); } AccessConflicts::Individual(conflicts) } /// Returns a vector of elements that the access and `other` cannot access at the same time. pub fn get_conflicts(&self, other: &Access) -> AccessConflicts { let mut conflicts = match self.get_component_conflicts(other) { AccessConflicts::All => return AccessConflicts::All, AccessConflicts::Individual(conflicts) => conflicts, }; if self.reads_all_resources { if other.writes_all_resources { return AccessConflicts::All; } conflicts.extend(other.resource_writes.ones()); } if other.reads_all_resources { if self.writes_all_resources { return AccessConflicts::All; } conflicts.extend(self.resource_writes.ones()); } if self.writes_all_resources { conflicts.extend(other.resource_read_and_writes.ones()); } if other.writes_all_resources { conflicts.extend(self.resource_read_and_writes.ones()); } conflicts.extend( self.resource_writes .intersection(&other.resource_read_and_writes), ); conflicts.extend( self.resource_read_and_writes .intersection(&other.resource_writes), ); AccessConflicts::Individual(conflicts) } /// Returns the indices of the resources this has access to. pub fn resource_reads_and_writes(&self) -> impl Iterator<Item = ComponentId> + '_ { self.resource_read_and_writes.ones().map(ComponentId::new) } /// Returns the indices of the resources this has non-exclusive access to. pub fn resource_reads(&self) -> impl Iterator<Item = ComponentId> + '_ { self.resource_read_and_writes .difference(&self.resource_writes) .map(ComponentId::new) } /// Returns the indices of the resources this has exclusive access to. pub fn resource_writes(&self) -> impl Iterator<Item = ComponentId> + '_ { self.resource_writes.ones().map(ComponentId::new) } /// Returns the indices of the components that this has an archetypal access to. /// /// These are components whose values are not accessed (and thus will never cause conflicts), /// but whose presence in an archetype may affect query results. /// /// Currently, this is only used for [`Has<T>`]. /// /// [`Has<T>`]: crate::query::Has pub fn archetypal(&self) -> impl Iterator<Item = ComponentId> + '_ { self.archetypal.ones().map(ComponentId::new) } /// Returns an iterator over the component IDs and their [`ComponentAccessKind`]. /// /// Returns `Err(UnboundedAccess)` if the access is unbounded. /// This typically occurs when an [`Access`] is marked as accessing all /// components, and then adding exceptions. /// /// # Examples /// /// ```rust /// # use bevy_ecs::query::{Access, ComponentAccessKind}; /// # use bevy_ecs::component::ComponentId; /// let mut access = Access::default(); /// /// access.add_component_read(ComponentId::new(1)); /// access.add_component_write(ComponentId::new(2)); /// access.add_archetypal(ComponentId::new(3)); /// /// let result = access /// .try_iter_component_access() /// .map(Iterator::collect::<Vec<_>>); /// /// assert_eq!( /// result, /// Ok(vec![ /// ComponentAccessKind::Shared(ComponentId::new(1)), /// ComponentAccessKind::Exclusive(ComponentId::new(2)), /// ComponentAccessKind::Archetypal(ComponentId::new(3)), /// ]), /// ); /// ``` pub fn try_iter_component_access( &self, ) -> Result<impl Iterator<Item = ComponentAccessKind> + '_, UnboundedAccessError> { // component_writes_inverted is only ever true when component_read_and_writes_inverted is // also true. Therefore it is sufficient to check just component_read_and_writes_inverted. if self.component_read_and_writes_inverted { return Err(UnboundedAccessError { writes_inverted: self.component_writes_inverted, read_and_writes_inverted: self.component_read_and_writes_inverted, }); } let reads_and_writes = self.component_read_and_writes.ones().map(|index| { let sparse_index = ComponentId::new(index); if self.component_writes.contains(index) { ComponentAccessKind::Exclusive(sparse_index) } else { ComponentAccessKind::Shared(sparse_index) } }); let archetypal = self .archetypal .ones() .filter(|&index| { !self.component_writes.contains(index) && !self.component_read_and_writes.contains(index) }) .map(|index| ComponentAccessKind::Archetypal(ComponentId::new(index))); Ok(reads_and_writes.chain(archetypal)) } } /// Performs an in-place union of `other` into `self`, where either set may be inverted. /// /// Each set corresponds to a `FixedBitSet` if `inverted` is `false`, /// or to the infinite (co-finite) complement of the `FixedBitSet` if `inverted` is `true`. /// /// This updates the `self` set to include any elements in the `other` set. /// Note that this may change `self_inverted` to `true` if we add an infinite /// set to a finite one, resulting in a new infinite set. fn invertible_union_with( self_set: &mut FixedBitSet, self_inverted: &mut bool, other_set: &FixedBitSet, other_inverted: bool, ) { match (*self_inverted, other_inverted) { (true, true) => self_set.intersect_with(other_set), (true, false) => self_set.difference_with(other_set), (false, true) => {
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/query/mod.rs
crates/bevy_ecs/src/query/mod.rs
#![expect( unsafe_op_in_unsafe_fn, reason = "See #11590. To be removed once all applicable unsafe code has an unsafe block with a safety comment." )] //! Contains APIs for retrieving component data from the world. mod access; mod access_iter; mod builder; mod error; mod fetch; mod filter; mod iter; mod par_iter; mod state; mod world_query; pub use access::*; pub use access_iter::*; pub use bevy_ecs_macros::{QueryData, QueryFilter}; pub use builder::*; pub use error::*; pub use fetch::*; pub use filter::*; pub use iter::*; pub use par_iter::*; pub use state::*; pub use world_query::*; /// A debug checked version of [`Option::unwrap_unchecked`]. Will panic in /// debug modes if unwrapping a `None` or `Err` value in debug mode, but is /// equivalent to `Option::unwrap_unchecked` or `Result::unwrap_unchecked` /// in release mode. #[doc(hidden)] pub trait DebugCheckedUnwrap { type Item; /// # Panics /// Panics if the value is `None` or `Err`, only in debug mode. /// /// # Safety /// This must never be called on a `None` or `Err` value. This can /// only be called on `Some` or `Ok` values. unsafe fn debug_checked_unwrap(self) -> Self::Item; } // These two impls are explicitly split to ensure that the unreachable! macro // does not cause inlining to fail when compiling in release mode. #[cfg(debug_assertions)] impl<T> DebugCheckedUnwrap for Option<T> { type Item = T; #[inline(always)] #[track_caller] unsafe fn debug_checked_unwrap(self) -> Self::Item { if let Some(inner) = self { inner } else { unreachable!() } } } // These two impls are explicitly split to ensure that the unreachable! macro // does not cause inlining to fail when compiling in release mode. #[cfg(debug_assertions)] impl<T, U> DebugCheckedUnwrap for Result<T, U> { type Item = T; #[inline(always)] #[track_caller] unsafe fn debug_checked_unwrap(self) -> Self::Item { if let Ok(inner) = self { inner } else { unreachable!() } } } // These two impls are explicitly split to ensure that the unreachable! macro // does not cause inlining to fail when compiling in release mode. #[cfg(not(debug_assertions))] impl<T, U> DebugCheckedUnwrap for Result<T, U> { type Item = T; #[inline(always)] #[track_caller] unsafe fn debug_checked_unwrap(self) -> Self::Item { if let Ok(inner) = self { inner } else { core::hint::unreachable_unchecked() } } } #[cfg(not(debug_assertions))] impl<T> DebugCheckedUnwrap for Option<T> { type Item = T; #[inline(always)] unsafe fn debug_checked_unwrap(self) -> Self::Item { if let Some(inner) = self { inner } else { core::hint::unreachable_unchecked() } } } #[cfg(test)] #[expect(clippy::print_stdout, reason = "Allowed in tests.")] mod tests { use crate::{ archetype::Archetype, change_detection::Tick, component::{Component, ComponentId, Components}, prelude::{AnyOf, Changed, Entity, Or, QueryState, Resource, With, Without}, query::{ ArchetypeFilter, ArchetypeQueryData, FilteredAccess, Has, QueryCombinationIter, QueryData, QueryFilter, ReadOnlyQueryData, WorldQuery, }, schedule::{IntoScheduleConfigs, Schedule}, storage::{Table, TableRow}, system::{assert_is_system, IntoSystem, Query, System, SystemState}, world::{unsafe_world_cell::UnsafeWorldCell, World}, }; use alloc::{vec, vec::Vec}; use core::{any::type_name, fmt::Debug, hash::Hash}; use std::{collections::HashSet, println}; #[derive(Component, Debug, Hash, Eq, PartialEq, Clone, Copy, PartialOrd, Ord)] struct A(usize); #[derive(Component, Debug, Hash, Eq, PartialEq, Clone, Copy)] struct B(usize); #[derive(Component, Debug, Eq, PartialEq, Clone, Copy)] struct C(usize); #[derive(Component, Debug, Eq, PartialEq, Clone, Copy)] struct D(usize); #[derive(Component, Debug, Hash, Eq, PartialEq, Clone, Copy, PartialOrd, Ord)] #[component(storage = "SparseSet")] struct Sparse(usize); #[test] fn query() { let mut world = World::new(); world.spawn((A(1), B(1))); world.spawn(A(2)); let values = world.query::<&A>().iter(&world).collect::<HashSet<&A>>(); assert!(values.contains(&A(1))); assert!(values.contains(&A(2))); for (_a, mut b) in world.query::<(&A, &mut B)>().iter_mut(&mut world) { b.0 = 3; } let values = world.query::<&B>().iter(&world).collect::<Vec<&B>>(); assert_eq!(values, vec![&B(3)]); } #[test] fn query_filtered_exactsizeiterator_len() { fn choose(n: usize, k: usize) -> usize { if n == 0 || k == 0 || n < k { return 0; } let ks = 1..=k; let ns = (n - k + 1..=n).rev(); ks.zip(ns).fold(1, |acc, (k, n)| acc * n / k) } fn assert_combination<D, F, const K: usize>(world: &mut World, expected_size: usize) where D: ReadOnlyQueryData + ArchetypeQueryData, F: ArchetypeFilter, { let mut query = world.query_filtered::<D, F>(); let query_type = type_name::<QueryCombinationIter<D, F, K>>(); let iter = query.iter_combinations::<K>(world); assert_all_sizes_iterator_equal(iter, expected_size, 0, query_type); let iter = query.iter_combinations::<K>(world); assert_all_sizes_iterator_equal(iter, expected_size, 1, query_type); let iter = query.iter_combinations::<K>(world); assert_all_sizes_iterator_equal(iter, expected_size, 5, query_type); } fn assert_all_sizes_equal<D, F>(world: &mut World, expected_size: usize) where D: ReadOnlyQueryData + ArchetypeQueryData, F: ArchetypeFilter, { let mut query = world.query_filtered::<D, F>(); let query_type = type_name::<QueryState<D, F>>(); assert_all_exact_sizes_iterator_equal(query.iter(world), expected_size, 0, query_type); assert_all_exact_sizes_iterator_equal(query.iter(world), expected_size, 1, query_type); assert_all_exact_sizes_iterator_equal(query.iter(world), expected_size, 5, query_type); let expected = expected_size; assert_combination::<D, F, 1>(world, choose(expected, 1)); assert_combination::<D, F, 2>(world, choose(expected, 2)); assert_combination::<D, F, 5>(world, choose(expected, 5)); assert_combination::<D, F, 43>(world, choose(expected, 43)); assert_combination::<D, F, 64>(world, choose(expected, 64)); } fn assert_all_exact_sizes_iterator_equal( iterator: impl ExactSizeIterator, expected_size: usize, skip: usize, query_type: &'static str, ) { let len = iterator.len(); println!("len: {len}"); assert_all_sizes_iterator_equal(iterator, expected_size, skip, query_type); assert_eq!(len, expected_size); } fn assert_all_sizes_iterator_equal( mut iterator: impl Iterator, expected_size: usize, skip: usize, query_type: &'static str, ) { let expected_size = expected_size.saturating_sub(skip); for _ in 0..skip { iterator.next(); } let size_hint_0 = iterator.size_hint().0; let size_hint_1 = iterator.size_hint().1; // `count` tests that not only it is the expected value, but also // the value is accurate to what the query returns. let count = iterator.count(); // This will show up when one of the asserts in this function fails println!( "query declared sizes: \n\ for query: {query_type} \n\ expected: {expected_size} \n\ size_hint().0: {size_hint_0} \n\ size_hint().1: {size_hint_1:?} \n\ count(): {count}" ); assert_eq!(size_hint_0, expected_size); assert_eq!(size_hint_1, Some(expected_size)); assert_eq!(count, expected_size); } let mut world = World::new(); world.spawn((A(1), B(1))); world.spawn(A(2)); world.spawn(A(3)); assert_all_sizes_equal::<&A, With<B>>(&mut world, 1); assert_all_sizes_equal::<&A, Without<B>>(&mut world, 2); let mut world = World::new(); world.spawn((A(1), B(1), C(1))); world.spawn((A(2), B(2))); world.spawn((A(3), B(3))); world.spawn((A(4), C(4))); world.spawn((A(5), C(5))); world.spawn((A(6), C(6))); world.spawn(A(7)); world.spawn(A(8)); world.spawn(A(9)); world.spawn(A(10)); // With/Without for B and C assert_all_sizes_equal::<&A, With<B>>(&mut world, 3); assert_all_sizes_equal::<&A, With<C>>(&mut world, 4); assert_all_sizes_equal::<&A, Without<B>>(&mut world, 7); assert_all_sizes_equal::<&A, Without<C>>(&mut world, 6); // With/Without (And) combinations assert_all_sizes_equal::<&A, (With<B>, With<C>)>(&mut world, 1); assert_all_sizes_equal::<&A, (With<B>, Without<C>)>(&mut world, 2); assert_all_sizes_equal::<&A, (Without<B>, With<C>)>(&mut world, 3); assert_all_sizes_equal::<&A, (Without<B>, Without<C>)>(&mut world, 4); // With/Without Or<()> combinations assert_all_sizes_equal::<&A, Or<(With<B>, With<C>)>>(&mut world, 6); assert_all_sizes_equal::<&A, Or<(With<B>, Without<C>)>>(&mut world, 7); assert_all_sizes_equal::<&A, Or<(Without<B>, With<C>)>>(&mut world, 8); assert_all_sizes_equal::<&A, Or<(Without<B>, Without<C>)>>(&mut world, 9); assert_all_sizes_equal::<&A, (Or<(With<B>,)>, Or<(With<C>,)>)>(&mut world, 1); assert_all_sizes_equal::<&A, Or<(Or<(With<B>, With<C>)>, With<D>)>>(&mut world, 6); for i in 11..14 { world.spawn((A(i), D(i))); } assert_all_sizes_equal::<&A, Or<(Or<(With<B>, With<C>)>, With<D>)>>(&mut world, 9); assert_all_sizes_equal::<&A, Or<(Or<(With<B>, With<C>)>, Without<D>)>>(&mut world, 10); // a fair amount of entities for i in 14..20 { world.spawn((C(i), D(i))); } assert_all_sizes_equal::<Entity, (With<C>, With<D>)>(&mut world, 6); } // the order of the combinations is not guaranteed, but each unique combination is present fn check_combinations<T: Ord + Hash + Debug, const K: usize>( values: HashSet<[&T; K]>, expected: HashSet<[&T; K]>, ) { values.iter().for_each(|pair| { let mut sorted = *pair; sorted.sort(); assert!(expected.contains(&sorted), "the results of iter_combinations should contain this combination {:?}. Expected: {:?}, got: {:?}", &sorted, &expected, &values); }); } #[test] fn query_iter_combinations() { let mut world = World::new(); world.spawn((A(1), B(1))); world.spawn(A(2)); world.spawn(A(3)); world.spawn(A(4)); let values: HashSet<[&A; 2]> = world.query::<&A>().iter_combinations(&world).collect(); check_combinations( values, HashSet::from([ [&A(1), &A(2)], [&A(1), &A(3)], [&A(1), &A(4)], [&A(2), &A(3)], [&A(2), &A(4)], [&A(3), &A(4)], ]), ); let mut a_query = world.query::<&A>(); let values: HashSet<[&A; 3]> = a_query.iter_combinations(&world).collect(); check_combinations( values, HashSet::from([ [&A(1), &A(2), &A(3)], [&A(1), &A(2), &A(4)], [&A(1), &A(3), &A(4)], [&A(2), &A(3), &A(4)], ]), ); let mut b_query = world.query::<&B>(); assert_eq!( b_query.iter_combinations::<2>(&world).size_hint(), (0, Some(0)) ); let values: Vec<[&B; 2]> = b_query.iter_combinations(&world).collect(); assert_eq!(values, Vec::<[&B; 2]>::new()); } #[test] fn query_filtered_iter_combinations() { use bevy_ecs::query::{Added, Or, With, Without}; let mut world = World::new(); world.spawn((A(1), B(1))); world.spawn(A(2)); world.spawn(A(3)); world.spawn(A(4)); let mut a_wout_b = world.query_filtered::<&A, Without<B>>(); let values: HashSet<[&A; 2]> = a_wout_b.iter_combinations(&world).collect(); check_combinations( values, HashSet::from([[&A(2), &A(3)], [&A(2), &A(4)], [&A(3), &A(4)]]), ); let values: HashSet<[&A; 3]> = a_wout_b.iter_combinations(&world).collect(); check_combinations(values, HashSet::from([[&A(2), &A(3), &A(4)]])); let mut query = world.query_filtered::<&A, Or<(With<A>, With<B>)>>(); let values: HashSet<[&A; 2]> = query.iter_combinations(&world).collect(); check_combinations( values, HashSet::from([ [&A(1), &A(2)], [&A(1), &A(3)], [&A(1), &A(4)], [&A(2), &A(3)], [&A(2), &A(4)], [&A(3), &A(4)], ]), ); let mut query = world.query_filtered::<&mut A, Without<B>>(); let mut combinations = query.iter_combinations_mut(&mut world); while let Some([mut a, mut b, mut c]) = combinations.fetch_next() { a.0 += 10; b.0 += 100; c.0 += 1000; } let values: HashSet<[&A; 3]> = a_wout_b.iter_combinations(&world).collect(); check_combinations(values, HashSet::from([[&A(12), &A(103), &A(1004)]])); // Check if Added<T>, Changed<T> works let mut world = World::new(); world.spawn((A(1), B(1))); world.spawn((A(2), B(2))); world.spawn((A(3), B(3))); world.spawn((A(4), B(4))); let mut query_added = world.query_filtered::<&A, Added<A>>(); world.clear_trackers(); world.spawn(A(5)); assert_eq!(query_added.iter_combinations::<2>(&world).count(), 0); world.clear_trackers(); world.spawn(A(6)); world.spawn(A(7)); assert_eq!(query_added.iter_combinations::<2>(&world).count(), 1); world.clear_trackers(); world.spawn(A(8)); world.spawn(A(9)); world.spawn(A(10)); assert_eq!(query_added.iter_combinations::<2>(&world).count(), 3); } #[test] fn query_iter_combinations_sparse() { let mut world = World::new(); world.spawn_batch((1..=4).map(Sparse)); let values: HashSet<[&Sparse; 3]> = world.query::<&Sparse>().iter_combinations(&world).collect(); check_combinations( values, HashSet::from([ [&Sparse(1), &Sparse(2), &Sparse(3)], [&Sparse(1), &Sparse(2), &Sparse(4)], [&Sparse(1), &Sparse(3), &Sparse(4)], [&Sparse(2), &Sparse(3), &Sparse(4)], ]), ); } #[test] fn get_many_only_mut_checks_duplicates() { let mut world = World::new(); let id = world.spawn(A(10)).id(); let mut query_state = world.query::<&mut A>(); let mut query = query_state.query_mut(&mut world); let result = query.get_many([id, id]); assert_eq!(result, Ok([&A(10), &A(10)])); let mut_result = query.get_many_mut([id, id]); assert!(mut_result.is_err()); } #[test] fn multi_storage_query() { let mut world = World::new(); world.spawn((Sparse(1), B(2))); world.spawn(Sparse(2)); let values = world .query::<&Sparse>() .iter(&world) .collect::<HashSet<&Sparse>>(); assert!(values.contains(&Sparse(1))); assert!(values.contains(&Sparse(2))); for (_a, mut b) in world.query::<(&Sparse, &mut B)>().iter_mut(&mut world) { b.0 = 3; } let values = world.query::<&B>().iter(&world).collect::<Vec<&B>>(); assert_eq!(values, vec![&B(3)]); } #[test] fn any_query() { let mut world = World::new(); world.spawn((A(1), B(2))); world.spawn(A(2)); world.spawn(C(3)); let values: Vec<(Option<&A>, Option<&B>)> = world.query::<AnyOf<(&A, &B)>>().iter(&world).collect(); assert_eq!( values, vec![(Some(&A(1)), Some(&B(2))), (Some(&A(2)), None),] ); } #[test] fn has_query() { let mut world = World::new(); world.spawn((A(1), B(1))); world.spawn(A(2)); world.spawn((A(3), B(1))); world.spawn(A(4)); let values: HashSet<(&A, bool)> = world.query::<(&A, Has<B>)>().iter(&world).collect(); assert!(values.contains(&(&A(1), true))); assert!(values.contains(&(&A(2), false))); assert!(values.contains(&(&A(3), true))); assert!(values.contains(&(&A(4), false))); } #[test] #[should_panic] fn self_conflicting_worldquery() { #[derive(QueryData)] #[query_data(mutable)] struct SelfConflicting { a: &'static mut A, b: &'static mut A, } let mut world = World::new(); world.query::<SelfConflicting>(); } #[test] fn derived_worldqueries() { let mut world = World::new(); world.spawn((A(10), B(18), C(3), Sparse(4))); world.spawn((A(101), B(148), C(13))); world.spawn((A(51), B(46), Sparse(72))); world.spawn((A(398), C(6), Sparse(9))); world.spawn((B(11), C(28), Sparse(92))); world.spawn((C(18348), Sparse(101))); world.spawn((B(839), Sparse(5))); world.spawn((B(6721), C(122))); world.spawn((A(220), Sparse(63))); world.spawn((A(1092), C(382))); world.spawn((A(2058), B(3019))); world.spawn((B(38), C(8), Sparse(100))); world.spawn((A(111), C(52), Sparse(1))); world.spawn((A(599), B(39), Sparse(13))); world.spawn((A(55), B(66), C(77))); world.spawn_empty(); { #[derive(QueryData)] struct CustomAB { a: &'static A, b: &'static B, } let custom_param_data = world .query::<CustomAB>() .iter(&world) .map(|item| (*item.a, *item.b)) .collect::<Vec<_>>(); let normal_data = world .query::<(&A, &B)>() .iter(&world) .map(|(a, b)| (*a, *b)) .collect::<Vec<_>>(); assert_eq!(custom_param_data, normal_data); } { #[derive(QueryData)] struct FancyParam { e: Entity, b: &'static B, opt: Option<&'static Sparse>, } let custom_param_data = world .query::<FancyParam>() .iter(&world) .map(|fancy| (fancy.e, *fancy.b, fancy.opt.copied())) .collect::<Vec<_>>(); let normal_data = world .query::<(Entity, &B, Option<&Sparse>)>() .iter(&world) .map(|(e, b, opt)| (e, *b, opt.copied())) .collect::<Vec<_>>(); assert_eq!(custom_param_data, normal_data); } { #[derive(QueryData)] struct MaybeBSparse { blah: Option<(&'static B, &'static Sparse)>, } #[derive(QueryData)] struct MatchEverything { abcs: AnyOf<(&'static A, &'static B, &'static C)>, opt_bsparse: MaybeBSparse, } let custom_param_data = world .query::<MatchEverything>() .iter(&world) .map( |MatchEverythingItem { abcs: (a, b, c), opt_bsparse: MaybeBSparseItem { blah: bsparse }, }| { ( (a.copied(), b.copied(), c.copied()), bsparse.map(|(b, sparse)| (*b, *sparse)), ) }, ) .collect::<Vec<_>>(); let normal_data = world .query::<(AnyOf<(&A, &B, &C)>, Option<(&B, &Sparse)>)>() .iter(&world) .map(|((a, b, c), bsparse)| { ( (a.copied(), b.copied(), c.copied()), bsparse.map(|(b, sparse)| (*b, *sparse)), ) }) .collect::<Vec<_>>(); assert_eq!(custom_param_data, normal_data); } { #[derive(QueryFilter)] struct AOrBFilter { a: Or<(With<A>, With<B>)>, } #[derive(QueryFilter)] struct NoSparseThatsSlow { no: Without<Sparse>, } let custom_param_entities = world .query_filtered::<Entity, (AOrBFilter, NoSparseThatsSlow)>() .iter(&world) .collect::<Vec<_>>(); let normal_entities = world .query_filtered::<Entity, (Or<(With<A>, With<B>)>, Without<Sparse>)>() .iter(&world) .collect::<Vec<_>>(); assert_eq!(custom_param_entities, normal_entities); } { #[derive(QueryFilter)] struct CSparseFilter { tuple_structs_pls: With<C>, ugh: With<Sparse>, } let custom_param_entities = world .query_filtered::<Entity, CSparseFilter>() .iter(&world) .collect::<Vec<_>>(); let normal_entities = world .query_filtered::<Entity, (With<C>, With<Sparse>)>() .iter(&world) .collect::<Vec<_>>(); assert_eq!(custom_param_entities, normal_entities); } { #[derive(QueryFilter)] struct WithoutComps { _1: Without<A>, _2: Without<B>, _3: Without<C>, } let custom_param_entities = world .query_filtered::<Entity, WithoutComps>() .iter(&world) .collect::<Vec<_>>(); let normal_entities = world .query_filtered::<Entity, (Without<A>, Without<B>, Without<C>)>() .iter(&world) .collect::<Vec<_>>(); assert_eq!(custom_param_entities, normal_entities); } { #[derive(QueryData)] struct IterCombAB { a: &'static A, b: &'static B, } let custom_param_data = world .query::<IterCombAB>() .iter_combinations::<2>(&world) .map(|[item0, item1]| [(*item0.a, *item0.b), (*item1.a, *item1.b)]) .collect::<Vec<_>>(); let normal_data = world .query::<(&A, &B)>() .iter_combinations(&world) .map(|[(a0, b0), (a1, b1)]| [(*a0, *b0), (*a1, *b1)]) .collect::<Vec<_>>(); assert_eq!(custom_param_data, normal_data); } } #[test] fn many_entities() { let mut world = World::new(); world.spawn((A(0), B(0))); world.spawn((A(0), B(0))); world.spawn(A(0)); world.spawn(B(0)); { fn system(has_a: Query<Entity, With<A>>, has_a_and_b: Query<(&A, &B)>) { assert_eq!(has_a_and_b.iter_many(&has_a).count(), 2); } let mut system = IntoSystem::into_system(system); system.initialize(&mut world); system.run((), &mut world).unwrap(); } { fn system(has_a: Query<Entity, With<A>>, mut b_query: Query<&mut B>) { let mut iter = b_query.iter_many_mut(&has_a); while let Some(mut b) = iter.fetch_next() { b.0 = 1; } } let mut system = IntoSystem::into_system(system); system.initialize(&mut world); system.run((), &mut world).unwrap(); } { fn system(query: Query<(Option<&A>, &B)>) { for (maybe_a, b) in &query { match maybe_a { Some(_) => assert_eq!(b.0, 1), None => assert_eq!(b.0, 0), } } } let mut system = IntoSystem::into_system(system); system.initialize(&mut world); system.run((), &mut world).unwrap(); } } #[test] fn mut_to_immut_query_methods_have_immut_item() { #[derive(Component)] struct Foo; let mut world = World::new(); let e = world.spawn(Foo).id(); // state let mut q = world.query::<&mut Foo>(); let _: Option<&Foo> = q.iter(&world).next(); let _: Option<[&Foo; 2]> = q.iter_combinations::<2>(&world).next(); let _: Option<&Foo> = q.iter_manual(&world).next(); let _: Option<&Foo> = q.iter_many(&world, [e]).next(); q.iter(&world).for_each(|_: &Foo| ()); let _: Option<&Foo> = q.get(&world, e).ok(); let _: Option<&Foo> = q.get_manual(&world, e).ok(); let _: Option<[&Foo; 1]> = q.get_many(&world, [e]).ok(); let _: Option<&Foo> = q.single(&world).ok(); let _: &Foo = q.single(&world).unwrap(); // system param let mut q = SystemState::<Query<&mut Foo>>::new(&mut world); let q = q.get_mut(&mut world); let _: Option<&Foo> = q.iter().next(); let _: Option<[&Foo; 2]> = q.iter_combinations::<2>().next(); let _: Option<&Foo> = q.iter_many([e]).next(); q.iter().for_each(|_: &Foo| ()); let _: Option<&Foo> = q.get(e).ok(); let _: Option<[&Foo; 1]> = q.get_many([e]).ok(); let _: Option<&Foo> = q.single().ok(); let _: &Foo = q.single().unwrap(); } // regression test for https://github.com/bevyengine/bevy/pull/8029 #[test] fn par_iter_mut_change_detection() { let mut world = World::new(); world.spawn((A(1), B(1))); fn propagate_system(mut query: Query<(&A, &mut B), Changed<A>>) { query.par_iter_mut().for_each(|(a, mut b)| { b.0 = a.0; }); } fn modify_system(mut query: Query<&mut A>) { for mut a in &mut query { a.0 = 2; } } let mut schedule = Schedule::default(); schedule.add_systems((propagate_system, modify_system).chain()); schedule.run(&mut world); world.clear_trackers(); schedule.run(&mut world); world.clear_trackers(); let values = world.query::<&B>().iter(&world).collect::<Vec<&B>>(); assert_eq!(values, vec![&B(2)]); } #[derive(Resource)] struct R; /// `QueryData` that performs read access on R to test that resource access is tracked struct ReadsRData; /// SAFETY: /// `update_component_access` adds resource read access for `R`. unsafe impl WorldQuery for ReadsRData { type Fetch<'w> = (); type State = ComponentId; fn shrink_fetch<'wlong: 'wshort, 'wshort>(_: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {} unsafe fn init_fetch<'w, 's>( _world: UnsafeWorldCell<'w>, _state: &'s Self::State, _last_run: Tick, _this_run: Tick, ) -> Self::Fetch<'w> { } const IS_DENSE: bool = true; #[inline] unsafe fn set_archetype<'w, 's>( _fetch: &mut Self::Fetch<'w>, _state: &'s Self::State, _archetype: &'w Archetype, _table: &Table, ) { } #[inline] unsafe fn set_table<'w, 's>( _fetch: &mut Self::Fetch<'w>, _state: &'s Self::State, _table: &'w Table, ) { } fn update_component_access(&component_id: &Self::State, access: &mut FilteredAccess) { assert!( !access.access().has_resource_write(component_id), "ReadsRData conflicts with a previous access in this query. Shared access cannot coincide with exclusive access." ); access.add_resource_read(component_id); } fn init_state(world: &mut World) -> Self::State { world.components_registrator().register_resource::<R>() } fn get_state(components: &Components) -> Option<Self::State> { components.resource_id::<R>() } fn matches_component_set( _state: &Self::State, _set_contains_id: &impl Fn(ComponentId) -> bool, ) -> bool { true } } /// SAFETY: `Self` is the same as `Self::ReadOnly` unsafe impl QueryData for ReadsRData { const IS_READ_ONLY: bool = true; const IS_ARCHETYPAL: bool = true; type ReadOnly = Self; type Item<'w, 's> = (); fn shrink<'wlong: 'wshort, 'wshort, 's>( _item: Self::Item<'wlong, 's>, ) -> Self::Item<'wshort, 's> { } #[inline(always)] unsafe fn fetch<'w, 's>( _state: &'s Self::State, _fetch: &mut Self::Fetch<'w>, _entity: Entity, _table_row: TableRow, ) -> Option<Self::Item<'w, 's>> { Some(()) } fn iter_access( state: &Self::State, ) -> impl Iterator<Item = super::access_iter::EcsAccessType<'_>> { core::iter::once(super::access_iter::EcsAccessType::Resource( super::access_iter::ResourceAccessLevel::Read(*state), )) } } /// SAFETY: access is read only unsafe impl ReadOnlyQueryData for ReadsRData {} impl ArchetypeQueryData for ReadsRData {} #[test] fn read_res_read_res_no_conflict() { fn system(_q1: Query<ReadsRData, With<A>>, _q2: Query<ReadsRData, Without<A>>) {} assert_is_system(system); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/query/access_iter.rs
crates/bevy_ecs/src/query/access_iter.rs
use core::fmt::Display; use crate::{ component::{ComponentId, Components}, query::{Access, QueryData}, }; /// Check if `Q` has any internal conflicts. #[inline(never)] pub fn has_conflicts<Q: QueryData>(components: &Components) -> Result<(), QueryAccessError> { // increasing this too much may slow down smaller queries const MAX_SIZE: usize = 16; let Some(state) = Q::get_state(components) else { return Err(QueryAccessError::ComponentNotRegistered); }; let iter = Q::iter_access(&state).enumerate(); let size = iter.size_hint().1.unwrap_or(MAX_SIZE); if size > MAX_SIZE { for (i, access) in iter { for access_other in Q::iter_access(&state).take(i) { if let Err(err) = access.is_compatible(access_other) { panic!("{}", err); } } } } else { // we can optimize small sizes by caching the iteration result in an array on the stack let mut inner_access = [EcsAccessType::Empty; MAX_SIZE]; for (i, access) in iter { for access_other in inner_access.iter().take(i) { if let Err(err) = access.is_compatible(*access_other) { panic!("{}", err); } } inner_access[i] = access; } } Ok(()) } /// The data storage type that is being accessed. #[derive(Copy, Clone, Debug, PartialEq)] pub enum EcsAccessType<'a> { /// Accesses [`Component`](crate::prelude::Component) data Component(EcsAccessLevel), /// Accesses [`Resource`](crate::prelude::Resource) data Resource(ResourceAccessLevel), /// borrowed access from [`WorldQuery::State`](crate::query::WorldQuery) Access(&'a Access), /// Does not access any data that can conflict. Empty, } impl<'a> EcsAccessType<'a> { /// Returns `Ok(())` if `self` and `other` are compatible. Returns a [`AccessConflictError`] otherwise. #[inline(never)] pub fn is_compatible(&self, other: Self) -> Result<(), AccessConflictError<'_>> { use EcsAccessLevel::*; use EcsAccessType::*; match (*self, other) { (Component(ReadAll), Component(Write(_))) | (Component(Write(_)), Component(ReadAll)) | (Component(_), Component(WriteAll)) | (Component(WriteAll), Component(_)) => Err(AccessConflictError(*self, other)), (Empty, _) | (_, Empty) | (Component(_), Resource(_)) | (Resource(_), Component(_)) // read only access doesn't conflict | (Component(Read(_)), Component(Read(_))) | (Component(ReadAll), Component(Read(_))) | (Component(Read(_)), Component(ReadAll)) | (Component(ReadAll), Component(ReadAll)) | (Resource(ResourceAccessLevel::Read(_)), Resource(ResourceAccessLevel::Read(_))) => { Ok(()) } (Component(Read(id)), Component(Write(id_other))) | (Component(Write(id)), Component(Read(id_other))) | (Component(Write(id)), Component(Write(id_other))) | ( Resource(ResourceAccessLevel::Read(id)), Resource(ResourceAccessLevel::Write(id_other)), ) | ( Resource(ResourceAccessLevel::Write(id)), Resource(ResourceAccessLevel::Read(id_other)), ) | ( Resource(ResourceAccessLevel::Write(id)), Resource(ResourceAccessLevel::Write(id_other)), ) => if id == id_other { Err(AccessConflictError(*self, other)) } else { Ok(()) }, // Borrowed Access (Component(Read(component_id)), Access(access)) | (Access(access), Component(Read(component_id))) => if access.has_component_write(component_id) { Err(AccessConflictError(*self, other)) } else { Ok(()) }, (Component(Write(component_id)), Access(access)) | (Access(access), Component(Write(component_id))) => if access.has_component_read(component_id) { Err(AccessConflictError(*self, other)) } else { Ok(()) }, (Component(ReadAll), Access(access)) | (Access(access), Component(ReadAll)) => if access.has_any_component_write() { Err(AccessConflictError(*self, other)) } else { Ok(()) }, (Component(WriteAll), Access(access)) | (Access(access), Component(WriteAll))=> if access.has_any_component_read() { Err(AccessConflictError(*self, other)) } else { Ok(()) }, (Resource(ResourceAccessLevel::Read(component_id)), Access(access)) | (Access(access), Resource(ResourceAccessLevel::Read(component_id))) => if access.has_resource_write(component_id) { Err(AccessConflictError(*self, other)) } else { Ok(()) }, (Resource(ResourceAccessLevel::Write(component_id)), Access(access)) | (Access(access), Resource(ResourceAccessLevel::Write(component_id))) => if access.has_resource_read(component_id) { Err(AccessConflictError(*self, other)) } else { Ok(()) }, (Access(access), Access(other_access)) => if access.is_compatible(other_access) { Ok(()) } else { Err(AccessConflictError(*self, other)) }, } } } /// The way the data will be accessed and whether we take access on all the components on /// an entity or just one component. #[derive(Clone, Copy, Debug, PartialEq)] pub enum EcsAccessLevel { /// Reads [`Component`](crate::prelude::Component) with [`ComponentId`] Read(ComponentId), /// Writes [`Component`](crate::prelude::Component) with [`ComponentId`] Write(ComponentId), /// Potentially reads all [`Component`](crate::prelude::Component)'s in the [`World`](crate::prelude::World) ReadAll, /// Potentially writes all [`Component`](crate::prelude::Component)'s in the [`World`](crate::prelude::World) WriteAll, } /// Access level needed by [`QueryData`] fetch to the resource. #[derive(Copy, Clone, Debug, PartialEq)] pub enum ResourceAccessLevel { /// Reads the resource with [`ComponentId`] Read(ComponentId), /// Writes the resource with [`ComponentId`] Write(ComponentId), } /// Error returned from [`EcsAccessType::is_compatible`] pub struct AccessConflictError<'a>(EcsAccessType<'a>, EcsAccessType<'a>); impl Display for AccessConflictError<'_> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { use EcsAccessLevel::*; use EcsAccessType::*; let AccessConflictError(a, b) = self; match (a, b) { // ReadAll/WriteAll + Component conflicts (Component(ReadAll), Component(Write(id))) | (Component(Write(id)), Component(ReadAll)) => { write!( f, "Component read all access conflicts with component {id:?} write." ) } (Component(WriteAll), Component(Write(id))) | (Component(Write(id)), Component(WriteAll)) => { write!( f, "Component write all access conflicts with component {id:?} write." ) } (Component(WriteAll), Component(Read(id))) | (Component(Read(id)), Component(WriteAll)) => { write!( f, "Component write all access conflicts with component {id:?} read." ) } (Component(WriteAll), Component(ReadAll)) | (Component(ReadAll), Component(WriteAll)) => { write!(f, "Component write all conflicts with component read all.") } (Component(WriteAll), Component(WriteAll)) => { write!(f, "Component write all conflicts with component write all.") } // Component + Component conflicts (Component(Read(id)), Component(Write(id_other))) | (Component(Write(id_other)), Component(Read(id))) => write!( f, "Component {id:?} read conflicts with component {id_other:?} write." ), (Component(Write(id)), Component(Write(id_other))) => write!( f, "Component {id:?} write conflicts with component {id_other:?} write." ), // Borrowed Access conflicts (Access(_), Component(Read(id))) | (Component(Read(id)), Access(_)) => write!( f, "Access has a write that conflicts with component {id:?} read." ), (Access(_), Component(Write(id))) | (Component(Write(id)), Access(_)) => write!( f, "Access has a read that conflicts with component {id:?} write." ), (Access(_), Component(ReadAll)) | (Component(ReadAll), Access(_)) => write!( f, "Access has a write that conflicts with component read all" ), (Access(_), Component(WriteAll)) | (Component(WriteAll), Access(_)) => write!( f, "Access has a read that conflicts with component write all" ), (Access(_), Resource(ResourceAccessLevel::Read(id))) | (Resource(ResourceAccessLevel::Read(id)), Access(_)) => write!( f, "Access has a write that conflicts with resource {id:?} read." ), (Access(_), Resource(ResourceAccessLevel::Write(id))) | (Resource(ResourceAccessLevel::Write(id)), Access(_)) => write!( f, "Access has a read that conflicts with resource {id:?} write." ), (Access(_), Access(_)) => write!(f, "Access conflicts with other Access"), _ => { unreachable!("Other accesses should be compatible"); } } } } /// Error returned from [`has_conflicts`]. #[derive(Clone, Copy, Debug, PartialEq)] pub enum QueryAccessError { /// Component was not registered on world ComponentNotRegistered, /// Entity did not have the requested components EntityDoesNotMatch, } impl core::error::Error for QueryAccessError {} impl Display for QueryAccessError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match *self { QueryAccessError::ComponentNotRegistered => { write!( f, "At least one component in Q was not registered in world. Consider calling `World::register_component`" ) } QueryAccessError::EntityDoesNotMatch => { write!(f, "Entity does not match Q") } } } } #[cfg(test)] mod tests { use super::*; use crate::{ prelude::Component, world::{EntityMut, EntityMutExcept, EntityRef, EntityRefExcept, World}, }; #[derive(Component)] struct C1; #[derive(Component)] struct C2; fn setup_world() -> World { let world = World::new(); let mut world = world; world.register_component::<C1>(); world.register_component::<C2>(); world } #[test] fn simple_compatible() { let world = setup_world(); let c = world.components(); // Compatible assert!(has_conflicts::<&mut C1>(c).is_ok()); assert!(has_conflicts::<&C1>(c).is_ok()); assert!(has_conflicts::<(&C1, &C1)>(c).is_ok()); } #[test] #[should_panic(expected = "conflicts")] fn conflict_component_read_conflicts_write() { let _ = has_conflicts::<(&C1, &mut C1)>(setup_world().components()); } #[test] #[should_panic(expected = "conflicts")] fn conflict_component_write_conflicts_read() { let _ = has_conflicts::<(&mut C1, &C1)>(setup_world().components()); } #[test] #[should_panic(expected = "conflicts")] fn conflict_component_write_conflicts_write() { let _ = has_conflicts::<(&mut C1, &mut C1)>(setup_world().components()); } #[test] fn entity_ref_compatible() { let world = setup_world(); let c = world.components(); // Compatible assert!(has_conflicts::<(EntityRef, &C1)>(c).is_ok()); assert!(has_conflicts::<(&C1, EntityRef)>(c).is_ok()); assert!(has_conflicts::<(EntityRef, EntityRef)>(c).is_ok()); } #[test] #[should_panic(expected = "conflicts")] fn entity_ref_conflicts_component_write() { let _ = has_conflicts::<(EntityRef, &mut C1)>(setup_world().components()); } #[test] #[should_panic(expected = "conflicts")] fn component_write_conflicts_entity_ref() { let _ = has_conflicts::<(&mut C1, EntityRef)>(setup_world().components()); } #[test] #[should_panic(expected = "conflicts")] fn entity_mut_conflicts_component_read() { let _ = has_conflicts::<(EntityMut, &C1)>(setup_world().components()); } #[test] #[should_panic(expected = "conflicts")] fn component_read_conflicts_entity_mut() { let _ = has_conflicts::<(&C1, EntityMut)>(setup_world().components()); } #[test] #[should_panic(expected = "conflicts")] fn entity_mut_conflicts_component_write() { let _ = has_conflicts::<(EntityMut, &mut C1)>(setup_world().components()); } #[test] #[should_panic(expected = "conflicts")] fn component_write_conflicts_entity_mut() { let _ = has_conflicts::<(&mut C1, EntityMut)>(setup_world().components()); } #[test] #[should_panic(expected = "conflicts")] fn entity_mut_conflicts_entity_ref() { let _ = has_conflicts::<(EntityMut, EntityRef)>(setup_world().components()); } #[test] #[should_panic(expected = "conflicts")] fn entity_ref_conflicts_entity_mut() { let _ = has_conflicts::<(EntityRef, EntityMut)>(setup_world().components()); } #[test] fn entity_ref_except_compatible() { let world = setup_world(); let c = world.components(); // Compatible assert!(has_conflicts::<(EntityRefExcept<C1>, &mut C1)>(c).is_ok()); assert!(has_conflicts::<(&mut C1, EntityRefExcept<C1>)>(c).is_ok()); assert!(has_conflicts::<(&C2, EntityRefExcept<C1>)>(c).is_ok()); assert!(has_conflicts::<(&mut C1, EntityRefExcept<(C1, C2)>,)>(c).is_ok()); assert!(has_conflicts::<(EntityRefExcept<(C1, C2)>, &mut C1,)>(c).is_ok()); assert!(has_conflicts::<(&mut C1, &mut C2, EntityRefExcept<(C1, C2)>,)>(c).is_ok()); assert!(has_conflicts::<(&mut C1, EntityRefExcept<(C1, C2)>, &mut C2,)>(c).is_ok()); assert!(has_conflicts::<(EntityRefExcept<(C1, C2)>, &mut C1, &mut C2,)>(c).is_ok()); } #[test] #[should_panic(expected = "conflicts")] fn entity_ref_except_conflicts_component_write() { let _ = has_conflicts::<(EntityRefExcept<C1>, &mut C2)>(setup_world().components()); } #[test] #[should_panic(expected = "conflicts")] fn component_write_conflicts_entity_ref_except() { let _ = has_conflicts::<(&mut C2, EntityRefExcept<C1>)>(setup_world().components()); } #[test] fn entity_mut_except_compatible() { let world = setup_world(); let c = world.components(); // Compatible assert!(has_conflicts::<(EntityMutExcept<C1>, &mut C1)>(c).is_ok()); assert!(has_conflicts::<(&mut C1, EntityMutExcept<C1>)>(c).is_ok()); assert!(has_conflicts::<(&mut C1, EntityMutExcept<(C1, C2)>,)>(c).is_ok()); assert!(has_conflicts::<(EntityMutExcept<(C1, C2)>, &mut C1,)>(c).is_ok()); assert!(has_conflicts::<(&mut C1, &mut C2, EntityMutExcept<(C1, C2)>,)>(c).is_ok()); assert!(has_conflicts::<(&mut C1, EntityMutExcept<(C1, C2)>, &mut C2,)>(c).is_ok()); assert!(has_conflicts::<(EntityMutExcept<(C1, C2)>, &mut C1, &mut C2,)>(c).is_ok()); } #[test] #[should_panic(expected = "conflicts")] fn entity_mut_except_conflicts_component_read() { let _ = has_conflicts::<(EntityMutExcept<C1>, &C2)>(setup_world().components()); } #[test] #[should_panic(expected = "conflicts")] fn component_read_conflicts_entity_mut_except() { let _ = has_conflicts::<(&C2, EntityMutExcept<C1>)>(setup_world().components()); } #[test] #[should_panic(expected = "conflicts")] fn entity_mut_except_conflicts_component_write() { let _ = has_conflicts::<(EntityMutExcept<C1>, &mut C2)>(setup_world().components()); } #[test] #[should_panic(expected = "conflicts")] fn component_write_conflicts_entity_mut_except() { let _ = has_conflicts::<(&mut C2, EntityMutExcept<C1>)>(setup_world().components()); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/query/iter.rs
crates/bevy_ecs/src/query/iter.rs
use super::{QueryData, QueryFilter, ReadOnlyQueryData}; use crate::{ archetype::{Archetype, ArchetypeEntity, Archetypes}, bundle::Bundle, change_detection::Tick, entity::{ContainsEntity, Entities, Entity, EntityEquivalent, EntitySet, EntitySetIterator}, query::{ArchetypeFilter, ArchetypeQueryData, DebugCheckedUnwrap, QueryState, StorageId}, storage::{Table, TableRow, Tables}, world::{ unsafe_world_cell::UnsafeWorldCell, EntityMut, EntityMutExcept, EntityRef, EntityRefExcept, FilteredEntityMut, FilteredEntityRef, }, }; use alloc::vec::Vec; use core::{ cmp::Ordering, fmt::{self, Debug, Formatter}, iter::FusedIterator, mem::MaybeUninit, ops::Range, }; use nonmax::NonMaxU32; /// An [`Iterator`] over query results of a [`Query`](crate::system::Query). /// /// This struct is created by the [`Query::iter`](crate::system::Query::iter) and /// [`Query::iter_mut`](crate::system::Query::iter_mut) methods. pub struct QueryIter<'w, 's, D: QueryData, F: QueryFilter> { world: UnsafeWorldCell<'w>, tables: &'w Tables, archetypes: &'w Archetypes, query_state: &'s QueryState<D, F>, cursor: QueryIterationCursor<'w, 's, D, F>, } impl<'w, 's, D: QueryData, F: QueryFilter> QueryIter<'w, 's, D, F> { /// # Safety /// - `world` must have permission to access any of the components registered in `query_state`. /// - `world` must be the same one used to initialize `query_state`. pub(crate) unsafe fn new( world: UnsafeWorldCell<'w>, query_state: &'s QueryState<D, F>, last_run: Tick, this_run: Tick, ) -> Self { QueryIter { world, query_state, // SAFETY: We only access table data that has been registered in `query_state`. tables: unsafe { &world.storages().tables }, archetypes: world.archetypes(), // SAFETY: The invariants are upheld by the caller. cursor: unsafe { QueryIterationCursor::init(world, query_state, last_run, this_run) }, } } /// Creates a new separate iterator yielding the same remaining items of the current one. /// Advancing the new iterator will not advance the original one, which will resume at the /// point it was left at. /// /// Differently from [`remaining_mut`](QueryIter::remaining_mut) the new iterator does not /// borrow from the original one. However it can only be called from an iterator over read only /// items. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct ComponentA; /// /// fn combinations(query: Query<&ComponentA>) { /// let mut iter = query.iter(); /// while let Some(a) = iter.next() { /// for b in iter.remaining() { /// // Check every combination (a, b) /// } /// } /// } /// ``` pub fn remaining(&self) -> QueryIter<'w, 's, D, F> where D: ReadOnlyQueryData, { QueryIter { world: self.world, tables: self.tables, archetypes: self.archetypes, query_state: self.query_state, cursor: self.cursor.clone(), } } /// Creates a new separate iterator yielding the same remaining items of the current one. /// Advancing the new iterator will not advance the original one, which will resume at the /// point it was left at. /// /// This method can be called on iterators over mutable items. However the original iterator /// will be borrowed while the new iterator exists and will thus not be usable in that timespan. /// /// # Example /// /// ``` /// # use bevy_ecs::prelude::*; /// # /// # #[derive(Component)] /// # struct ComponentA; /// /// fn combinations(mut query: Query<&mut ComponentA>) { /// let mut iter = query.iter_mut(); /// while let Some(a) = iter.next() { /// for b in iter.remaining_mut() { /// // Check every combination (a, b) /// } /// } /// } /// ``` pub fn remaining_mut(&mut self) -> QueryIter<'_, 's, D, F> { QueryIter { world: self.world, tables: self.tables, archetypes: self.archetypes, query_state: self.query_state, cursor: self.cursor.reborrow(), } } /// Executes the equivalent of [`Iterator::fold`] over a contiguous segment /// from a storage. /// /// # Safety /// - `range` must be in `[0, storage::entity_count)` or None. #[inline] pub(super) unsafe fn fold_over_storage_range<B, Func>( &mut self, mut accum: B, func: &mut Func, storage: StorageId, range: Option<Range<u32>>, ) -> B where Func: FnMut(B, D::Item<'w, 's>) -> B, { if self.cursor.is_dense { // SAFETY: `self.cursor.is_dense` is true, so storage ids are guaranteed to be table ids. let table_id = unsafe { storage.table_id }; // SAFETY: Matched table IDs are guaranteed to still exist. let table = unsafe { self.tables.get(table_id).debug_checked_unwrap() }; let range = range.unwrap_or(0..table.entity_count()); accum = // SAFETY: // - The fetched table matches both D and F // - caller ensures `range` is within `[0, table.entity_count)` // - The if block ensures that the query iteration is dense unsafe { self.fold_over_table_range(accum, func, table, range) }; } else { // SAFETY: `self.cursor.is_dense` is false, so storage ids are guaranteed to be archetype ids. let archetype_id = unsafe { storage.archetype_id }; // SAFETY: Matched archetype IDs are guaranteed to still exist. let archetype = unsafe { self.archetypes.get(archetype_id).debug_checked_unwrap() }; // SAFETY: Matched table IDs are guaranteed to still exist. let table = unsafe { self.tables.get(archetype.table_id()).debug_checked_unwrap() }; let range = range.unwrap_or(0..archetype.len()); // When an archetype and its table have equal entity counts, dense iteration can be safely used. // this leverages cache locality to optimize performance. if table.entity_count() == archetype.len() { accum = // SAFETY: // - The fetched archetype matches both D and F // - The provided archetype and its' table have the same length. // - caller ensures `range` is within `[0, archetype.len)` // - The if block ensures that the query iteration is not dense. unsafe { self.fold_over_dense_archetype_range(accum, func, archetype,range) }; } else { accum = // SAFETY: // - The fetched archetype matches both D and F // - caller ensures `range` is within `[0, archetype.len)` // - The if block ensures that the query iteration is not dense. unsafe { self.fold_over_archetype_range(accum, func, archetype,range) }; } } accum } /// Executes the equivalent of [`Iterator::fold`] over a contiguous segment /// from a table. /// /// # Safety /// - all `rows` must be in `[0, table.entity_count)`. /// - `table` must match D and F /// - The query iteration must be dense (i.e. `self.query_state.is_dense` must be true). #[inline] pub(super) unsafe fn fold_over_table_range<B, Func>( &mut self, mut accum: B, func: &mut Func, table: &'w Table, rows: Range<u32>, ) -> B where Func: FnMut(B, D::Item<'w, 's>) -> B, { if table.is_empty() { return accum; } D::set_table(&mut self.cursor.fetch, &self.query_state.fetch_state, table); F::set_table( &mut self.cursor.filter, &self.query_state.filter_state, table, ); let entities = table.entities(); for row in rows { // SAFETY: Caller assures `row` in range of the current archetype. let entity = unsafe { entities.get_unchecked(row as usize) }; // SAFETY: This is from an exclusive range, so it can't be max. let row = unsafe { TableRow::new(NonMaxU32::new_unchecked(row)) }; // SAFETY: set_table was called prior. // Caller assures `row` in range of the current archetype. let fetched = unsafe { !F::filter_fetch( &self.query_state.filter_state, &mut self.cursor.filter, *entity, row, ) }; if fetched { continue; } // SAFETY: set_table was called prior. // Caller assures `row` in range of the current archetype. if let Some(item) = D::fetch( &self.query_state.fetch_state, &mut self.cursor.fetch, *entity, row, ) { accum = func(accum, item); } } accum } /// Executes the equivalent of [`Iterator::fold`] over a contiguous segment /// from an archetype. /// /// # Safety /// - all `indices` must be in `[0, archetype.len())`. /// - `archetype` must match D and F /// - The query iteration must not be dense (i.e. `self.query_state.is_dense` must be false). #[inline] pub(super) unsafe fn fold_over_archetype_range<B, Func>( &mut self, mut accum: B, func: &mut Func, archetype: &'w Archetype, indices: Range<u32>, ) -> B where Func: FnMut(B, D::Item<'w, 's>) -> B, { if archetype.is_empty() { return accum; } let table = self.tables.get(archetype.table_id()).debug_checked_unwrap(); D::set_archetype( &mut self.cursor.fetch, &self.query_state.fetch_state, archetype, table, ); F::set_archetype( &mut self.cursor.filter, &self.query_state.filter_state, archetype, table, ); let entities = archetype.entities(); for index in indices { // SAFETY: Caller assures `index` in range of the current archetype. let archetype_entity = unsafe { entities.get_unchecked(index as usize) }; // SAFETY: set_archetype was called prior. // Caller assures `index` in range of the current archetype. let fetched = unsafe { !F::filter_fetch( &self.query_state.filter_state, &mut self.cursor.filter, archetype_entity.id(), archetype_entity.table_row(), ) }; if fetched { continue; } // SAFETY: set_archetype was called prior, `index` is an archetype index in range of the current archetype // Caller assures `index` in range of the current archetype. if let Some(item) = unsafe { D::fetch( &self.query_state.fetch_state, &mut self.cursor.fetch, archetype_entity.id(), archetype_entity.table_row(), ) } { accum = func(accum, item); } } accum } /// Executes the equivalent of [`Iterator::fold`] over a contiguous segment /// from an archetype which has the same entity count as its table. /// /// # Safety /// - all `indices` must be in `[0, archetype.len())`. /// - `archetype` must match D and F /// - `archetype` must have the same length as its table. /// - The query iteration must not be dense (i.e. `self.query_state.is_dense` must be false). #[inline] pub(super) unsafe fn fold_over_dense_archetype_range<B, Func>( &mut self, mut accum: B, func: &mut Func, archetype: &'w Archetype, rows: Range<u32>, ) -> B where Func: FnMut(B, D::Item<'w, 's>) -> B, { if archetype.is_empty() { return accum; } let table = self.tables.get(archetype.table_id()).debug_checked_unwrap(); debug_assert!( archetype.len() == table.entity_count(), "archetype and its table must have the same length. " ); D::set_archetype( &mut self.cursor.fetch, &self.query_state.fetch_state, archetype, table, ); F::set_archetype( &mut self.cursor.filter, &self.query_state.filter_state, archetype, table, ); let entities = table.entities(); for row in rows { // SAFETY: Caller assures `row` in range of the current archetype. let entity = unsafe { *entities.get_unchecked(row as usize) }; // SAFETY: This is from an exclusive range, so it can't be max. let row = unsafe { TableRow::new(NonMaxU32::new_unchecked(row)) }; // SAFETY: set_table was called prior. // Caller assures `row` in range of the current archetype. let filter_matched = unsafe { F::filter_fetch( &self.query_state.filter_state, &mut self.cursor.filter, entity, row, ) }; if !filter_matched { continue; } // SAFETY: set_table was called prior. // Caller assures `row` in range of the current archetype. if let Some(item) = D::fetch( &self.query_state.fetch_state, &mut self.cursor.fetch, entity, row, ) { accum = func(accum, item); } } accum } /// Sorts all query items into a new iterator, using the query lens as a key. /// /// This sort is stable (i.e., does not reorder equal elements). /// /// This uses [`slice::sort`] internally. /// /// Defining the lens works like [`transmute_lens`](crate::system::Query::transmute_lens). /// This includes the allowed parameter type changes listed under [allowed transmutes]. /// However, the lens uses the filter of the original query when present. /// /// The sort is not cached across system runs. /// /// [allowed transmutes]: crate::system::Query#allowed-transmutes /// /// # Panics /// /// This will panic if `next` has been called on `QueryIter` before, unless the underlying `Query` is empty. /// /// # Examples /// ```rust /// # use bevy_ecs::prelude::*; /// # use std::{ops::{Deref, DerefMut}, iter::Sum}; /// # /// # #[derive(Component)] /// # struct PartMarker; /// # /// # #[derive(Component, PartialEq, Eq, PartialOrd, Ord)] /// # struct PartIndex(usize); /// # /// # #[derive(Component, Clone, Copy)] /// # struct PartValue(f32); /// # /// # impl Deref for PartValue { /// # type Target = f32; /// # /// # fn deref(&self) -> &Self::Target { /// # &self.0 /// # } /// # } /// # /// # #[derive(Component)] /// # struct ParentValue(f32); /// # /// # impl Deref for ParentValue { /// # type Target = f32; /// # /// # fn deref(&self) -> &Self::Target { /// # &self.0 /// # } /// # } /// # /// # impl DerefMut for ParentValue { /// # fn deref_mut(&mut self) -> &mut Self::Target { /// # &mut self.0 /// # } /// # } /// # /// # #[derive(Component, Debug, PartialEq, Eq, PartialOrd, Ord)] /// # struct Length(usize); /// # /// # #[derive(Component, Debug, PartialEq, Eq, PartialOrd, Ord)] /// # struct Width(usize); /// # /// # #[derive(Component, Debug, PartialEq, Eq, PartialOrd, Ord)] /// # struct Height(usize); /// # /// # #[derive(Component, PartialEq, Eq, PartialOrd, Ord)] /// # struct ParentEntity(Entity); /// # /// # #[derive(Component, Clone, Copy)] /// # struct ChildPartCount(usize); /// # /// # impl Deref for ChildPartCount { /// # type Target = usize; /// # /// # fn deref(&self) -> &Self::Target { /// # &self.0 /// # } /// # } /// # let mut world = World::new(); /// // We can ensure that a query always returns in the same order. /// fn system_1(query: Query<(Entity, &PartIndex)>) { /// let parts: Vec<(Entity, &PartIndex)> = query.iter().sort::<&PartIndex>().collect(); /// } /// /// // We can freely rearrange query components in the key. /// fn system_2(query: Query<(&Length, &Width, &Height), With<PartMarker>>) { /// for (length, width, height) in query.iter().sort::<(&Height, &Length, &Width)>() { /// println!("height: {height:?}, width: {width:?}, length: {length:?}") /// } /// } /// /// // We can sort by Entity without including it in the original Query. /// // Here, we match iteration orders between query iterators. /// fn system_3( /// part_query: Query<(&PartValue, &ParentEntity)>, /// mut parent_query: Query<(&ChildPartCount, &mut ParentValue)>, /// ) { /// let part_values = &mut part_query /// .into_iter() /// .sort::<&ParentEntity>() /// .map(|(&value, parent_entity)| *value); /// /// for (&child_count, mut parent_value) in parent_query.iter_mut().sort::<Entity>() { /// **parent_value = part_values.take(*child_count).sum(); /// } /// } /// # /// # let mut schedule = Schedule::default(); /// # schedule.add_systems((system_1, system_2, system_3)); /// # schedule.run(&mut world); /// ``` pub fn sort<L: ReadOnlyQueryData + 'w>( self, ) -> QuerySortedIter< 'w, 's, D, F, impl ExactSizeIterator<Item = Entity> + DoubleEndedIterator + FusedIterator + 'w, > where for<'lw, 'ls> L::Item<'lw, 'ls>: Ord, { self.sort_impl::<L>(|keyed_query| keyed_query.sort()) } /// Sorts all query items into a new iterator, using the query lens as a key. /// /// This sort is unstable (i.e., may reorder equal elements). /// /// This uses [`slice::sort_unstable`] internally. /// /// Defining the lens works like [`transmute_lens`](crate::system::Query::transmute_lens). /// This includes the allowed parameter type changes listed under [allowed transmutes].. /// However, the lens uses the filter of the original query when present. /// /// The sort is not cached across system runs. /// /// [allowed transmutes]: crate::system::Query#allowed-transmutes /// /// # Panics /// /// This will panic if `next` has been called on `QueryIter` before, unless the underlying `Query` is empty. /// /// # Example /// ``` /// # use bevy_ecs::prelude::*; /// # /// # let mut world = World::new(); /// # /// # #[derive(Component)] /// # struct PartMarker; /// # /// #[derive(Component, PartialEq, Eq, PartialOrd, Ord)] /// enum Flying { /// Enabled, /// Disabled /// }; /// /// // We perform an unstable sort by a Component with few values. /// fn system_1(query: Query<&Flying, With<PartMarker>>) { /// let part_values: Vec<&Flying> = query.iter().sort_unstable::<&Flying>().collect(); /// } /// # /// # let mut schedule = Schedule::default(); /// # schedule.add_systems((system_1)); /// # schedule.run(&mut world); /// ``` pub fn sort_unstable<L: ReadOnlyQueryData + 'w>( self, ) -> QuerySortedIter< 'w, 's, D, F, impl ExactSizeIterator<Item = Entity> + DoubleEndedIterator + FusedIterator + 'w, > where for<'lw, 'ls> L::Item<'lw, 'ls>: Ord, { self.sort_impl::<L>(|keyed_query| keyed_query.sort_unstable()) } /// Sorts all query items into a new iterator with a comparator function over the query lens. /// /// This sort is stable (i.e., does not reorder equal elements). /// /// This uses [`slice::sort_by`] internally. /// /// Defining the lens works like [`transmute_lens`](crate::system::Query::transmute_lens). /// This includes the allowed parameter type changes listed under [allowed transmutes]. /// However, the lens uses the filter of the original query when present. /// /// The sort is not cached across system runs. /// /// [allowed transmutes]: crate::system::Query#allowed-transmutes /// /// # Panics /// /// This will panic if `next` has been called on `QueryIter` before, unless the underlying `Query` is empty. /// /// # Example /// ``` /// # use bevy_ecs::prelude::*; /// # use std::ops::Deref; /// # /// # impl Deref for PartValue { /// # type Target = f32; /// # /// # fn deref(&self) -> &Self::Target { /// # &self.0 /// # } /// # } /// # /// # let mut world = World::new(); /// # /// #[derive(Component)] /// struct PartValue(f32); /// /// // We can use a cmp function on components do not implement Ord. /// fn system_1(query: Query<&PartValue>) { /// // Sort part values according to `f32::total_comp`. /// let part_values: Vec<&PartValue> = query /// .iter() /// .sort_by::<&PartValue>(|value_1, value_2| value_1.total_cmp(*value_2)) /// .collect(); /// } /// # /// # let mut schedule = Schedule::default(); /// # schedule.add_systems((system_1)); /// # schedule.run(&mut world); /// ``` pub fn sort_by<L: ReadOnlyQueryData + 'w>( self, mut compare: impl FnMut(&L::Item<'_, '_>, &L::Item<'_, '_>) -> Ordering, ) -> QuerySortedIter< 'w, 's, D, F, impl ExactSizeIterator<Item = Entity> + DoubleEndedIterator + FusedIterator + 'w, > { self.sort_impl::<L>(move |keyed_query| { keyed_query.sort_by(|(key_1, _), (key_2, _)| compare(key_1, key_2)); }) } /// Sorts all query items into a new iterator with a comparator function over the query lens. /// /// This sort is unstable (i.e., may reorder equal elements). /// /// This uses [`slice::sort_unstable_by`] internally. /// /// Defining the lens works like [`transmute_lens`](crate::system::Query::transmute_lens). /// This includes the allowed parameter type changes listed under [allowed transmutes]. /// However, the lens uses the filter of the original query when present. /// /// The sort is not cached across system runs. /// /// [allowed transmutes]: crate::system::Query#allowed-transmutes /// /// # Panics /// /// This will panic if `next` has been called on `QueryIter` before, unless the underlying `Query` is empty. pub fn sort_unstable_by<L: ReadOnlyQueryData + 'w>( self, mut compare: impl FnMut(&L::Item<'_, '_>, &L::Item<'_, '_>) -> Ordering, ) -> QuerySortedIter< 'w, 's, D, F, impl ExactSizeIterator<Item = Entity> + DoubleEndedIterator + FusedIterator + 'w, > { self.sort_impl::<L>(move |keyed_query| { keyed_query.sort_unstable_by(|(key_1, _), (key_2, _)| compare(key_1, key_2)); }) } /// Sorts all query items into a new iterator with a key extraction function over the query lens. /// /// This sort is stable (i.e., does not reorder equal elements). /// /// This uses [`slice::sort_by_key`] internally. /// /// Defining the lens works like [`transmute_lens`](crate::system::Query::transmute_lens). /// This includes the allowed parameter type changes listed under [allowed transmutes]. /// However, the lens uses the filter of the original query when present. /// /// The sort is not cached across system runs. /// /// [allowed transmutes]: crate::system::Query#allowed-transmutes /// /// # Panics /// /// This will panic if `next` has been called on `QueryIter` before, unless the underlying `Query` is empty. /// /// # Example /// ``` /// # use bevy_ecs::prelude::*; /// # use std::ops::Deref; /// # /// # #[derive(Component)] /// # struct PartMarker; /// # /// # impl Deref for PartValue { /// # type Target = f32; /// # /// # fn deref(&self) -> &Self::Target { /// # &self.0 /// # } /// # } /// # /// # let mut world = World::new(); /// # /// #[derive(Component)] /// struct AvailableMarker; /// /// #[derive(Component, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] /// enum Rarity { /// Common, /// Rare, /// Epic, /// Legendary /// }; /// /// #[derive(Component)] /// struct PartValue(f32); /// /// // We can sort with the internals of components that do not implement Ord. /// fn system_1(query: Query<(Entity, &PartValue)>) { /// // Sort by the sines of the part values. /// let parts: Vec<(Entity, &PartValue)> = query /// .iter() /// .sort_by_key::<&PartValue, _>(|value| value.sin() as usize) /// .collect(); /// } /// /// // We can define our own custom comparison functions over an EntityRef. /// fn system_2(query: Query<EntityRef, With<PartMarker>>) { /// // Sort by whether parts are available and their rarity. /// // We want the available legendaries to come first, so we reverse the iterator. /// let parts: Vec<EntityRef> = query.iter() /// .sort_by_key::<EntityRef, _>(|entity_ref| { /// ( /// entity_ref.contains::<AvailableMarker>(), /// entity_ref.get::<Rarity>().copied() /// ) /// }) /// .rev() /// .collect(); /// } /// # let mut schedule = Schedule::default(); /// # schedule.add_systems((system_1, system_2)); /// # schedule.run(&mut world); /// ``` pub fn sort_by_key<L: ReadOnlyQueryData + 'w, K>( self, mut f: impl FnMut(&L::Item<'_, '_>) -> K, ) -> QuerySortedIter< 'w, 's, D, F, impl ExactSizeIterator<Item = Entity> + DoubleEndedIterator + FusedIterator + 'w, > where K: Ord, { self.sort_impl::<L>(move |keyed_query| keyed_query.sort_by_key(|(lens, _)| f(lens))) } /// Sorts all query items into a new iterator with a key extraction function over the query lens. /// /// This sort is unstable (i.e., may reorder equal elements). /// /// This uses [`slice::sort_unstable_by_key`] internally. /// /// Defining the lens works like [`transmute_lens`](crate::system::Query::transmute_lens). /// This includes the allowed parameter type changes listed under [allowed transmutes]. /// However, the lens uses the filter of the original query when present. /// /// The sort is not cached across system runs. /// /// [allowed transmutes]: crate::system::Query#allowed-transmutes /// /// # Panics /// /// This will panic if `next` has been called on `QueryIter` before, unless the underlying `Query` is empty. pub fn sort_unstable_by_key<L: ReadOnlyQueryData + 'w, K>( self, mut f: impl FnMut(&L::Item<'_, '_>) -> K, ) -> QuerySortedIter< 'w, 's, D, F, impl ExactSizeIterator<Item = Entity> + DoubleEndedIterator + FusedIterator + 'w, > where K: Ord, { self.sort_impl::<L>(move |keyed_query| { keyed_query.sort_unstable_by_key(|(lens, _)| f(lens)); }) } /// Sort all query items into a new iterator with a key extraction function over the query lens. /// /// This sort is stable (i.e., does not reorder equal elements). /// /// This uses [`slice::sort_by_cached_key`] internally. /// /// Defining the lens works like [`transmute_lens`](crate::system::Query::transmute_lens). /// This includes the allowed parameter type changes listed under [allowed transmutes]. /// However, the lens uses the filter of the original query when present. /// /// The sort is not cached across system runs. /// /// [allowed transmutes]: crate::system::Query#allowed-transmutes /// /// # Panics /// /// This will panic if `next` has been called on `QueryIter` before, unless the underlying `Query` is empty. pub fn sort_by_cached_key<L: ReadOnlyQueryData + 'w, K>( self, mut f: impl FnMut(&L::Item<'_, '_>) -> K, ) -> QuerySortedIter< 'w, 's, D, F, impl ExactSizeIterator<Item = Entity> + DoubleEndedIterator + FusedIterator + 'w, > where K: Ord, { self.sort_impl::<L>(move |keyed_query| keyed_query.sort_by_cached_key(|(lens, _)| f(lens))) } /// Shared implementation for the various `sort` methods. /// This uses the lens to collect the items for sorting, but delegates the actual sorting to the provided closure. /// /// Defining the lens works like [`transmute_lens`](crate::system::Query::transmute_lens). /// This includes the allowed parameter type changes listed under [allowed transmutes]. /// However, the lens uses the filter of the original query when present. /// /// The sort is not cached across system runs. /// /// [allowed transmutes]: crate::system::Query#allowed-transmutes /// /// # Panics /// /// This will panic if `next` has been called on `QueryIter` before, unless the underlying `Query` is empty. fn sort_impl<L: ReadOnlyQueryData + 'w>( self, f: impl FnOnce(&mut Vec<(L::Item<'_, '_>, NeutralOrd<Entity>)>), ) -> QuerySortedIter< 'w, 's, D, F, impl ExactSizeIterator<Item = Entity> + DoubleEndedIterator + FusedIterator + 'w, > { // On the first successful iteration of `QueryIterationCursor`, `archetype_entities` or `table_entities` // will be set to a non-zero value. The correctness of this method relies on this. // I.e. this sort method will execute if and only if `next` on `QueryIterationCursor` of a // non-empty `QueryIter` has not yet been called. When empty, this sort method will not panic. if !self.cursor.archetype_entities.is_empty() || !self.cursor.table_entities.is_empty() { panic!("it is not valid to call sort() after next()") } let world = self.world; let query_lens_state = self.query_state.transmute_filtered::<(L, Entity), F>(world); // SAFETY: // `self.world` has permission to access the required components. // The original query iter has not been iterated on, so no items are aliased from it. // `QueryIter::new` ensures `world` is the same one used to initialize `query_state`. let query_lens = unsafe { query_lens_state.query_unchecked_manual(world) }.into_iter(); let mut keyed_query: Vec<_> = query_lens .map(|(key, entity)| (key, NeutralOrd(entity))) .collect(); f(&mut keyed_query); let entity_iter = keyed_query .into_iter() .map(|(.., entity)| entity.0) .collect::<Vec<_>>() .into_iter(); // SAFETY: // `self.world` has permission to access the required components. // Each lens query item is dropped before the respective actual query item is accessed. unsafe { QuerySortedIter::new( world, self.query_state, entity_iter, world.last_change_tick(),
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/src/query/world_query.rs
crates/bevy_ecs/src/query/world_query.rs
use crate::{ archetype::Archetype, change_detection::Tick, component::{ComponentId, Components}, query::FilteredAccess, storage::Table, world::{unsafe_world_cell::UnsafeWorldCell, World}, }; use variadics_please::all_tuples; /// Types that can be used as parameters in a [`Query`]. /// Types that implement this should also implement either [`QueryData`] or [`QueryFilter`] /// /// # Safety /// /// Implementor must ensure that /// [`update_component_access`], [`QueryData::provide_extra_access`], [`matches_component_set`], [`QueryData::fetch`], [`QueryFilter::filter_fetch`] and [`init_fetch`] /// obey the following: /// /// - For each component mutably accessed by [`QueryData::fetch`], [`update_component_access`] or [`QueryData::provide_extra_access`] should add write access unless read or write access has already been added, in which case it should panic. /// - For each component readonly accessed by [`QueryData::fetch`] or [`QueryFilter::filter_fetch`], [`update_component_access`] or [`QueryData::provide_extra_access`] should add read access unless write access has already been added, in which case it should panic. /// - If `fetch` mutably accesses the same component twice, [`update_component_access`] should panic. /// - [`update_component_access`] may not add a `Without` filter for a component unless [`matches_component_set`] always returns `false` when the component set contains that component. /// - [`update_component_access`] may not add a `With` filter for a component unless [`matches_component_set`] always returns `false` when the component set doesn't contain that component. /// - In cases where the query represents a disjunction (such as an `Or` filter) where each element is a valid [`WorldQuery`], the following rules must be obeyed: /// - [`matches_component_set`] must be a disjunction of the element's implementations /// - [`update_component_access`] must replace the filters with a disjunction of filters /// - Each filter in that disjunction must be a conjunction of the corresponding element's filter with the previous `access` /// - For each resource readonly accessed by [`init_fetch`], [`update_component_access`] should add read access. /// - Mutable resource access is not allowed. /// - Any access added during [`QueryData::provide_extra_access`] must be a subset of `available_access`, and must not conflict with any access in `access`. /// /// When implementing [`update_component_access`], note that `add_read` and `add_write` both also add a `With` filter, whereas `extend_access` does not change the filters. /// /// [`QueryData::provide_extra_access`]: crate::query::QueryData::provide_extra_access /// [`QueryData::fetch`]: crate::query::QueryData::fetch /// [`QueryFilter::filter_fetch`]: crate::query::QueryFilter::filter_fetch /// [`init_fetch`]: Self::init_fetch /// [`matches_component_set`]: Self::matches_component_set /// [`Query`]: crate::system::Query /// [`update_component_access`]: Self::update_component_access /// [`QueryData`]: crate::query::QueryData /// [`QueryFilter`]: crate::query::QueryFilter pub unsafe trait WorldQuery { /// Per archetype/table state retrieved by this [`WorldQuery`] to compute [`Self::Item`](crate::query::QueryData::Item) for each entity. type Fetch<'w>: Clone; /// State used to construct a [`Self::Fetch`](WorldQuery::Fetch). This will be cached inside [`QueryState`](crate::query::QueryState), /// so it is best to move as much data / computation here as possible to reduce the cost of /// constructing [`Self::Fetch`](WorldQuery::Fetch). type State: Send + Sync + Sized; /// This function manually implements subtyping for the query fetches. fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort>; /// Creates a new instance of [`Self::Fetch`](WorldQuery::Fetch), /// by combining data from the [`World`] with the cached [`Self::State`](WorldQuery::State). /// Readonly accesses resources registered in [`WorldQuery::update_component_access`]. /// /// # Safety /// /// - `state` must have been initialized (via [`WorldQuery::init_state`]) using the same `world` passed /// in to this function. /// - `world` must have the **right** to access any access registered in `update_component_access`. /// - There must not be simultaneous resource access conflicting with readonly resource access registered in [`WorldQuery::update_component_access`]. unsafe fn init_fetch<'w, 's>( world: UnsafeWorldCell<'w>, state: &'s Self::State, last_run: Tick, this_run: Tick, ) -> Self::Fetch<'w>; /// Returns true if (and only if) every table of every archetype matched by this fetch contains /// all of the matched components. /// /// This is used to select a more efficient "table iterator" /// for "dense" queries. If this returns true, [`WorldQuery::set_table`] must be used before /// [`QueryData::fetch`](crate::query::QueryData::fetch) can be called for iterators. If this returns false, /// [`WorldQuery::set_archetype`] must be used before [`QueryData::fetch`](crate::query::QueryData::fetch) can be called for /// iterators. const IS_DENSE: bool; /// Adjusts internal state to account for the next [`Archetype`]. This will always be called on /// archetypes that match this [`WorldQuery`]. /// /// # Safety /// /// - `archetype` and `tables` must be from the same [`World`] that [`WorldQuery::init_state`] was called on. /// - `table` must correspond to `archetype`. /// - `state` must be the [`State`](Self::State) that `fetch` was initialized with. unsafe fn set_archetype<'w, 's>( fetch: &mut Self::Fetch<'w>, state: &'s Self::State, archetype: &'w Archetype, table: &'w Table, ); /// Adjusts internal state to account for the next [`Table`]. This will always be called on tables /// that match this [`WorldQuery`]. /// /// # Safety /// /// - `table` must be from the same [`World`] that [`WorldQuery::init_state`] was called on. /// - `state` must be the [`State`](Self::State) that `fetch` was initialized with. unsafe fn set_table<'w, 's>( fetch: &mut Self::Fetch<'w>, state: &'s Self::State, table: &'w Table, ); /// Adds any component accesses used by this [`WorldQuery`] to `access`. /// /// Used to check which queries are disjoint and can run in parallel // This does not have a default body of `{}` because 99% of cases need to add accesses // and forgetting to do so would be unsound. fn update_component_access(state: &Self::State, access: &mut FilteredAccess); /// Creates and initializes a [`State`](WorldQuery::State) for this [`WorldQuery`] type. fn init_state(world: &mut World) -> Self::State; /// Attempts to initialize a [`State`](WorldQuery::State) for this [`WorldQuery`] type using read-only /// access to [`Components`]. fn get_state(components: &Components) -> Option<Self::State>; /// Returns `true` if this query matches a set of components. Otherwise, returns `false`. /// /// Used to check which [`Archetype`]s can be skipped by the query /// (if none of the [`Component`](crate::component::Component)s match). /// This is how archetypal query filters like `With` work. fn matches_component_set( state: &Self::State, set_contains_id: &impl Fn(ComponentId) -> bool, ) -> bool; } macro_rules! impl_tuple_world_query { ($(#[$meta:meta])* $(($name: ident, $state: ident)),*) => { #[expect( clippy::allow_attributes, reason = "This is a tuple-related macro; as such the lints below may not always apply." )] #[allow( non_snake_case, reason = "The names of some variables are provided by the macro's caller, not by us." )] #[allow( unused_variables, reason = "Zero-length tuples won't use any of the parameters." )] #[allow( clippy::unused_unit, reason = "Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case." )] $(#[$meta])* /// SAFETY: /// `fetch` accesses are the conjunction of the subqueries' accesses /// This is sound because `update_component_access` adds accesses according to the implementations of all the subqueries. /// `update_component_access` adds all `With` and `Without` filters from the subqueries. /// This is sound because `matches_component_set` always returns `false` if any the subqueries' implementations return `false`. unsafe impl<$($name: WorldQuery),*> WorldQuery for ($($name,)*) { type Fetch<'w> = ($($name::Fetch<'w>,)*); type State = ($($name::State,)*); fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> { let ($($name,)*) = fetch; ($( $name::shrink_fetch($name), )*) } #[inline] unsafe fn init_fetch<'w, 's>(world: UnsafeWorldCell<'w>, state: &'s Self::State, last_run: Tick, this_run: Tick) -> Self::Fetch<'w> { let ($($name,)*) = state; // SAFETY: The invariants are upheld by the caller. ($(unsafe { $name::init_fetch(world, $name, last_run, this_run) },)*) } const IS_DENSE: bool = true $(&& $name::IS_DENSE)*; #[inline] unsafe fn set_archetype<'w, 's>( fetch: &mut Self::Fetch<'w>, state: &'s Self::State, archetype: &'w Archetype, table: &'w Table ) { let ($($name,)*) = fetch; let ($($state,)*) = state; // SAFETY: The invariants are upheld by the caller. $(unsafe { $name::set_archetype($name, $state, archetype, table); })* } #[inline] unsafe fn set_table<'w, 's>(fetch: &mut Self::Fetch<'w>, state: &'s Self::State, table: &'w Table) { let ($($name,)*) = fetch; let ($($state,)*) = state; // SAFETY: The invariants are upheld by the caller. $(unsafe { $name::set_table($name, $state, table); })* } fn update_component_access(state: &Self::State, access: &mut FilteredAccess) { let ($($name,)*) = state; $($name::update_component_access($name, access);)* } fn init_state(world: &mut World) -> Self::State { ($($name::init_state(world),)*) } fn get_state(components: &Components) -> Option<Self::State> { Some(($($name::get_state(components)?,)*)) } fn matches_component_set(state: &Self::State, set_contains_id: &impl Fn(ComponentId) -> bool) -> bool { let ($($name,)*) = state; true $(&& $name::matches_component_set($name, set_contains_id))* } } }; } all_tuples!( #[doc(fake_variadic)] impl_tuple_world_query, 0, 15, F, S );
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false