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_ecs/src/error/bevy_error.rs | crates/bevy_ecs/src/error/bevy_error.rs | use alloc::boxed::Box;
use core::{
error::Error,
fmt::{Debug, Display},
};
/// The built in "universal" Bevy error type. This has a blanket [`From`] impl for any type that implements Rust's [`Error`],
/// meaning it can be used as a "catch all" error.
///
/// # Backtraces
///
/// When used with the `backtrace` Cargo feature, it will capture a backtrace when the error is constructed (generally in the [`From`] impl]).
/// When printed, the backtrace will be displayed. By default, the backtrace will be trimmed down to filter out noise. To see the full backtrace,
/// set the `BEVY_BACKTRACE=full` environment variable.
///
/// # Usage
///
/// ```
/// # use bevy_ecs::prelude::*;
///
/// fn fallible_system() -> Result<(), BevyError> {
/// // This will result in Rust's built-in ParseIntError, which will automatically
/// // be converted into a BevyError.
/// let parsed: usize = "I am not a number".parse()?;
/// Ok(())
/// }
/// ```
pub struct BevyError {
inner: Box<InnerBevyError>,
}
impl BevyError {
/// Attempts to downcast the internal error to the given type.
pub fn downcast_ref<E: Error + 'static>(&self) -> Option<&E> {
self.inner.error.downcast_ref::<E>()
}
fn format_backtrace(&self, _f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
#[cfg(feature = "backtrace")]
{
let f = _f;
let backtrace = &self.inner.backtrace;
if let std::backtrace::BacktraceStatus::Captured = backtrace.status() {
let full_backtrace = std::env::var("BEVY_BACKTRACE").is_ok_and(|val| val == "full");
let backtrace_str = alloc::string::ToString::to_string(backtrace);
let mut skip_next_location_line = false;
for line in backtrace_str.split('\n') {
if !full_backtrace {
if skip_next_location_line {
if line.starts_with(" at") {
continue;
}
skip_next_location_line = false;
}
if line.contains("std::backtrace_rs::backtrace::") {
skip_next_location_line = true;
continue;
}
if line.contains("std::backtrace::Backtrace::") {
skip_next_location_line = true;
continue;
}
if line.contains("<bevy_ecs::error::bevy_error::BevyError as core::convert::From<E>>::from") {
skip_next_location_line = true;
continue;
}
if line.contains("<core::result::Result<T,F> as core::ops::try_trait::FromResidual<core::result::Result<core::convert::Infallible,E>>>::from_residual") {
skip_next_location_line = true;
continue;
}
if line.contains("__rust_begin_short_backtrace") {
break;
}
if line.contains("bevy_ecs::observer::Observers::invoke::{{closure}}") {
break;
}
}
writeln!(f, "{line}")?;
}
if !full_backtrace {
if std::thread::panicking() {
SKIP_NORMAL_BACKTRACE.set(true);
}
writeln!(f, "{FILTER_MESSAGE}")?;
}
}
}
Ok(())
}
}
/// This type exists (rather than having a `BevyError(Box<dyn InnerBevyError)`) to make [`BevyError`] use a "thin pointer" instead of
/// a "fat pointer", which reduces the size of our Result by a usize. This does introduce an extra indirection, but error handling is a "cold path".
/// We don't need to optimize it to that degree.
/// PERF: We could probably have the best of both worlds with a "custom vtable" impl, but thats not a huge priority right now and the code simplicity
/// of the current impl is nice.
struct InnerBevyError {
error: Box<dyn Error + Send + Sync + 'static>,
#[cfg(feature = "backtrace")]
backtrace: std::backtrace::Backtrace,
}
// NOTE: writing the impl this way gives us From<&str> ... nice!
impl<E> From<E> for BevyError
where
Box<dyn Error + Send + Sync + 'static>: From<E>,
{
#[cold]
fn from(error: E) -> Self {
BevyError {
inner: Box::new(InnerBevyError {
error: error.into(),
#[cfg(feature = "backtrace")]
backtrace: std::backtrace::Backtrace::capture(),
}),
}
}
}
impl Display for BevyError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
writeln!(f, "{}", self.inner.error)?;
self.format_backtrace(f)?;
Ok(())
}
}
impl Debug for BevyError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
writeln!(f, "{:?}", self.inner.error)?;
self.format_backtrace(f)?;
Ok(())
}
}
#[cfg(feature = "backtrace")]
const FILTER_MESSAGE: &str = "note: Some \"noisy\" backtrace lines have been filtered out. Run with `BEVY_BACKTRACE=full` for a verbose backtrace.";
#[cfg(feature = "backtrace")]
std::thread_local! {
static SKIP_NORMAL_BACKTRACE: core::cell::Cell<bool> =
const { core::cell::Cell::new(false) };
}
/// When called, this will skip the currently configured panic hook when a [`BevyError`] backtrace has already been printed.
#[cfg(feature = "backtrace")]
#[expect(clippy::print_stdout, reason = "Allowed behind `std` feature gate.")]
pub fn bevy_error_panic_hook(
current_hook: impl Fn(&std::panic::PanicHookInfo),
) -> impl Fn(&std::panic::PanicHookInfo) {
move |info| {
if SKIP_NORMAL_BACKTRACE.replace(false) {
if let Some(payload) = info.payload().downcast_ref::<&str>() {
std::println!("{payload}");
} else if let Some(payload) = info.payload().downcast_ref::<alloc::string::String>() {
std::println!("{payload}");
}
return;
}
current_hook(info);
}
}
#[cfg(test)]
mod tests {
#[test]
#[cfg(not(miri))] // miri backtraces are weird
#[cfg(not(windows))] // the windows backtrace in this context is ... unhelpful and not worth testing
fn filtered_backtrace_test() {
fn i_fail() -> crate::error::Result {
let _: usize = "I am not a number".parse()?;
Ok(())
}
// SAFETY: this is not safe ... this test could run in parallel with another test
// that writes the environment variable. We either accept that so we can write this test,
// or we don't.
unsafe { std::env::set_var("RUST_BACKTRACE", "1") };
let error = i_fail().err().unwrap();
let debug_message = alloc::format!("{error:?}");
let mut lines = debug_message.lines().peekable();
assert_eq!(
"ParseIntError { kind: InvalidDigit }",
lines.next().unwrap()
);
// On mac backtraces can start with Backtrace::create
let mut skip = false;
if let Some(line) = lines.peek()
&& &line[6..] == "std::backtrace::Backtrace::create"
{
skip = true;
}
if skip {
lines.next().unwrap();
}
let expected_lines = alloc::vec![
"bevy_ecs::error::bevy_error::tests::filtered_backtrace_test::i_fail",
"bevy_ecs::error::bevy_error::tests::filtered_backtrace_test",
"bevy_ecs::error::bevy_error::tests::filtered_backtrace_test::{{closure}}",
"core::ops::function::FnOnce::call_once",
];
for expected in expected_lines {
let line = lines.next().unwrap();
assert_eq!(&line[6..], expected);
let mut skip = false;
if let Some(line) = lines.peek()
&& line.starts_with(" at")
{
skip = true;
}
if skip {
lines.next().unwrap();
}
}
// on linux there is a second call_once
let mut skip = false;
if let Some(line) = lines.peek()
&& &line[6..] == "core::ops::function::FnOnce::call_once"
{
skip = true;
}
if skip {
lines.next().unwrap();
}
let mut skip = false;
if let Some(line) = lines.peek()
&& line.starts_with(" at")
{
skip = true;
}
if skip {
lines.next().unwrap();
}
assert_eq!(super::FILTER_MESSAGE, lines.next().unwrap());
assert!(lines.next().is_none());
}
}
| 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/error/mod.rs | crates/bevy_ecs/src/error/mod.rs | //! Error handling for Bevy systems, commands, and observers.
//!
//! When a system is added to a [`Schedule`], and its return type is that of [`Result`], then Bevy
//! considers those systems to be "fallible", and the ECS scheduler will special-case the [`Err`]
//! variant of the returned `Result`.
//!
//! All [`BevyError`]s returned by a system, observer or command are handled by an "error handler". By default, the
//! [`panic`] error handler function is used, resulting in a panic with the error message attached.
//!
//! You can change the default behavior by registering a custom error handler:
//! Use [`DefaultErrorHandler`] to set a custom error handler function for a world,
//! or `App::set_error_handler` for a whole app.
//! In practice, this is generally feature-flagged: panicking or loudly logging errors in development,
//! and quietly logging or ignoring them in production to avoid crashing the app.
//!
//! Bevy provides a number of pre-built error-handlers for you to use:
//!
//! - [`panic`] β panics with the system error
//! - [`error`] β logs the system error at the `error` level
//! - [`warn`] β logs the system error at the `warn` level
//! - [`info`] β logs the system error at the `info` level
//! - [`debug`] β logs the system error at the `debug` level
//! - [`trace`] β logs the system error at the `trace` level
//! - [`ignore`] β ignores the system error
//!
//! However, you can use any custom error handler logic by providing your own function (or
//! non-capturing closure that coerces to the function signature) as long as it matches the
//! signature:
//!
//! ```rust,ignore
//! fn(BevyError, ErrorContext)
//! ```
//!
//! The [`ErrorContext`] allows you to access additional details relevant to providing
//! context surrounding the error β such as the system's [`name`] β in your error messages.
//!
//! ```rust, ignore
//! use bevy_ecs::error::{BevyError, ErrorContext, DefaultErrorHandler};
//! use log::trace;
//!
//! fn my_error_handler(error: BevyError, ctx: ErrorContext) {
//! if ctx.name().ends_with("plz_ignore") {
//! trace!("Nothing to see here, move along.");
//! return;
//! }
//! bevy_ecs::error::error(error, ctx);
//! }
//!
//! fn main() {
//! let mut world = World::new();
//! world.insert_resource(DefaultErrorHandler(my_error_handler));
//! // Use your world here
//! }
//! ```
//!
//! If you need special handling of individual fallible systems, you can use Bevy's [`system piping
//! feature`] to capture the [`Result`] output of the system and handle it accordingly.
//!
//! When working with commands, you can handle the result of each command separately using the [`HandleError::handle_error_with`] method.
//!
//! [`Schedule`]: crate::schedule::Schedule
//! [`panic`]: panic()
//! [`World`]: crate::world::World
//! [`System`]: crate::system::System
//! [`name`]: crate::system::System::name
//! [`system piping feature`]: crate::system::In
mod bevy_error;
mod command_handling;
mod handler;
pub use bevy_error::*;
pub use command_handling::*;
pub use handler::*;
/// A result type for use in fallible systems, commands and observers.
///
/// The [`BevyError`] type is a type-erased error type with optional Bevy-specific diagnostics.
pub type Result<T = (), E = BevyError> = core::result::Result<T, E>;
| 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/error/command_handling.rs | crates/bevy_ecs/src/error/command_handling.rs | use core::fmt;
use bevy_utils::prelude::DebugName;
use crate::{
entity::Entity,
never::Never,
system::{entity_command::EntityCommandError, Command, EntityCommand},
world::{error::EntityMutableFetchError, World},
};
use super::{BevyError, ErrorContext, ErrorHandler};
/// Takes a [`Command`] that potentially returns a Result and uses a given error handler function to convert it into
/// a [`Command`] that internally handles an error if it occurs and returns `()`.
pub trait HandleError<Out = ()>: Send + 'static {
/// Takes a [`Command`] that returns a Result and uses a given error handler function to convert it into
/// a [`Command`] that internally handles an error if it occurs and returns `()`.
fn handle_error_with(self, error_handler: ErrorHandler) -> impl Command;
/// Takes a [`Command`] that returns a Result and uses the default error handler function to convert it into
/// a [`Command`] that internally handles an error if it occurs and returns `()`.
fn handle_error(self) -> impl Command;
/// Takes a [`Command`] that returns a Result and ignores any error that occurs.
fn ignore_error(self) -> impl Command;
}
impl<C, T, E> HandleError<Result<T, E>> for C
where
C: Command<Result<T, E>>,
E: Into<BevyError>,
{
fn handle_error_with(self, error_handler: ErrorHandler) -> impl Command {
move |world: &mut World| match self.apply(world) {
Ok(_) => {}
Err(err) => (error_handler)(
err.into(),
ErrorContext::Command {
name: DebugName::type_name::<C>(),
},
),
}
}
fn handle_error(self) -> impl Command {
move |world: &mut World| match self.apply(world) {
Ok(_) => {}
Err(err) => world.default_error_handler()(
err.into(),
ErrorContext::Command {
name: DebugName::type_name::<C>(),
},
),
}
}
fn ignore_error(self) -> impl Command {
move |world: &mut World| {
let _ = self.apply(world);
}
}
}
impl<C> HandleError<Never> for C
where
C: Command<Never>,
{
fn handle_error_with(self, _error_handler: fn(BevyError, ErrorContext)) -> impl Command {
move |world: &mut World| {
self.apply(world);
}
}
#[inline]
fn handle_error(self) -> impl Command {
move |world: &mut World| {
self.apply(world);
}
}
#[inline]
fn ignore_error(self) -> impl Command {
move |world: &mut World| {
self.apply(world);
}
}
}
impl<C> HandleError for C
where
C: Command,
{
#[inline]
fn handle_error_with(self, _error_handler: fn(BevyError, ErrorContext)) -> impl Command {
self
}
#[inline]
fn handle_error(self) -> impl Command {
self
}
#[inline]
fn ignore_error(self) -> impl Command {
self
}
}
/// Passes in a specific entity to an [`EntityCommand`], resulting in a [`Command`] that
/// internally runs the [`EntityCommand`] on that entity.
///
// NOTE: This is a separate trait from `EntityCommand` because "result-returning entity commands" and
// "non-result returning entity commands" require different implementations, so they cannot be automatically
// implemented. And this isn't the type of implementation that we want to thrust on people implementing
// EntityCommand.
pub trait CommandWithEntity<Out> {
/// Passes in a specific entity to an [`EntityCommand`], resulting in a [`Command`] that
/// internally runs the [`EntityCommand`] on that entity.
fn with_entity(self, entity: Entity) -> impl Command<Out> + HandleError<Out>;
}
impl<C> CommandWithEntity<Result<(), EntityMutableFetchError>> for C
where
C: EntityCommand,
{
fn with_entity(
self,
entity: Entity,
) -> impl Command<Result<(), EntityMutableFetchError>>
+ HandleError<Result<(), EntityMutableFetchError>> {
move |world: &mut World| -> Result<(), EntityMutableFetchError> {
let entity = world.get_entity_mut(entity)?;
self.apply(entity);
Ok(())
}
}
}
impl<C, T, Err> CommandWithEntity<Result<T, EntityCommandError<Err>>> for C
where
C: EntityCommand<Result<T, Err>>,
Err: fmt::Debug + fmt::Display + Send + Sync + 'static,
{
fn with_entity(
self,
entity: Entity,
) -> impl Command<Result<T, EntityCommandError<Err>>> + HandleError<Result<T, EntityCommandError<Err>>>
{
move |world: &mut World| {
let entity = world.get_entity_mut(entity)?;
self.apply(entity)
.map_err(EntityCommandError::CommandFailed)
}
}
}
| 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/error/handler.rs | crates/bevy_ecs/src/error/handler.rs | use core::fmt::Display;
use crate::{change_detection::Tick, error::BevyError, prelude::Resource};
use bevy_utils::prelude::DebugName;
use derive_more::derive::{Deref, DerefMut};
/// Context for a [`BevyError`] to aid in debugging.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ErrorContext {
/// The error occurred in a system.
System {
/// The name of the system that failed.
name: DebugName,
/// The last tick that the system was run.
last_run: Tick,
},
/// The error occurred in a run condition.
RunCondition {
/// The name of the run condition that failed.
name: DebugName,
/// The last tick that the run condition was evaluated.
last_run: Tick,
/// The system this run condition is attached to.
system: DebugName,
/// `true` if this run condition was on a set.
on_set: bool,
},
/// The error occurred in a command.
Command {
/// The name of the command that failed.
name: DebugName,
},
/// The error occurred in an observer.
Observer {
/// The name of the observer that failed.
name: DebugName,
/// The last tick that the observer was run.
last_run: Tick,
},
}
impl Display for ErrorContext {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::System { name, .. } => {
write!(f, "System `{name}` failed")
}
Self::Command { name } => write!(f, "Command `{name}` failed"),
Self::Observer { name, .. } => {
write!(f, "Observer `{name}` failed")
}
Self::RunCondition {
name,
system,
on_set,
..
} => {
write!(
f,
"Run condition `{name}` failed for{} system `{system}`",
if *on_set { " set containing" } else { "" }
)
}
}
}
}
impl ErrorContext {
/// The name of the ECS construct that failed.
pub fn name(&self) -> DebugName {
match self {
Self::System { name, .. }
| Self::Command { name, .. }
| Self::Observer { name, .. }
| Self::RunCondition { name, .. } => name.clone(),
}
}
/// A string representation of the kind of ECS construct that failed.
///
/// This is a simpler helper used for logging.
pub fn kind(&self) -> &str {
match self {
Self::System { .. } => "system",
Self::Command { .. } => "command",
Self::Observer { .. } => "observer",
Self::RunCondition { .. } => "run condition",
}
}
}
macro_rules! inner {
($call:path, $e:ident, $c:ident) => {
$call!(
"Encountered an error in {} `{}`: {}",
$c.kind(),
$c.name(),
$e
);
};
}
/// Defines how Bevy reacts to errors.
pub type ErrorHandler = fn(BevyError, ErrorContext);
/// Error handler to call when an error is not handled otherwise.
/// Defaults to [`panic()`].
///
/// When updated while a [`Schedule`] is running, it doesn't take effect for
/// that schedule until it's completed.
///
/// [`Schedule`]: crate::schedule::Schedule
#[derive(Resource, Deref, DerefMut, Copy, Clone)]
pub struct DefaultErrorHandler(pub ErrorHandler);
impl Default for DefaultErrorHandler {
fn default() -> Self {
Self(panic)
}
}
/// Error handler that panics with the system error.
#[track_caller]
#[inline]
pub fn panic(error: BevyError, ctx: ErrorContext) {
inner!(panic, error, ctx);
}
/// Error handler that logs the system error at the `error` level.
#[track_caller]
#[inline]
pub fn error(error: BevyError, ctx: ErrorContext) {
inner!(log::error, error, ctx);
}
/// Error handler that logs the system error at the `warn` level.
#[track_caller]
#[inline]
pub fn warn(error: BevyError, ctx: ErrorContext) {
inner!(log::warn, error, ctx);
}
/// Error handler that logs the system error at the `info` level.
#[track_caller]
#[inline]
pub fn info(error: BevyError, ctx: ErrorContext) {
inner!(log::info, error, ctx);
}
/// Error handler that logs the system error at the `debug` level.
#[track_caller]
#[inline]
pub fn debug(error: BevyError, ctx: ErrorContext) {
inner!(log::debug, error, ctx);
}
/// Error handler that logs the system error at the `trace` level.
#[track_caller]
#[inline]
pub fn trace(error: BevyError, ctx: ErrorContext) {
inner!(log::trace, error, ctx);
}
/// Error handler that ignores the system error.
#[track_caller]
#[inline]
pub fn ignore(_: BevyError, _: ErrorContext) {}
| 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/observer/runner.rs | crates/bevy_ecs/src/observer/runner.rs | //! Logic for evaluating observers, and storing functions inside of observers.
use core::any::Any;
use crate::{
error::ErrorContext,
event::Event,
observer::TriggerContext,
prelude::*,
query::DebugCheckedUnwrap,
system::{ObserverSystem, RunSystemError},
world::DeferredWorld,
};
use bevy_ptr::PtrMut;
/// Type for function that is run when an observer is triggered.
///
/// Typically refers to the default runner that runs the system stored in the associated [`Observer`] component,
/// but can be overridden for custom behavior.
///
/// See `observer_system_runner` for safety considerations.
pub type ObserverRunner =
unsafe fn(DeferredWorld, observer: Entity, &TriggerContext, event: PtrMut, trigger: PtrMut);
/// # Safety
///
/// - `world` must be the [`DeferredWorld`] that the `entity` is defined in
/// - `event_ptr` must match the `E` [`Event`] type.
/// - `trigger_ptr` must match the [`Event::Trigger`] type for `E`.
/// - `trigger_context`'s [`TriggerContext::event_key`] must match the `E` event type.
///
// NOTE: The way `Trigger` and `On` interact in this implementation is _subtle_ and _easily invalidated_
// from a soundness perspective. Please read and understand the safety comments before making any changes,
// either here or in `On`.
pub(super) unsafe fn observer_system_runner<E: Event, B: Bundle, S: ObserverSystem<E, B>>(
mut world: DeferredWorld,
observer: Entity,
trigger_context: &TriggerContext,
event_ptr: PtrMut,
trigger_ptr: PtrMut,
) {
let world = world.as_unsafe_world_cell();
// SAFETY: Observer was triggered so must still exist in world
let observer_cell = unsafe { world.get_entity(observer).debug_checked_unwrap() };
// SAFETY: Observer was triggered so must have an `Observer`
let mut state = unsafe { observer_cell.get_mut::<Observer>().debug_checked_unwrap() };
// TODO: Move this check into the observer cache to avoid dynamic dispatch
let last_trigger = world.last_trigger_id();
if state.last_trigger_id == last_trigger {
return;
}
state.last_trigger_id = last_trigger;
// SAFETY: Caller ensures `trigger_ptr` is castable to `&mut E::Trigger<'_>`
// The soundness story here is complicated: This casts to &'a mut E::Trigger<'a> which notably
// casts the _arbitrary lifetimes_ of the passed in `trigger_ptr` (&'w E::Trigger<'t>, which are
// 'w and 't on On<'w, 't>) as the _same_ lifetime 'a, which is _local to this function call_.
// This becomes On<'a, 'a> in practice. This is why `On<'w, 't>` has the strict constraint that
// the 'w lifetime can never be exposed. To do so would make it possible to introduce use-after-free bugs.
// See this thread for more details: <https://github.com/bevyengine/bevy/pull/20731#discussion_r2311907935>
let trigger: &mut E::Trigger<'_> = unsafe { trigger_ptr.deref_mut() };
let on: On<E, B> = On::new(
// SAFETY: Caller ensures `ptr` is castable to `&mut E`
unsafe { event_ptr.deref_mut() },
observer,
trigger,
trigger_context,
);
// SAFETY:
// - observer was triggered so must have an `Observer` component.
// - observer cannot be dropped or mutated until after the system pointer is already dropped.
let system: *mut dyn ObserverSystem<E, B> = unsafe {
let system: &mut dyn Any = state.system.as_mut();
let system = system.downcast_mut::<S>().debug_checked_unwrap();
&mut *system
};
// SAFETY:
// - there are no outstanding references to world except a private component
// - system is an `ObserverSystem` so won't mutate world beyond the access of a `DeferredWorld`
// and is never exclusive
// - system is the same type erased system from above
unsafe {
#[cfg(feature = "hotpatching")]
if world
.get_resource_ref::<crate::HotPatchChanges>()
.map(|r| {
r.last_changed()
.is_newer_than((*system).get_last_run(), world.change_tick())
})
.unwrap_or(true)
{
(*system).refresh_hotpatch();
};
if let Err(RunSystemError::Failed(err)) = (*system)
.validate_param_unsafe(world)
.map_err(From::from)
.and_then(|()| (*system).run_unsafe(on, world))
{
let handler = state
.error_handler
.unwrap_or_else(|| world.default_error_handler());
handler(
err,
ErrorContext::Observer {
name: (*system).name(),
last_run: (*system).get_last_run(),
},
);
};
(*system).queue_deferred(world.into_deferred());
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
error::{ignore, DefaultErrorHandler},
event::Event,
observer::On,
};
#[derive(Event)]
struct TriggerEvent;
#[test]
#[should_panic(expected = "I failed!")]
fn test_fallible_observer() {
fn system(_: On<TriggerEvent>) -> Result {
Err("I failed!".into())
}
let mut world = World::default();
world.add_observer(system);
Schedule::default().run(&mut world);
world.trigger(TriggerEvent);
}
#[test]
fn test_fallible_observer_ignored_errors() {
#[derive(Resource, Default)]
struct Ran(bool);
fn system(_: On<TriggerEvent>, mut ran: ResMut<Ran>) -> Result {
ran.0 = true;
Err("I failed!".into())
}
// Using observer error handler
let mut world = World::default();
world.init_resource::<Ran>();
world.spawn(Observer::new(system).with_error_handler(ignore));
world.trigger(TriggerEvent);
assert!(world.resource::<Ran>().0);
// Using world error handler
let mut world = World::default();
world.init_resource::<Ran>();
world.spawn(Observer::new(system));
// Test that the correct handler is used when the observer was added
// before the default handler
world.insert_resource(DefaultErrorHandler(ignore));
world.trigger(TriggerEvent);
assert!(world.resource::<Ran>().0);
}
#[test]
#[should_panic]
fn exclusive_system_cannot_be_observer() {
fn system(_: On<TriggerEvent>, _world: &mut World) {}
let mut world = World::default();
world.add_observer(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/observer/distributed_storage.rs | crates/bevy_ecs/src/observer/distributed_storage.rs | //! Information about observers that is stored on the entities themselves.
//!
//! This allows for easier cleanup, better inspection, and more flexible querying.
//!
//! Each observer is associated with an entity, defined by the [`Observer`] component.
//! The [`Observer`] component contains the system that will be run when the observer is triggered,
//! and the [`ObserverDescriptor`] which contains information about what the observer is observing.
//!
//! When we watch entities, we add the [`ObservedBy`] component to those entities,
//! which links back to the observer entity.
use core::any::Any;
use crate::{
component::{ComponentCloneBehavior, ComponentId, Mutable, StorageType},
entity::Entity,
error::{ErrorContext, ErrorHandler},
event::{Event, EventKey},
lifecycle::{ComponentHook, HookContext},
observer::{observer_system_runner, ObserverRunner},
prelude::*,
system::{IntoObserverSystem, ObserverSystem},
world::DeferredWorld,
};
use alloc::boxed::Box;
use alloc::vec::Vec;
use bevy_utils::prelude::DebugName;
#[cfg(feature = "bevy_reflect")]
use crate::prelude::ReflectComponent;
/// An [`Observer`] system. Add this [`Component`] to an [`Entity`] to turn it into an "observer".
///
/// Observers watch for a "trigger" of a specific [`Event`]. An event can be triggered on the [`World`]
/// by calling [`World::trigger`]. It can also be queued up as a [`Command`] using [`Commands::trigger`].
///
/// When a [`World`] triggers an [`Event`], it will immediately run every [`Observer`] that watches for that [`Event`].
///
/// # Usage
///
/// The simplest usage of the observer pattern looks like this:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut world = World::default();
/// #[derive(Event)]
/// struct Speak {
/// message: String,
/// }
///
/// world.add_observer(|event: On<Speak>| {
/// println!("{}", event.message);
/// });
///
/// world.trigger(Speak {
/// message: "Hello!".into(),
/// });
/// ```
///
/// Notice that we used [`World::add_observer`]. This is just a shorthand for spawning an [`Entity`] with an [`Observer`] manually:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut world = World::default();
/// # #[derive(Event)]
/// # struct Speak;
/// // These are functionally the same:
/// world.add_observer(|event: On<Speak>| {});
/// world.spawn(Observer::new(|event: On<Speak>| {}));
/// ```
///
/// Observers are a specialized [`System`] called an [`ObserverSystem`]. The first parameter must be [`On`], which provides access
/// to the [`Event`], the [`Trigger`], and some additional execution context.
///
/// Because they are systems, they can access arbitrary [`World`] data by adding [`SystemParam`]s:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut world = World::default();
/// # #[derive(Event)]
/// # struct PrintNames;
/// # #[derive(Component, Debug)]
/// # struct Name;
/// world.add_observer(|event: On<PrintNames>, names: Query<&Name>| {
/// for name in &names {
/// println!("{name:?}");
/// }
/// });
/// ```
///
/// You can also add [`Commands`], which means you can spawn new entities, insert new components, etc:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut world = World::default();
/// # #[derive(Event)]
/// # struct SpawnThing;
/// # #[derive(Component, Debug)]
/// # struct Thing;
/// world.add_observer(|event: On<SpawnThing>, mut commands: Commands| {
/// commands.spawn(Thing);
/// });
/// ```
///
/// Observers can also trigger new events:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut world = World::default();
/// # #[derive(Event)]
/// # struct A;
/// # #[derive(Event)]
/// # struct B;
/// world.add_observer(|event: On<A>, mut commands: Commands| {
/// commands.trigger(B);
/// });
/// ```
///
/// When the commands are flushed (including these "nested triggers") they will be
/// recursively evaluated until there are no commands left, meaning nested triggers all
/// evaluate at the same time!
///
/// ## Event [`Trigger`] behavior
///
/// Each [`Event`] defines a [`Trigger`] behavior, which determines _which_ observers will run for the given [`Event`] and _how_ they will be run.
///
/// [`Event`] by default (when derived) uses [`GlobalTrigger`](crate::event::GlobalTrigger). When it is triggered any [`Observer`] watching for it will be run.
///
/// ## Event sub-types
///
/// There are some built-in specialized [`Event`] types with custom [`Trigger`] logic:
///
/// - [`EntityEvent`] / [`EntityTrigger`](crate::event::EntityTrigger): An [`Event`] that targets a _specific_ entity. This also has opt-in support for
/// "event bubbling" behavior. See [`EntityEvent`] for details.
/// - [`EntityComponentsTrigger`](crate::event::EntityComponentsTrigger): An [`Event`] that targets an entity _and_ one or more components on that entity.
/// This is used for [component lifecycle events](crate::lifecycle).
///
/// You can also define your own!
///
/// ## Observer execution timing
///
/// Observers triggered via [`World::trigger`] are evaluated immediately, as are all commands they queue up.
///
/// Observers triggered via [`Commands::trigger`] are evaluated at the next sync point in the ECS schedule, just like any other [`Command`].
///
/// To control the relative ordering of observer trigger commands sent from different systems,
/// order the systems in the schedule relative to each other.
///
/// Currently, Bevy does not provide [a way to specify the relative ordering of observers](https://github.com/bevyengine/bevy/issues/14890)
/// watching for the same event. Their ordering is considered to be arbitrary. It is recommended to make no
/// assumptions about their execution order.
///
/// Commands sent by observers are [currently not immediately applied](https://github.com/bevyengine/bevy/issues/19569).
/// Instead, all queued observers will run, and then all of the commands from those observers will be applied.
///
/// ## [`ObservedBy`]
///
/// When entities are observed, they will receive an [`ObservedBy`] component,
/// which will be updated to track the observers that are currently observing them.
///
/// ## Manual [`Observer`] target configuration
///
/// You can manually control the targets that an observer is watching by calling builder methods like [`Observer::with_entity`]
/// _before_ inserting the [`Observer`] component.
///
/// In general, it is better to use the [`EntityWorldMut::observe`] or [`EntityCommands::observe`] methods,
/// which spawns a new observer, and configures it to watch the entity it is called on.
///
/// ## Cleaning up observers
///
/// If an [`EntityEvent`] [`Observer`] targets specific entities, and all of those entities are despawned, the [`Observer`] entity will also be despawned.
/// This protects against observer "garbage" building up over time.
///
/// ## Component lifecycle events: Observers vs Hooks
///
/// It is important to note that observers, just like [hooks](crate::lifecycle::ComponentHooks),
/// can watch for and respond to [lifecycle](crate::lifecycle) events.
/// Unlike hooks, observers are not treated as an "innate" part of component behavior:
/// they can be added or removed at runtime, and multiple observers
/// can be registered for the same lifecycle event for the same component.
///
/// The ordering of hooks versus observers differs based on the lifecycle event in question:
///
/// - when adding components, hooks are evaluated first, then observers
/// - when removing components, observers are evaluated first, then hooks
///
/// This allows hooks to act as constructors and destructors for components,
/// as they always have the first and final say in the component's lifecycle.
///
/// ## Observer re-targeting
///
/// Currently, [observers cannot be retargeted after spawning](https://github.com/bevyengine/bevy/issues/19587):
/// despawn and respawn an observer as a workaround.
///
/// ## Internal observer cache
///
/// For more efficient observer triggering, Observers make use of the internal [`CachedObservers`](crate::observer::CachedObservers) storage.
/// In general, this is an implementation detail developers don't need to worry about, but it can be used when implementing custom [`Trigger`](crate::event::Trigger)
/// types, or to add "dynamic" observers for cases like scripting / modding.
///
/// [`SystemParam`]: crate::system::SystemParam
/// [`Trigger`]: crate::event::Trigger
pub struct Observer {
hook_on_add: ComponentHook,
pub(crate) error_handler: Option<ErrorHandler>,
pub(crate) system: Box<dyn AnyNamedSystem>,
pub(crate) descriptor: ObserverDescriptor,
pub(crate) last_trigger_id: u32,
pub(crate) despawned_watched_entities: u32,
pub(crate) runner: ObserverRunner,
}
impl Observer {
/// Creates a new [`Observer`], which defaults to a "global" observer. This means it will run _whenever_ an event of type `E` is triggered.
///
/// # Panics
///
/// Panics if the given system is an exclusive system.
pub fn new<E: Event, B: Bundle, M, I: IntoObserverSystem<E, B, M>>(system: I) -> Self {
let system = Box::new(IntoObserverSystem::into_system(system));
assert!(
!system.is_exclusive(),
concat!(
"Exclusive system `{}` may not be used as observer.\n",
"Instead of `&mut World`, use either `DeferredWorld` if you do not need structural changes, or `Commands` if you do."
),
system.name()
);
Self {
system,
descriptor: Default::default(),
hook_on_add: hook_on_add::<E, B, I::System>,
error_handler: None,
runner: observer_system_runner::<E, B, I::System>,
despawned_watched_entities: 0,
last_trigger_id: 0,
}
}
/// Creates a new [`Observer`] with custom runner, this is mostly used for dynamic event observers
pub fn with_dynamic_runner(runner: ObserverRunner) -> Self {
Self {
system: Box::new(IntoSystem::into_system(|| {})),
descriptor: Default::default(),
hook_on_add: |mut world, hook_context| {
let default_error_handler = world.default_error_handler();
world.commands().queue(move |world: &mut World| {
let entity = hook_context.entity;
if let Some(mut observe) = world.get_mut::<Observer>(entity) {
if observe.descriptor.event_keys.is_empty() {
return;
}
if observe.error_handler.is_none() {
observe.error_handler = Some(default_error_handler);
}
world.register_observer(entity);
}
});
},
error_handler: None,
runner,
despawned_watched_entities: 0,
last_trigger_id: 0,
}
}
/// Observes the given `entity` (in addition to any entity already being observed).
/// This will cause the [`Observer`] to run whenever an [`EntityEvent::event_target`] is the given `entity`.
/// Note that if this is called _after_ an [`Observer`] is spawned, it will produce no effects.
pub fn with_entity(mut self, entity: Entity) -> Self {
self.watch_entity(entity);
self
}
/// Observes the given `entities` (in addition to any entity already being observed).
/// This will cause the [`Observer`] to run whenever an [`EntityEvent::event_target`] is any of the `entities`.
/// Note that if this is called _after_ an [`Observer`] is spawned, it will produce no effects.
pub fn with_entities<I: IntoIterator<Item = Entity>>(mut self, entities: I) -> Self {
self.watch_entities(entities);
self
}
/// Observes the given `entity` (in addition to any entity already being observed).
/// This will cause the [`Observer`] to run whenever an [`EntityEvent::event_target`] is the given `entity`.
/// Note that if this is called _after_ an [`Observer`] is spawned, it will produce no effects.
pub fn watch_entity(&mut self, entity: Entity) {
self.descriptor.entities.push(entity);
}
/// Observes the given `entity` (in addition to any entity already being observed).
/// This will cause the [`Observer`] to run whenever an [`EntityEvent::event_target`] is any of the `entities`.
/// Note that if this is called _after_ an [`Observer`] is spawned, it will produce no effects.
pub fn watch_entities<I: IntoIterator<Item = Entity>>(&mut self, entities: I) {
self.descriptor.entities.extend(entities);
}
/// Observes the given `component`. This will cause the [`Observer`] to run whenever the [`Event`] has
/// an [`EntityComponentsTrigger`](crate::event::EntityComponentsTrigger) that targets the given `component`.
pub fn with_component(mut self, component: ComponentId) -> Self {
self.descriptor.components.push(component);
self
}
/// Observes the given `components`. This will cause the [`Observer`] to run whenever the [`Event`] has
/// an [`EntityComponentsTrigger`](crate::event::EntityComponentsTrigger) that targets any of the `components`.
pub fn with_components<I: IntoIterator<Item = ComponentId>>(mut self, components: I) -> Self {
self.descriptor.components.extend(components);
self
}
/// Observes the given `event_key`. This will cause the [`Observer`] to run whenever an event with the given [`EventKey`]
/// is triggered.
/// # Safety
/// The type of the `event_key` [`EventKey`] _must_ match the actual value
/// of the event passed into the observer system.
pub unsafe fn with_event_key(mut self, event_key: EventKey) -> Self {
self.descriptor.event_keys.push(event_key);
self
}
/// Sets the error handler to use for this observer.
///
/// See the [`error` module-level documentation](crate::error) for more information.
pub fn with_error_handler(mut self, error_handler: fn(BevyError, ErrorContext)) -> Self {
self.error_handler = Some(error_handler);
self
}
/// Returns the [`ObserverDescriptor`] for this [`Observer`].
pub fn descriptor(&self) -> &ObserverDescriptor {
&self.descriptor
}
/// Returns the name of the [`Observer`]'s system .
pub fn system_name(&self) -> DebugName {
self.system.system_name()
}
}
impl Component for Observer {
const STORAGE_TYPE: StorageType = StorageType::SparseSet;
type Mutability = Mutable;
fn on_add() -> Option<ComponentHook> {
Some(|world, context| {
let Some(observe) = world.get::<Self>(context.entity) else {
return;
};
let hook = observe.hook_on_add;
hook(world, context);
})
}
fn on_remove() -> Option<ComponentHook> {
Some(|mut world, HookContext { entity, .. }| {
let descriptor = core::mem::take(
&mut world
.entity_mut(entity)
.get_mut::<Self>()
.unwrap()
.as_mut()
.descriptor,
);
world.commands().queue(move |world: &mut World| {
world.unregister_observer(entity, descriptor);
});
})
}
}
/// Store information about what an [`Observer`] observes.
///
/// This information is stored inside of the [`Observer`] component,
#[derive(Default, Clone)]
pub struct ObserverDescriptor {
/// The event keys the observer is watching.
pub(super) event_keys: Vec<EventKey>,
/// The components the observer is watching.
pub(super) components: Vec<ComponentId>,
/// The entities the observer is watching.
pub(super) entities: Vec<Entity>,
}
impl ObserverDescriptor {
/// Add the given `event_keys` to the descriptor.
/// # Safety
/// The type of each [`EventKey`] in `event_keys` _must_ match the actual value
/// of the event passed into the observer.
pub unsafe fn with_event_keys(mut self, event_keys: Vec<EventKey>) -> Self {
self.event_keys = event_keys;
self
}
/// Add the given `components` to the descriptor.
pub fn with_components(mut self, components: Vec<ComponentId>) -> Self {
self.components = components;
self
}
/// Add the given `entities` to the descriptor.
pub fn with_entities(mut self, entities: Vec<Entity>) -> Self {
self.entities = entities;
self
}
/// Returns the `event_keys` that the observer is watching.
pub fn event_keys(&self) -> &[EventKey] {
&self.event_keys
}
/// Returns the `components` that the observer is watching.
pub fn components(&self) -> &[ComponentId] {
&self.components
}
/// Returns the `entities` that the observer is watching.
pub fn entities(&self) -> &[Entity] {
&self.entities
}
}
/// A [`ComponentHook`] used by [`Observer`] to handle its [`on-add`](`crate::lifecycle::ComponentHooks::on_add`).
///
/// This function exists separate from [`Observer`] to allow [`Observer`] to have its type parameters
/// erased.
///
/// The type parameters of this function _must_ match those used to create the [`Observer`].
/// As such, it is recommended to only use this function within the [`Observer::new`] method to
/// ensure type parameters match.
fn hook_on_add<E: Event, B: Bundle, S: ObserverSystem<E, B>>(
mut world: DeferredWorld<'_>,
HookContext { entity, .. }: HookContext,
) {
world.commands().queue(move |world: &mut World| {
let event_key = world.register_event_key::<E>();
let components = B::component_ids(&mut world.components_registrator());
if let Some(mut observer) = world.get_mut::<Observer>(entity) {
observer.descriptor.event_keys.push(event_key);
observer.descriptor.components.extend(components);
let system: &mut dyn Any = observer.system.as_mut();
let system: *mut dyn ObserverSystem<E, B> = system.downcast_mut::<S>().unwrap();
// SAFETY: World reference is exclusive and initialize does not touch system, so references do not alias
unsafe {
(*system).initialize(world);
}
world.register_observer(entity);
}
});
}
/// Tracks a list of entity observers for the [`Entity`] [`ObservedBy`] is added to.
#[derive(Default, Debug)]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[cfg_attr(feature = "bevy_reflect", reflect(Component, Debug))]
pub struct ObservedBy(pub(crate) Vec<Entity>);
impl ObservedBy {
/// Provides a read-only reference to the list of entities observing this entity.
pub fn get(&self) -> &[Entity] {
&self.0
}
}
impl Component for ObservedBy {
const STORAGE_TYPE: StorageType = StorageType::SparseSet;
type Mutability = Mutable;
fn on_remove() -> Option<ComponentHook> {
Some(|mut world, HookContext { entity, .. }| {
let observed_by = {
let mut component = world.get_mut::<ObservedBy>(entity).unwrap();
core::mem::take(&mut component.0)
};
for e in observed_by {
let (total_entities, despawned_watched_entities) = {
let Ok(mut entity_mut) = world.get_entity_mut(e) else {
continue;
};
let Some(mut state) = entity_mut.get_mut::<Observer>() else {
continue;
};
state.despawned_watched_entities += 1;
(
state.descriptor.entities.len(),
state.despawned_watched_entities as usize,
)
};
// Despawn Observer if it has no more active sources.
if total_entities == despawned_watched_entities {
world.commands().entity(e).despawn();
}
}
})
}
fn clone_behavior() -> ComponentCloneBehavior {
ComponentCloneBehavior::Ignore
}
}
pub(crate) trait AnyNamedSystem: Any + Send + Sync + 'static {
fn system_name(&self) -> DebugName;
}
impl<T: Any + System> AnyNamedSystem for T {
fn system_name(&self) -> DebugName {
self.name()
}
}
| 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/observer/mod.rs | crates/bevy_ecs/src/observer/mod.rs | //! Observers are a push-based tool for responding to [`Event`]s. The [`Observer`] component holds a [`System`] that runs whenever a matching [`Event`]
//! is triggered.
//!
//! See [`Event`] and [`Observer`] for in-depth documentation and usage examples.
mod centralized_storage;
mod distributed_storage;
mod entity_cloning;
mod runner;
mod system_param;
pub use centralized_storage::*;
pub use distributed_storage::*;
pub use runner::*;
pub use system_param::*;
use crate::{
change_detection::MaybeLocation,
event::Event,
prelude::*,
system::IntoObserverSystem,
world::{DeferredWorld, *},
};
impl World {
/// Spawns a "global" [`Observer`] which will watch for the given event.
/// Returns its [`Entity`] as a [`EntityWorldMut`].
///
/// `system` can be any system whose first parameter is [`On`].
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// struct A;
///
/// # let mut world = World::new();
/// world.add_observer(|_: On<Add, A>| {
/// // ...
/// });
/// world.add_observer(|_: On<Remove, A>| {
/// // ...
/// });
/// ```
///
/// **Calling [`observe`](EntityWorldMut::observe) on the returned
/// [`EntityWorldMut`] will observe the observer itself, which you very
/// likely do not want.**
///
/// # Panics
///
/// Panics if the given system is an exclusive system.
pub fn add_observer<E: Event, B: Bundle, M>(
&mut self,
system: impl IntoObserverSystem<E, B, M>,
) -> EntityWorldMut<'_> {
self.spawn(Observer::new(system))
}
/// Triggers the given [`Event`], which will run any [`Observer`]s watching for it.
///
/// For a variant that borrows the `event` rather than consuming it, use [`World::trigger_ref`] instead.
#[track_caller]
pub fn trigger<'a, E: Event<Trigger<'a>: Default>>(&mut self, mut event: E) {
self.trigger_ref_with_caller(
&mut event,
&mut <E::Trigger<'a> as Default>::default(),
MaybeLocation::caller(),
);
}
/// Triggers the given [`Event`] using the given [`Trigger`](crate::event::Trigger), which will run any [`Observer`]s watching for it.
///
/// For a variant that borrows the `event` rather than consuming it, use [`World::trigger_ref`] instead.
#[track_caller]
pub fn trigger_with<'a, E: Event>(&mut self, mut event: E, mut trigger: E::Trigger<'a>) {
self.trigger_ref_with_caller(&mut event, &mut trigger, MaybeLocation::caller());
}
/// Triggers the given mutable [`Event`] reference, which will run any [`Observer`]s watching for it.
///
/// Compared to [`World::trigger`], this method is most useful when it's necessary to check
/// or use the event after it has been modified by observers.
#[track_caller]
pub fn trigger_ref<'a, E: Event<Trigger<'a>: Default>>(&mut self, event: &mut E) {
self.trigger_ref_with_caller(
event,
&mut <E::Trigger<'a> as Default>::default(),
MaybeLocation::caller(),
);
}
/// Triggers the given mutable [`Event`] reference using the given mutable [`Trigger`](crate::event::Trigger) reference, which
/// will run any [`Observer`]s watching for it.
///
/// Compared to [`World::trigger`], this method is most useful when it's necessary to check
/// or use the event after it has been modified by observers.
pub fn trigger_ref_with<'a, E: Event>(&mut self, event: &mut E, trigger: &mut E::Trigger<'a>) {
self.trigger_ref_with_caller(event, trigger, MaybeLocation::caller());
}
pub(crate) fn trigger_ref_with_caller<'a, E: Event>(
&mut self,
event: &mut E,
trigger: &mut E::Trigger<'a>,
caller: MaybeLocation,
) {
let event_key = self.register_event_key::<E>();
// SAFETY: event_key was just registered and matches `event`
unsafe {
DeferredWorld::from(self).trigger_raw(event_key, event, trigger, caller);
}
}
/// Register an observer to the cache, called when an observer is created
pub(crate) fn register_observer(&mut self, observer_entity: Entity) {
// SAFETY: References do not alias.
let (observer_state, archetypes, observers) = unsafe {
let observer_state: *const Observer = self.get::<Observer>(observer_entity).unwrap();
// Populate ObservedBy for each observed entity.
for watched_entity in (*observer_state).descriptor.entities.iter().copied() {
let mut entity_mut = self.entity_mut(watched_entity);
let mut observed_by = entity_mut.entry::<ObservedBy>().or_default().into_mut();
observed_by.0.push(observer_entity);
}
(&*observer_state, &mut self.archetypes, &mut self.observers)
};
let descriptor = &observer_state.descriptor;
for &event_key in &descriptor.event_keys {
let cache = observers.get_observers_mut(event_key);
if descriptor.components.is_empty() && descriptor.entities.is_empty() {
cache
.global_observers
.insert(observer_entity, observer_state.runner);
} else if descriptor.components.is_empty() {
// Observer is not targeting any components so register it as an entity observer
for &watched_entity in &observer_state.descriptor.entities {
let map = cache.entity_observers.entry(watched_entity).or_default();
map.insert(observer_entity, observer_state.runner);
}
} else {
// Register observer for each watched component
for &component in &descriptor.components {
let observers =
cache
.component_observers
.entry(component)
.or_insert_with(|| {
if let Some(flag) = Observers::is_archetype_cached(event_key) {
archetypes.update_flags(component, flag, true);
}
CachedComponentObservers::default()
});
if descriptor.entities.is_empty() {
// Register for all triggers targeting the component
observers
.global_observers
.insert(observer_entity, observer_state.runner);
} else {
// Register for each watched entity
for &watched_entity in &descriptor.entities {
let map = observers
.entity_component_observers
.entry(watched_entity)
.or_default();
map.insert(observer_entity, observer_state.runner);
}
}
}
}
}
}
/// Remove the observer from the cache, called when an observer gets despawned
pub(crate) fn unregister_observer(&mut self, entity: Entity, descriptor: ObserverDescriptor) {
let archetypes = &mut self.archetypes;
let observers = &mut self.observers;
for &event_key in &descriptor.event_keys {
let cache = observers.get_observers_mut(event_key);
if descriptor.components.is_empty() && descriptor.entities.is_empty() {
cache.global_observers.remove(&entity);
} else if descriptor.components.is_empty() {
for watched_entity in &descriptor.entities {
// This check should be unnecessary since this observer hasn't been unregistered yet
let Some(observers) = cache.entity_observers.get_mut(watched_entity) else {
continue;
};
observers.remove(&entity);
if observers.is_empty() {
cache.entity_observers.remove(watched_entity);
}
}
} else {
for component in &descriptor.components {
let Some(observers) = cache.component_observers.get_mut(component) else {
continue;
};
if descriptor.entities.is_empty() {
observers.global_observers.remove(&entity);
} else {
for watched_entity in &descriptor.entities {
let Some(map) =
observers.entity_component_observers.get_mut(watched_entity)
else {
continue;
};
map.remove(&entity);
if map.is_empty() {
observers.entity_component_observers.remove(watched_entity);
}
}
}
if observers.global_observers.is_empty()
&& observers.entity_component_observers.is_empty()
{
cache.component_observers.remove(component);
if let Some(flag) = Observers::is_archetype_cached(event_key)
&& let Some(by_component) = archetypes.by_component.get(component)
{
for archetype in by_component.keys() {
let archetype = &mut archetypes.archetypes[archetype.index()];
if archetype.contains(*component) {
let no_longer_observed = archetype
.iter_components()
.all(|id| !cache.component_observers.contains_key(&id));
if no_longer_observed {
archetype.flags.set(flag, false);
}
}
}
}
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use alloc::{vec, vec::Vec};
use bevy_ptr::OwningPtr;
use crate::{
change_detection::MaybeLocation,
event::{EntityComponentsTrigger, Event, GlobalTrigger},
hierarchy::ChildOf,
observer::{Observer, Replace},
prelude::*,
world::DeferredWorld,
};
#[derive(Component)]
struct A;
#[derive(Component)]
struct B;
#[derive(Component)]
#[component(storage = "SparseSet")]
struct S;
#[derive(Event)]
struct EventA;
#[derive(EntityEvent)]
struct EntityEventA(Entity);
#[derive(EntityEvent)]
#[entity_event(trigger = EntityComponentsTrigger<'a>)]
struct EntityComponentsEvent(Entity);
#[derive(Event)]
struct EventWithData {
counter: usize,
}
#[derive(Resource, Default)]
struct Order(Vec<&'static str>);
impl Order {
#[track_caller]
fn observed(&mut self, name: &'static str) {
self.0.push(name);
}
}
#[derive(Component, EntityEvent)]
#[entity_event(propagate, auto_propagate)]
struct EventPropagating(Entity);
#[test]
fn observer_order_spawn_despawn() {
let mut world = World::new();
world.init_resource::<Order>();
world.add_observer(|_: On<Add, A>, mut res: ResMut<Order>| res.observed("add"));
world.add_observer(|_: On<Insert, A>, mut res: ResMut<Order>| res.observed("insert"));
world.add_observer(|_: On<Replace, A>, mut res: ResMut<Order>| {
res.observed("replace");
});
world.add_observer(|_: On<Remove, A>, mut res: ResMut<Order>| res.observed("remove"));
let entity = world.spawn(A).id();
world.despawn(entity);
assert_eq!(
vec!["add", "insert", "replace", "remove"],
world.resource::<Order>().0
);
}
#[test]
fn observer_order_insert_remove() {
let mut world = World::new();
world.init_resource::<Order>();
world.add_observer(|_: On<Add, A>, mut res: ResMut<Order>| res.observed("add"));
world.add_observer(|_: On<Insert, A>, mut res: ResMut<Order>| res.observed("insert"));
world.add_observer(|_: On<Replace, A>, mut res: ResMut<Order>| {
res.observed("replace");
});
world.add_observer(|_: On<Remove, A>, mut res: ResMut<Order>| res.observed("remove"));
let mut entity = world.spawn_empty();
entity.insert(A);
entity.remove::<A>();
entity.flush();
assert_eq!(
vec!["add", "insert", "replace", "remove"],
world.resource::<Order>().0
);
}
#[test]
fn observer_order_insert_remove_sparse() {
let mut world = World::new();
world.init_resource::<Order>();
world.add_observer(|_: On<Add, S>, mut res: ResMut<Order>| res.observed("add"));
world.add_observer(|_: On<Insert, S>, mut res: ResMut<Order>| res.observed("insert"));
world.add_observer(|_: On<Replace, S>, mut res: ResMut<Order>| {
res.observed("replace");
});
world.add_observer(|_: On<Remove, S>, mut res: ResMut<Order>| res.observed("remove"));
let mut entity = world.spawn_empty();
entity.insert(S);
entity.remove::<S>();
entity.flush();
assert_eq!(
vec!["add", "insert", "replace", "remove"],
world.resource::<Order>().0
);
}
#[test]
fn observer_order_replace() {
let mut world = World::new();
world.init_resource::<Order>();
let entity = world.spawn(A).id();
world.add_observer(|_: On<Add, A>, mut res: ResMut<Order>| res.observed("add"));
world.add_observer(|_: On<Insert, A>, mut res: ResMut<Order>| res.observed("insert"));
world.add_observer(|_: On<Replace, A>, mut res: ResMut<Order>| {
res.observed("replace");
});
world.add_observer(|_: On<Remove, A>, mut res: ResMut<Order>| res.observed("remove"));
let mut entity = world.entity_mut(entity);
entity.insert(A);
entity.flush();
assert_eq!(vec!["replace", "insert"], world.resource::<Order>().0);
}
#[test]
fn observer_order_recursive() {
let mut world = World::new();
world.init_resource::<Order>();
world.add_observer(
|add: On<Add, A>, mut res: ResMut<Order>, mut commands: Commands| {
res.observed("add_a");
commands.entity(add.entity).insert(B);
},
);
world.add_observer(
|remove: On<Remove, A>, mut res: ResMut<Order>, mut commands: Commands| {
res.observed("remove_a");
commands.entity(remove.entity).remove::<B>();
},
);
world.add_observer(
|add: On<Add, B>, mut res: ResMut<Order>, mut commands: Commands| {
res.observed("add_b");
commands.entity(add.entity).remove::<A>();
},
);
world.add_observer(|_: On<Remove, B>, mut res: ResMut<Order>| {
res.observed("remove_b");
});
let entity = world.spawn(A).flush();
let entity = world.get_entity(entity).unwrap();
assert!(!entity.contains::<A>());
assert!(!entity.contains::<B>());
assert_eq!(
vec!["add_a", "add_b", "remove_a", "remove_b"],
world.resource::<Order>().0
);
}
#[test]
fn observer_trigger_ref() {
let mut world = World::new();
world.add_observer(|mut event: On<EventWithData>| event.counter += 1);
world.add_observer(|mut event: On<EventWithData>| event.counter += 2);
world.add_observer(|mut event: On<EventWithData>| event.counter += 4);
let mut event = EventWithData { counter: 0 };
world.trigger_ref(&mut event);
assert_eq!(7, event.counter);
}
#[test]
fn observer_multiple_listeners() {
let mut world = World::new();
world.init_resource::<Order>();
world.add_observer(|_: On<Add, A>, mut res: ResMut<Order>| res.observed("add_1"));
world.add_observer(|_: On<Add, A>, mut res: ResMut<Order>| res.observed("add_2"));
world.spawn(A).flush();
assert_eq!(vec!["add_2", "add_1"], world.resource::<Order>().0);
// we have one A entity and two observers
assert_eq!(world.query::<&A>().query(&world).count(), 1);
assert_eq!(world.query::<&Observer>().query(&world).count(), 2);
}
#[test]
fn observer_multiple_events() {
let mut world = World::new();
world.init_resource::<Order>();
let on_remove = world.register_event_key::<Remove>();
world.spawn(
// SAFETY: Add and Remove are both unit types, so this is safe
unsafe {
Observer::new(|_: On<Add, A>, mut res: ResMut<Order>| {
res.observed("add/remove");
})
.with_event_key(on_remove)
},
);
let entity = world.spawn(A).id();
world.despawn(entity);
assert_eq!(
vec!["add/remove", "add/remove"],
world.resource::<Order>().0
);
}
#[test]
fn observer_multiple_components() {
let mut world = World::new();
world.init_resource::<Order>();
world.register_component::<A>();
world.register_component::<B>();
world.add_observer(|_: On<Add, (A, B)>, mut res: ResMut<Order>| {
res.observed("add_ab");
});
let entity = world.spawn(A).id();
world.entity_mut(entity).insert(B);
assert_eq!(vec!["add_ab", "add_ab"], world.resource::<Order>().0);
}
#[test]
fn observer_despawn() {
let mut world = World::new();
let system: fn(On<Add, A>) = |_| {
panic!("Observer triggered after being despawned.");
};
let observer = world.add_observer(system).id();
world.despawn(observer);
world.spawn(A).flush();
}
// Regression test for https://github.com/bevyengine/bevy/issues/14961
#[test]
fn observer_despawn_archetype_flags() {
let mut world = World::new();
world.init_resource::<Order>();
let entity = world.spawn((A, B)).flush();
world.add_observer(|_: On<Remove, A>, mut res: ResMut<Order>| {
res.observed("remove_a");
});
let system: fn(On<Remove, B>) = |_: On<Remove, B>| {
panic!("Observer triggered after being despawned.");
};
let observer = world.add_observer(system).flush();
world.despawn(observer);
world.despawn(entity);
assert_eq!(vec!["remove_a"], world.resource::<Order>().0);
}
#[test]
fn observer_multiple_matches() {
let mut world = World::new();
world.init_resource::<Order>();
world.add_observer(|_: On<Add, (A, B)>, mut res: ResMut<Order>| {
res.observed("add_ab");
});
world.spawn((A, B)).flush();
assert_eq!(vec!["add_ab"], world.resource::<Order>().0);
}
#[test]
fn observer_entity_routing() {
let mut world = World::new();
world.init_resource::<Order>();
let system: fn(On<EntityEventA>) = |_| {
panic!("Trigger routed to non-targeted entity.");
};
world.spawn_empty().observe(system);
let entity = world
.spawn_empty()
.observe(|_: On<EntityEventA>, mut res: ResMut<Order>| res.observed("a_1"))
.id();
world.add_observer(move |event: On<EntityEventA>, mut res: ResMut<Order>| {
assert_eq!(event.event_target(), entity);
res.observed("a_2");
});
world.trigger(EntityEventA(entity));
assert_eq!(vec!["a_2", "a_1"], world.resource::<Order>().0);
}
#[test]
fn observer_multiple_targets() {
#[derive(Resource, Default)]
struct R(i32);
let mut world = World::new();
let component_a = world.register_component::<A>();
let component_b = world.register_component::<B>();
world.init_resource::<R>();
// targets (entity_1, A)
let entity_1 = world
.spawn_empty()
.observe(|_: On<EntityComponentsEvent, A>, mut res: ResMut<R>| res.0 += 1)
.id();
// targets (entity_2, B)
let entity_2 = world
.spawn_empty()
.observe(|_: On<EntityComponentsEvent, B>, mut res: ResMut<R>| res.0 += 10)
.id();
// targets any entity or component
world.add_observer(|_: On<EntityComponentsEvent>, mut res: ResMut<R>| res.0 += 100);
// targets any entity, and components A or B
world
.add_observer(|_: On<EntityComponentsEvent, (A, B)>, mut res: ResMut<R>| res.0 += 1000);
// test all tuples
world.add_observer(
|_: On<EntityComponentsEvent, (A, B, (A, B))>, mut res: ResMut<R>| res.0 += 10000,
);
world.add_observer(
|_: On<EntityComponentsEvent, (A, B, (A, B), ((A, B), (A, B)))>, mut res: ResMut<R>| {
res.0 += 100000;
},
);
world.add_observer(
|_: On<EntityComponentsEvent, (A, B, (A, B), (B, A), (A, B, ((A, B), (B, A))))>,
mut res: ResMut<R>| res.0 += 1000000,
);
// trigger for an entity and a component
world.trigger_with(
EntityComponentsEvent(entity_1),
EntityComponentsTrigger {
components: &[component_a],
},
);
// only observer that doesn't trigger is the one only watching entity_2
assert_eq!(1111101, world.resource::<R>().0);
world.resource_mut::<R>().0 = 0;
// trigger for both entities, but no components: trigger once per entity target
world.trigger_with(
EntityComponentsEvent(entity_1),
EntityComponentsTrigger { components: &[] },
);
world.trigger_with(
EntityComponentsEvent(entity_2),
EntityComponentsTrigger { components: &[] },
);
// only the observer that doesn't require components triggers - once per entity
assert_eq!(200, world.resource::<R>().0);
world.resource_mut::<R>().0 = 0;
// trigger for both entities and both components: trigger once per entity target
// we only get 2222211 because a given observer can trigger only once per entity target
world.trigger_with(
EntityComponentsEvent(entity_1),
EntityComponentsTrigger {
components: &[component_a, component_b],
},
);
world.trigger_with(
EntityComponentsEvent(entity_2),
EntityComponentsTrigger {
components: &[component_a, component_b],
},
);
assert_eq!(2222211, world.resource::<R>().0);
world.resource_mut::<R>().0 = 0;
}
#[test]
fn observer_dynamic_component() {
let mut world = World::new();
world.init_resource::<Order>();
let component_id = world.register_component::<A>();
world.spawn(
Observer::new(|_: On<Add>, mut res: ResMut<Order>| res.observed("event_a"))
.with_component(component_id),
);
let mut entity = world.spawn_empty();
OwningPtr::make(A, |ptr| {
// SAFETY: we registered `component_id` above.
unsafe { entity.insert_by_id(component_id, ptr) };
});
assert_eq!(vec!["event_a"], world.resource::<Order>().0);
}
#[test]
fn observer_dynamic_trigger() {
let mut world = World::new();
world.init_resource::<Order>();
let event_a = world.register_event_key::<EventA>();
// SAFETY: we registered `event_a` above and it matches the type of EventA
let observe = unsafe {
Observer::with_dynamic_runner(
|mut world, _observer, _trigger_context, _event, _trigger| {
world.resource_mut::<Order>().observed("event_a");
},
)
.with_event_key(event_a)
};
world.spawn(observe);
world.commands().queue(move |world: &mut World| {
// SAFETY: we registered `event_a` above and it matches the type of EventA
unsafe {
DeferredWorld::from(world).trigger_raw(
event_a,
&mut EventA,
&mut GlobalTrigger,
MaybeLocation::caller(),
);
}
});
world.flush();
assert_eq!(vec!["event_a"], world.resource::<Order>().0);
}
#[test]
fn observer_propagating() {
let mut world = World::new();
world.init_resource::<Order>();
let parent = world.spawn_empty().id();
let child = world.spawn(ChildOf(parent)).id();
world.entity_mut(parent).observe(
move |event: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("parent");
assert_eq!(event.event_target(), parent);
assert_eq!(event.original_event_target(), child);
},
);
world.entity_mut(child).observe(
move |event: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("child");
assert_eq!(event.event_target(), child);
assert_eq!(event.original_event_target(), child);
},
);
world.trigger(EventPropagating(child));
assert_eq!(vec!["child", "parent"], world.resource::<Order>().0);
}
#[test]
fn observer_propagating_redundant_dispatch_same_entity() {
let mut world = World::new();
world.init_resource::<Order>();
let parent = world
.spawn_empty()
.observe(|_: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("parent");
})
.id();
let child = world
.spawn(ChildOf(parent))
.observe(|_: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("child");
})
.id();
world.trigger(EventPropagating(child));
world.trigger(EventPropagating(child));
assert_eq!(
vec!["child", "parent", "child", "parent"],
world.resource::<Order>().0
);
}
#[test]
fn observer_propagating_redundant_dispatch_parent_child() {
let mut world = World::new();
world.init_resource::<Order>();
let parent = world
.spawn_empty()
.observe(|_: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("parent");
})
.id();
let child = world
.spawn(ChildOf(parent))
.observe(|_: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("child");
})
.id();
world.trigger(EventPropagating(child));
world.trigger(EventPropagating(parent));
assert_eq!(
vec!["child", "parent", "parent"],
world.resource::<Order>().0
);
}
#[test]
fn observer_propagating_halt() {
let mut world = World::new();
world.init_resource::<Order>();
let parent = world
.spawn_empty()
.observe(|_: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("parent");
})
.id();
let child = world
.spawn(ChildOf(parent))
.observe(|mut event: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("child");
event.propagate(false);
})
.id();
world.trigger(EventPropagating(child));
assert_eq!(vec!["child"], world.resource::<Order>().0);
}
#[test]
fn observer_propagating_join() {
let mut world = World::new();
world.init_resource::<Order>();
let parent = world
.spawn_empty()
.observe(|_: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("parent");
})
.id();
let child_a = world
.spawn(ChildOf(parent))
.observe(|_: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("child_a");
})
.id();
let child_b = world
.spawn(ChildOf(parent))
.observe(|_: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("child_b");
})
.id();
world.trigger(EventPropagating(child_a));
world.trigger(EventPropagating(child_b));
assert_eq!(
vec!["child_a", "parent", "child_b", "parent"],
world.resource::<Order>().0
);
}
#[test]
fn observer_propagating_no_next() {
let mut world = World::new();
world.init_resource::<Order>();
let entity = world
.spawn_empty()
.observe(|_: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("event");
})
.id();
world.trigger(EventPropagating(entity));
assert_eq!(vec!["event"], world.resource::<Order>().0);
}
#[test]
fn observer_propagating_parallel_propagation() {
let mut world = World::new();
world.init_resource::<Order>();
let parent_a = world
.spawn_empty()
.observe(|_: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("parent_a");
})
.id();
let child_a = world
.spawn(ChildOf(parent_a))
.observe(|mut event: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("child_a");
event.propagate(false);
})
.id();
let parent_b = world
.spawn_empty()
.observe(|_: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("parent_b");
})
.id();
let child_b = world
.spawn(ChildOf(parent_b))
.observe(|_: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("child_b");
})
.id();
world.trigger(EventPropagating(child_a));
world.trigger(EventPropagating(child_b));
assert_eq!(
vec!["child_a", "child_b", "parent_b"],
world.resource::<Order>().0
);
}
#[test]
fn observer_propagating_world() {
let mut world = World::new();
world.init_resource::<Order>();
world.add_observer(|_: On<EventPropagating>, mut res: ResMut<Order>| {
res.observed("event");
});
let grandparent = world.spawn_empty().id();
let parent = world.spawn(ChildOf(grandparent)).id();
let child = world.spawn(ChildOf(parent)).id();
world.trigger(EventPropagating(child));
assert_eq!(vec!["event", "event", "event"], world.resource::<Order>().0);
}
#[test]
fn observer_propagating_world_skipping() {
let mut world = World::new();
world.init_resource::<Order>();
world.add_observer(
|event: On<EventPropagating>, query: Query<&A>, mut res: ResMut<Order>| {
if query.get(event.event_target()).is_ok() {
res.observed("event");
}
},
);
let grandparent = world.spawn(A).id();
let parent = world.spawn(ChildOf(grandparent)).id();
let child = world.spawn((A, ChildOf(parent))).id();
world.trigger(EventPropagating(child));
assert_eq!(vec!["event", "event"], world.resource::<Order>().0);
}
// Originally for https://github.com/bevyengine/bevy/issues/18452
#[test]
| 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/observer/system_param.rs | crates/bevy_ecs/src/observer/system_param.rs | //! System parameters for working with observers.
use crate::{
bundle::Bundle,
change_detection::MaybeLocation,
event::{Event, EventKey, PropagateEntityTrigger},
prelude::*,
traversal::Traversal,
};
use bevy_ptr::Ptr;
use core::{
fmt::Debug,
marker::PhantomData,
ops::{Deref, DerefMut},
};
/// A [system parameter] used by an observer to process events. See [`Observer`] and [`Event`] for examples.
///
/// `On` contains the triggered [`Event`] data for a given run of an `Observer`. It also provides access to the
/// [`Trigger`](crate::event::Trigger), which for things like [`EntityEvent`] with a [`PropagateEntityTrigger`],
/// includes control over event propagation.
///
/// The generic `B: Bundle` is used to further specialize the events that this observer is interested in.
/// The entity involved *does not* have to have these components, but the observer will only be
/// triggered if the event matches the components in `B`.
///
/// This is used to avoid providing a generic argument in your event, as is done for [`Add`]
/// and the other lifecycle events.
///
/// Providing multiple components in this bundle will cause this event to be triggered by any
/// matching component in the bundle,
/// [rather than requiring all of them to be present](https://github.com/bevyengine/bevy/issues/15325).
///
/// [system parameter]: crate::system::SystemParam
// SAFETY WARNING!
// this type must _never_ expose anything with the 'w lifetime
// See the safety discussion on `Trigger` for more details.
pub struct On<'w, 't, E: Event, B: Bundle = ()> {
observer: Entity,
// SAFETY WARNING: never expose this 'w lifetime
event: &'w mut E,
// SAFETY WARNING: never expose this 'w lifetime
trigger: &'w mut E::Trigger<'t>,
// SAFETY WARNING: never expose this 'w lifetime
trigger_context: &'w TriggerContext,
_marker: PhantomData<B>,
}
impl<'w, 't, E: Event, B: Bundle> On<'w, 't, E, B> {
/// Creates a new instance of [`On`] for the given triggered event.
pub fn new(
event: &'w mut E,
observer: Entity,
trigger: &'w mut E::Trigger<'t>,
trigger_context: &'w TriggerContext,
) -> Self {
Self {
event,
observer,
trigger,
trigger_context,
_marker: PhantomData,
}
}
/// Returns the event type of this [`On`] instance.
pub fn event_key(&self) -> EventKey {
self.trigger_context.event_key
}
/// Returns a reference to the triggered event.
pub fn event(&self) -> &E {
self.event
}
/// Returns a mutable reference to the triggered event.
pub fn event_mut(&mut self) -> &mut E {
self.event
}
/// Returns a pointer to the triggered event.
pub fn event_ptr(&self) -> Ptr<'_> {
Ptr::from(&self.event)
}
/// Returns the [`Trigger`](crate::event::Trigger) context for this event.
pub fn trigger(&self) -> &E::Trigger<'t> {
self.trigger
}
/// Returns the mutable [`Trigger`](crate::event::Trigger) context for this event.
pub fn trigger_mut(&mut self) -> &mut E::Trigger<'t> {
self.trigger
}
/// Returns the [`Entity`] of the [`Observer`] of the triggered event.
/// This allows you to despawn the observer, ceasing observation.
///
/// # Examples
///
/// ```rust
/// # use bevy_ecs::prelude::*;
///
/// #[derive(EntityEvent)]
/// struct AssertEvent {
/// entity: Entity,
/// }
///
/// fn assert_observer(event: On<AssertEvent>) {
/// assert_eq!(event.observer(), event.entity);
/// }
///
/// let mut world = World::new();
/// let entity = world.spawn(Observer::new(assert_observer)).id();
///
/// world.trigger(AssertEvent { entity });
/// ```
pub fn observer(&self) -> Entity {
self.observer
}
/// Returns the source code location that triggered this observer, if the `track_location` cargo feature is enabled.
pub fn caller(&self) -> MaybeLocation {
self.trigger_context.caller
}
}
impl<
'w,
't,
const AUTO_PROPAGATE: bool,
E: EntityEvent + for<'a> Event<Trigger<'a> = PropagateEntityTrigger<AUTO_PROPAGATE, E, T>>,
B: Bundle,
T: Traversal<E>,
> On<'w, 't, E, B>
{
/// Returns the original [`Entity`] that this [`EntityEvent`] targeted via [`EntityEvent::event_target`] when it was _first_ triggered,
/// prior to any propagation logic.
pub fn original_event_target(&self) -> Entity {
self.trigger.original_event_target
}
/// Enables or disables event propagation, allowing the same event to trigger observers on a chain of different entities.
///
/// The path an [`EntityEvent`] will propagate along is specified by the [`Traversal`] component defined in [`PropagateEntityTrigger`].
///
/// [`EntityEvent`] does not propagate by default. To enable propagation, you must:
/// + Enable propagation in [`EntityEvent`] using `#[entity_event(propagate)]`. See [`EntityEvent`] for details.
/// + Either call `propagate(true)` in the first observer or in the [`EntityEvent`] derive add `#[entity_event(auto_propagate)]`.
///
/// You can prevent an event from propagating further using `propagate(false)`. This will prevent the event from triggering on the next
/// [`Entity`] in the [`Traversal`], but note that all remaining observers for the _current_ entity will still run.
///
///
/// [`Traversal`]: crate::traversal::Traversal
pub fn propagate(&mut self, should_propagate: bool) {
self.trigger.propagate = should_propagate;
}
/// Returns the value of the flag that controls event propagation. See [`propagate`] for more information.
///
/// [`propagate`]: On::propagate
pub fn get_propagate(&self) -> bool {
self.trigger.propagate
}
}
impl<'w, 't, E: for<'a> Event<Trigger<'a>: Debug> + Debug, B: Bundle> Debug for On<'w, 't, E, B> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("On")
.field("event", &self.event)
.field("trigger", &self.trigger)
.field("_marker", &self._marker)
.finish()
}
}
impl<'w, 't, E: Event, B: Bundle> Deref for On<'w, 't, E, B> {
type Target = E;
fn deref(&self) -> &Self::Target {
self.event
}
}
impl<'w, 't, E: Event, B: Bundle> DerefMut for On<'w, 't, E, B> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.event
}
}
/// Metadata about a specific [`Event`] that triggered an observer.
///
/// This information is exposed via methods on [`On`].
pub struct TriggerContext {
/// The [`EventKey`] the trigger targeted.
pub event_key: EventKey,
/// The location of the source code that triggered the observer.
pub caller: MaybeLocation,
}
| 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/observer/entity_cloning.rs | crates/bevy_ecs/src/observer/entity_cloning.rs | //! Logic to track observers when cloning entities.
use crate::{
component::ComponentCloneBehavior,
entity::{
CloneByFilter, ComponentCloneCtx, EntityClonerBuilder, EntityMapper, SourceComponent,
},
observer::ObservedBy,
world::World,
};
use super::Observer;
impl<Filter: CloneByFilter> EntityClonerBuilder<'_, Filter> {
/// Sets the option to automatically add cloned entities to the observers targeting source entity.
pub fn add_observers(&mut self, add_observers: bool) -> &mut Self {
if add_observers {
self.override_clone_behavior::<ObservedBy>(ComponentCloneBehavior::Custom(
component_clone_observed_by,
))
} else {
self.remove_clone_behavior_override::<ObservedBy>()
}
}
}
fn component_clone_observed_by(_source: &SourceComponent, ctx: &mut ComponentCloneCtx) {
let target = ctx.target();
let source = ctx.source();
ctx.queue_deferred(move |world: &mut World, _mapper: &mut dyn EntityMapper| {
let observed_by = world
.get::<ObservedBy>(source)
.map(|observed_by| observed_by.0.clone())
.expect("Source entity must have ObservedBy");
world
.entity_mut(target)
.insert(ObservedBy(observed_by.clone()));
for observer_entity in observed_by.iter().copied() {
let mut observer_state = world
.get_mut::<Observer>(observer_entity)
.expect("Source observer entity must have Observer");
observer_state.descriptor.entities.push(target);
let event_keys = observer_state.descriptor.event_keys.clone();
let components = observer_state.descriptor.components.clone();
for event_key in event_keys {
let observers = world.observers.get_observers_mut(event_key);
if components.is_empty() {
if let Some(map) = observers.entity_observers.get(&source).cloned() {
observers.entity_observers.insert(target, map);
}
} else {
for component in &components {
let Some(observers) = observers.component_observers.get_mut(component)
else {
continue;
};
if let Some(map) =
observers.entity_component_observers.get(&source).cloned()
{
observers.entity_component_observers.insert(target, map);
}
}
}
}
}
});
}
#[cfg(test)]
mod tests {
use crate::{
entity::{Entity, EntityCloner},
event::EntityEvent,
observer::On,
resource::Resource,
system::ResMut,
world::World,
};
#[derive(Resource, Default)]
struct Num(usize);
#[derive(EntityEvent)]
struct E(Entity);
#[test]
fn clone_entity_with_observer() {
let mut world = World::default();
world.init_resource::<Num>();
let e = world
.spawn_empty()
.observe(|_: On<E>, mut res: ResMut<Num>| res.0 += 1)
.id();
world.trigger(E(e));
let e_clone = world.spawn_empty().id();
EntityCloner::build_opt_out(&mut world)
.add_observers(true)
.clone_entity(e, e_clone);
world.trigger(E(e));
world.trigger(E(e_clone));
assert_eq!(world.resource::<Num>().0, 3);
}
}
| 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/observer/centralized_storage.rs | crates/bevy_ecs/src/observer/centralized_storage.rs | //! Centralized storage for observers, allowing for efficient look-ups.
//!
//! This has multiple levels:
//! - [`World::observers`](crate::world::World::observers) provides access to [`Observers`], which is a central storage for all observers.
//! - [`Observers`] contains multiple distinct caches in the form of [`CachedObservers`].
//! - Most observers are looked up by the [`ComponentId`] of the event they are observing
//! - Lifecycle observers have their own fields to save lookups.
//! - [`CachedObservers`] contains maps of [`ObserverRunner`]s, which are the actual functions that will be run when the observer is triggered.
//! - These are split by target type, in order to allow for different lookup strategies.
//! - [`CachedComponentObservers`] is one of these maps, which contains observers that are specifically targeted at a component.
use bevy_platform::collections::HashMap;
use crate::{
archetype::ArchetypeFlags, component::ComponentId, entity::EntityHashMap, event::EventKey,
observer::ObserverRunner,
};
/// An internal lookup table tracking all of the observers in the world.
///
/// Stores a cache mapping event ids to their registered observers.
/// Some observer kinds (like [lifecycle](crate::lifecycle) observers) have a dedicated field,
/// saving lookups for the most common triggers.
///
/// This can be accessed via [`World::observers`](crate::world::World::observers).
#[derive(Default, Debug)]
pub struct Observers {
// Cached ECS observers to save a lookup for high-traffic built-in event types.
add: CachedObservers,
insert: CachedObservers,
replace: CachedObservers,
remove: CachedObservers,
despawn: CachedObservers,
// Map from event type to set of observers watching for that event
cache: HashMap<EventKey, CachedObservers>,
}
impl Observers {
pub(crate) fn get_observers_mut(&mut self, event_key: EventKey) -> &mut CachedObservers {
use crate::lifecycle::*;
match event_key {
ADD => &mut self.add,
INSERT => &mut self.insert,
REPLACE => &mut self.replace,
REMOVE => &mut self.remove,
DESPAWN => &mut self.despawn,
_ => self.cache.entry(event_key).or_default(),
}
}
/// Attempts to get the observers for the given `event_key`.
///
/// When accessing the observers for lifecycle events, such as [`Add`], [`Insert`], [`Replace`], [`Remove`], and [`Despawn`],
/// use the [`EventKey`] constants from the [`lifecycle`](crate::lifecycle) module.
///
/// [`Add`]: crate::lifecycle::Add
/// [`Insert`]: crate::lifecycle::Insert
/// [`Replace`]: crate::lifecycle::Replace
/// [`Remove`]: crate::lifecycle::Remove
/// [`Despawn`]: crate::lifecycle::Despawn
pub fn try_get_observers(&self, event_key: EventKey) -> Option<&CachedObservers> {
use crate::lifecycle::*;
match event_key {
ADD => Some(&self.add),
INSERT => Some(&self.insert),
REPLACE => Some(&self.replace),
REMOVE => Some(&self.remove),
DESPAWN => Some(&self.despawn),
_ => self.cache.get(&event_key),
}
}
pub(crate) fn is_archetype_cached(event_key: EventKey) -> Option<ArchetypeFlags> {
use crate::lifecycle::*;
match event_key {
ADD => Some(ArchetypeFlags::ON_ADD_OBSERVER),
INSERT => Some(ArchetypeFlags::ON_INSERT_OBSERVER),
REPLACE => Some(ArchetypeFlags::ON_REPLACE_OBSERVER),
REMOVE => Some(ArchetypeFlags::ON_REMOVE_OBSERVER),
DESPAWN => Some(ArchetypeFlags::ON_DESPAWN_OBSERVER),
_ => None,
}
}
pub(crate) fn update_archetype_flags(
&self,
component_id: ComponentId,
flags: &mut ArchetypeFlags,
) {
if self.add.component_observers.contains_key(&component_id) {
flags.insert(ArchetypeFlags::ON_ADD_OBSERVER);
}
if self.insert.component_observers.contains_key(&component_id) {
flags.insert(ArchetypeFlags::ON_INSERT_OBSERVER);
}
if self.replace.component_observers.contains_key(&component_id) {
flags.insert(ArchetypeFlags::ON_REPLACE_OBSERVER);
}
if self.remove.component_observers.contains_key(&component_id) {
flags.insert(ArchetypeFlags::ON_REMOVE_OBSERVER);
}
if self.despawn.component_observers.contains_key(&component_id) {
flags.insert(ArchetypeFlags::ON_DESPAWN_OBSERVER);
}
}
}
/// Collection of [`ObserverRunner`] for [`Observer`](crate::observer::Observer) registered to a particular event.
///
/// This is stored inside of [`Observers`], specialized for each kind of observer.
#[derive(Default, Debug)]
pub struct CachedObservers {
/// Observers watching for any time this event is triggered, regardless of target.
/// These will also respond to events targeting specific components or entities
pub(super) global_observers: ObserverMap,
/// Observers watching for triggers of events for a specific component
pub(super) component_observers: HashMap<ComponentId, CachedComponentObservers>,
/// Observers watching for triggers of events for a specific entity
pub(super) entity_observers: EntityHashMap<ObserverMap>,
}
impl CachedObservers {
/// Observers watching for any time this event is triggered, regardless of target.
/// These will also respond to events targeting specific components or entities
pub fn global_observers(&self) -> &ObserverMap {
&self.global_observers
}
/// Returns observers watching for triggers of events for a specific component.
pub fn component_observers(&self) -> &HashMap<ComponentId, CachedComponentObservers> {
&self.component_observers
}
/// Returns observers watching for triggers of events for a specific entity.
pub fn entity_observers(&self) -> &EntityHashMap<ObserverMap> {
&self.entity_observers
}
}
/// Map between an observer entity and its [`ObserverRunner`]
pub type ObserverMap = EntityHashMap<ObserverRunner>;
/// Collection of [`ObserverRunner`] for [`Observer`](crate::observer::Observer) registered to a particular event targeted at a specific component.
///
/// This is stored inside of [`CachedObservers`].
#[derive(Default, Debug)]
pub struct CachedComponentObservers {
// Observers watching for events targeting this component, but not a specific entity
pub(super) global_observers: ObserverMap,
// Observers watching for events targeting this component on a specific entity
pub(super) entity_component_observers: EntityHashMap<ObserverMap>,
}
impl CachedComponentObservers {
/// Returns observers watching for events targeting this component, but not a specific entity
pub fn global_observers(&self) -> &ObserverMap {
&self.global_observers
}
/// Returns observers watching for events targeting this component on a specific entity
pub fn entity_component_observers(&self) -> &EntityHashMap<ObserverMap> {
&self.entity_component_observers
}
}
| 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/relationship/relationship_query.rs | crates/bevy_ecs/src/relationship/relationship_query.rs | use crate::{
entity::Entity,
query::{QueryData, QueryFilter},
relationship::{Relationship, RelationshipTarget},
system::Query,
};
use alloc::collections::VecDeque;
use smallvec::SmallVec;
use super::SourceIter;
impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> {
/// If the given `entity` contains the `R` [`Relationship`] component, returns the
/// target entity of that relationship.
pub fn related<R: Relationship>(&'w self, entity: Entity) -> Option<Entity>
where
<D as QueryData>::ReadOnly: QueryData<Item<'w, 's> = &'w R>,
{
self.get(entity).map(R::get).ok()
}
/// If the given `entity` contains the `S` [`RelationshipTarget`] component, returns the
/// source entities stored on that component.
pub fn relationship_sources<S: RelationshipTarget>(
&'w self,
entity: Entity,
) -> impl Iterator<Item = Entity> + 'w
where
<D as QueryData>::ReadOnly: QueryData<Item<'w, 's> = &'w S>,
{
self.get(entity)
.into_iter()
.flat_map(RelationshipTarget::iter)
}
/// Recursively walks up the tree defined by the given `R` [`Relationship`] until
/// there are no more related entities, returning the "root entity" of the relationship hierarchy.
///
/// # Warning
///
/// For relationship graphs that contain loops, this could loop infinitely.
/// If your relationship is not a tree (like Bevy's hierarchy), be sure to stop if you encounter a duplicate entity.
pub fn root_ancestor<R: Relationship>(&'w self, entity: Entity) -> Entity
where
<D as QueryData>::ReadOnly: QueryData<Item<'w, 's> = &'w R>,
{
// Recursively search up the tree until we're out of parents
match self.get(entity) {
Ok(parent) => self.root_ancestor(parent.get()),
Err(_) => entity,
}
}
/// Iterates all "leaf entities" as defined by the [`RelationshipTarget`] hierarchy.
///
/// # Warning
///
/// For relationship graphs that contain loops, this could loop infinitely.
/// If your relationship is not a tree (like Bevy's hierarchy), be sure to stop if you encounter a duplicate entity.
pub fn iter_leaves<S: RelationshipTarget>(
&'w self,
entity: Entity,
) -> impl Iterator<Item = Entity> + use<'w, 's, S, D, F>
where
<D as QueryData>::ReadOnly: QueryData<Item<'w, 's> = &'w S>,
SourceIter<'w, S>: DoubleEndedIterator,
{
self.iter_descendants_depth_first(entity).filter(|entity| {
self.get(*entity)
// These are leaf nodes if they have the `Children` component but it's empty
.map(|children| children.len() == 0)
// Or if they don't have the `Children` component at all
.unwrap_or(true)
})
}
/// Iterates all sibling entities that also have the `R` [`Relationship`] with the same target entity.
pub fn iter_siblings<R: Relationship>(
&'w self,
entity: Entity,
) -> impl Iterator<Item = Entity> + 'w
where
D::ReadOnly: QueryData<Item<'w, 's> = (Option<&'w R>, Option<&'w R::RelationshipTarget>)>,
{
self.get(entity)
.ok()
.and_then(|(maybe_parent, _)| maybe_parent.map(R::get))
.and_then(|parent| self.get(parent).ok())
.and_then(|(_, maybe_children)| maybe_children)
.into_iter()
.flat_map(move |children| children.iter().filter(move |child| *child != entity))
}
/// Iterates all descendant entities as defined by the given `entity`'s [`RelationshipTarget`] and their recursive
/// [`RelationshipTarget`].
///
/// # Warning
///
/// For relationship graphs that contain loops, this could loop infinitely.
/// If your relationship is not a tree (like Bevy's hierarchy), be sure to stop if you encounter a duplicate entity.
pub fn iter_descendants<S: RelationshipTarget>(
&'w self,
entity: Entity,
) -> DescendantIter<'w, 's, D, F, S>
where
D::ReadOnly: QueryData<Item<'w, 's> = &'w S>,
{
DescendantIter::new(self, entity)
}
/// Iterates all descendant entities as defined by the given `entity`'s [`RelationshipTarget`] and their recursive
/// [`RelationshipTarget`] in depth-first order.
///
/// # Warning
///
/// For relationship graphs that contain loops, this could loop infinitely.
/// If your relationship is not a tree (like Bevy's hierarchy), be sure to stop if you encounter a duplicate entity.
pub fn iter_descendants_depth_first<S: RelationshipTarget>(
&'w self,
entity: Entity,
) -> DescendantDepthFirstIter<'w, 's, D, F, S>
where
D::ReadOnly: QueryData<Item<'w, 's> = &'w S>,
SourceIter<'w, S>: DoubleEndedIterator,
{
DescendantDepthFirstIter::new(self, entity)
}
/// Iterates all ancestors of the given `entity` as defined by the `R` [`Relationship`].
///
/// # Warning
///
/// For relationship graphs that contain loops, this could loop infinitely.
/// If your relationship is not a tree (like Bevy's hierarchy), be sure to stop if you encounter a duplicate entity.
pub fn iter_ancestors<R: Relationship>(
&'w self,
entity: Entity,
) -> AncestorIter<'w, 's, D, F, R>
where
D::ReadOnly: QueryData<Item<'w, 's> = &'w R>,
{
AncestorIter::new(self, entity)
}
}
/// An [`Iterator`] of [`Entity`]s over the descendants of an [`Entity`].
///
/// Traverses the hierarchy breadth-first.
pub struct DescendantIter<'w, 's, D: QueryData, F: QueryFilter, S: RelationshipTarget>
where
D::ReadOnly: QueryData<Item<'w, 's> = &'w S>,
{
children_query: &'w Query<'w, 's, D, F>,
vecdeque: VecDeque<Entity>,
}
impl<'w, 's, D: QueryData, F: QueryFilter, S: RelationshipTarget> DescendantIter<'w, 's, D, F, S>
where
D::ReadOnly: QueryData<Item<'w, 's> = &'w S>,
{
/// Returns a new [`DescendantIter`].
pub fn new(children_query: &'w Query<'w, 's, D, F>, entity: Entity) -> Self {
DescendantIter {
children_query,
vecdeque: children_query
.get(entity)
.into_iter()
.flat_map(RelationshipTarget::iter)
.collect(),
}
}
}
impl<'w, 's, D: QueryData, F: QueryFilter, S: RelationshipTarget> Iterator
for DescendantIter<'w, 's, D, F, S>
where
D::ReadOnly: QueryData<Item<'w, 's> = &'w S>,
{
type Item = Entity;
fn next(&mut self) -> Option<Self::Item> {
let entity = self.vecdeque.pop_front()?;
if let Ok(children) = self.children_query.get(entity) {
self.vecdeque.extend(children.iter());
}
Some(entity)
}
}
/// An [`Iterator`] of [`Entity`]s over the descendants of an [`Entity`].
///
/// Traverses the hierarchy depth-first.
pub struct DescendantDepthFirstIter<'w, 's, D: QueryData, F: QueryFilter, S: RelationshipTarget>
where
D::ReadOnly: QueryData<Item<'w, 's> = &'w S>,
{
children_query: &'w Query<'w, 's, D, F>,
stack: SmallVec<[Entity; 8]>,
}
impl<'w, 's, D: QueryData, F: QueryFilter, S: RelationshipTarget>
DescendantDepthFirstIter<'w, 's, D, F, S>
where
D::ReadOnly: QueryData<Item<'w, 's> = &'w S>,
SourceIter<'w, S>: DoubleEndedIterator,
{
/// Returns a new [`DescendantDepthFirstIter`].
pub fn new(children_query: &'w Query<'w, 's, D, F>, entity: Entity) -> Self {
DescendantDepthFirstIter {
children_query,
stack: children_query
.get(entity)
.map_or(SmallVec::new(), |children| children.iter().rev().collect()),
}
}
}
impl<'w, 's, D: QueryData, F: QueryFilter, S: RelationshipTarget> Iterator
for DescendantDepthFirstIter<'w, 's, D, F, S>
where
D::ReadOnly: QueryData<Item<'w, 's> = &'w S>,
SourceIter<'w, S>: DoubleEndedIterator,
{
type Item = Entity;
fn next(&mut self) -> Option<Self::Item> {
let entity = self.stack.pop()?;
if let Ok(children) = self.children_query.get(entity) {
self.stack.extend(children.iter().rev());
}
Some(entity)
}
}
/// An [`Iterator`] of [`Entity`]s over the ancestors of an [`Entity`].
pub struct AncestorIter<'w, 's, D: QueryData, F: QueryFilter, R: Relationship>
where
D::ReadOnly: QueryData<Item<'w, 's> = &'w R>,
{
parent_query: &'w Query<'w, 's, D, F>,
next: Option<Entity>,
}
impl<'w, 's, D: QueryData, F: QueryFilter, R: Relationship> AncestorIter<'w, 's, D, F, R>
where
D::ReadOnly: QueryData<Item<'w, 's> = &'w R>,
{
/// Returns a new [`AncestorIter`].
pub fn new(parent_query: &'w Query<'w, 's, D, F>, entity: Entity) -> Self {
AncestorIter {
parent_query,
next: Some(entity),
}
}
}
impl<'w, 's, D: QueryData, F: QueryFilter, R: Relationship> Iterator
for AncestorIter<'w, 's, D, F, R>
where
D::ReadOnly: QueryData<Item<'w, 's> = &'w R>,
{
type Item = Entity;
fn next(&mut self) -> Option<Self::Item> {
self.next = self.parent_query.get(self.next?).ok().map(R::get);
self.next
}
}
| 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/relationship/related_methods.rs | crates/bevy_ecs/src/relationship/related_methods.rs | use crate::{
bundle::Bundle,
entity::{hash_set::EntityHashSet, Entity},
prelude::Children,
relationship::{
Relationship, RelationshipHookMode, RelationshipSourceCollection, RelationshipTarget,
},
system::{Commands, EntityCommands},
world::{DeferredWorld, EntityWorldMut, World},
};
use bevy_platform::prelude::{Box, Vec};
use core::{marker::PhantomData, mem};
use super::OrderedRelationshipSourceCollection;
impl<'w> EntityWorldMut<'w> {
/// Spawns a entity related to this entity (with the `R` relationship) by taking a bundle
pub fn with_related<R: Relationship>(&mut self, bundle: impl Bundle) -> &mut Self {
let parent = self.id();
self.world_scope(|world| {
world.spawn((bundle, R::from(parent)));
});
self
}
/// Spawns entities related to this entity (with the `R` relationship) by taking a function that operates on a [`RelatedSpawner`].
pub fn with_related_entities<R: Relationship>(
&mut self,
func: impl FnOnce(&mut RelatedSpawner<R>),
) -> &mut Self {
let parent = self.id();
self.world_scope(|world| {
func(&mut RelatedSpawner::new(world, parent));
});
self
}
/// Relates the given entities to this entity with the relation `R`.
///
/// See [`add_one_related`](Self::add_one_related) if you want relate only one entity.
pub fn add_related<R: Relationship>(&mut self, related: &[Entity]) -> &mut Self {
let id = self.id();
self.world_scope(|world| {
for related in related {
world
.entity_mut(*related)
.modify_or_insert_relation_with_relationship_hook_mode::<R>(
id,
RelationshipHookMode::Run,
);
}
});
self
}
/// Removes the relation `R` between this entity and all its related entities.
pub fn detach_all_related<R: Relationship>(&mut self) -> &mut Self {
self.remove::<R::RelationshipTarget>()
}
/// Relates the given entities to this entity with the relation `R`, starting at this particular index.
///
/// If the `related` has duplicates, a related entity will take the index of its last occurrence in `related`.
/// If the indices go out of bounds, they will be clamped into bounds.
/// This will not re-order existing related entities unless they are in `related`.
///
/// # Example
///
/// ```
/// use bevy_ecs::prelude::*;
///
/// let mut world = World::new();
/// let e0 = world.spawn_empty().id();
/// let e1 = world.spawn_empty().id();
/// let e2 = world.spawn_empty().id();
/// let e3 = world.spawn_empty().id();
/// let e4 = world.spawn_empty().id();
///
/// let mut main_entity = world.spawn_empty();
/// main_entity.add_related::<ChildOf>(&[e0, e1, e2, e2]);
/// main_entity.insert_related::<ChildOf>(1, &[e0, e3, e4, e4]);
/// let main_id = main_entity.id();
///
/// let relationship_source = main_entity.get::<Children>().unwrap().collection();
/// assert_eq!(relationship_source, &[e1, e0, e3, e2, e4]);
/// ```
pub fn insert_related<R: Relationship>(&mut self, index: usize, related: &[Entity]) -> &mut Self
where
<R::RelationshipTarget as RelationshipTarget>::Collection:
OrderedRelationshipSourceCollection,
{
let id = self.id();
self.world_scope(|world| {
for (offset, related) in related.iter().enumerate() {
let index = index.saturating_add(offset);
if world
.get::<R>(*related)
.is_some_and(|relationship| relationship.get() == id)
{
world
.get_mut::<R::RelationshipTarget>(id)
.expect("hooks should have added relationship target")
.collection_mut_risky()
.place(*related, index);
} else {
world
.entity_mut(*related)
.modify_or_insert_relation_with_relationship_hook_mode::<R>(
id,
RelationshipHookMode::Run,
);
world
.get_mut::<R::RelationshipTarget>(id)
.expect("hooks should have added relationship target")
.collection_mut_risky()
.place_most_recent(index);
}
}
});
self
}
/// Removes the relation `R` between this entity and the given entities.
pub fn remove_related<R: Relationship>(&mut self, related: &[Entity]) -> &mut Self {
let id = self.id();
self.world_scope(|world| {
for related in related {
if world
.get::<R>(*related)
.is_some_and(|relationship| relationship.get() == id)
{
world.entity_mut(*related).remove::<R>();
}
}
});
self
}
/// Replaces all the related entities with a new set of entities.
pub fn replace_related<R: Relationship>(&mut self, related: &[Entity]) -> &mut Self {
type Collection<R> =
<<R as Relationship>::RelationshipTarget as RelationshipTarget>::Collection;
if related.is_empty() {
self.remove::<R::RelationshipTarget>();
return self;
}
let Some(existing_relations) = self.get_mut::<R::RelationshipTarget>() else {
return self.add_related::<R>(related);
};
// We replace the component here with a dummy value so we can modify it without taking it (this would create archetype move).
// SAFETY: We eventually return the correctly initialized collection into the target.
let mut relations = mem::replace(
existing_relations.into_inner(),
<R as Relationship>::RelationshipTarget::from_collection_risky(
Collection::<R>::with_capacity(0),
),
);
let collection = relations.collection_mut_risky();
let mut potential_relations = EntityHashSet::from_iter(related.iter().copied());
let id = self.id();
self.world_scope(|world| {
for related in collection.iter() {
if !potential_relations.remove(related) {
world.entity_mut(related).remove::<R>();
}
}
for related in potential_relations {
// SAFETY: We'll manually be adjusting the contents of the `RelationshipTarget` to fit the final state.
world
.entity_mut(related)
.modify_or_insert_relation_with_relationship_hook_mode::<R>(
id,
RelationshipHookMode::Skip,
);
}
});
// SAFETY: The entities we're inserting will be the entities that were either already there or entities that we've just inserted.
collection.clear();
collection.extend_from_iter(related.iter().copied());
self.insert(relations);
self
}
/// Replaces all the related entities with a new set of entities.
///
/// This is a more efficient of [`Self::replace_related`] which doesn't allocate.
/// The passed in arguments must adhere to these invariants:
/// - `entities_to_unrelate`: A slice of entities to remove from the relationship source.
/// Entities need not be related to this entity, but must not appear in `entities_to_relate`
/// - `entities_to_relate`: A slice of entities to relate to this entity.
/// This must contain all entities that will remain related (i.e. not those in `entities_to_unrelate`) plus the newly related entities.
/// - `newly_related_entities`: A subset of `entities_to_relate` containing only entities not already related to this entity.
/// - Slices **must not** contain any duplicates
///
/// # Warning
///
/// Violating these invariants may lead to panics, crashes or unpredictable engine behavior.
///
/// # Panics
///
/// Panics when debug assertions are enabled and any invariants are broken.
///
// TODO: Consider making these iterators so users aren't required to allocate a separate buffers for the different slices.
pub fn replace_related_with_difference<R: Relationship>(
&mut self,
entities_to_unrelate: &[Entity],
entities_to_relate: &[Entity],
newly_related_entities: &[Entity],
) -> &mut Self {
#[cfg(debug_assertions)]
{
let entities_to_relate = EntityHashSet::from_iter(entities_to_relate.iter().copied());
let entities_to_unrelate =
EntityHashSet::from_iter(entities_to_unrelate.iter().copied());
let mut newly_related_entities =
EntityHashSet::from_iter(newly_related_entities.iter().copied());
assert!(
entities_to_relate.is_disjoint(&entities_to_unrelate),
"`entities_to_relate` ({entities_to_relate:?}) shared entities with `entities_to_unrelate` ({entities_to_unrelate:?})"
);
assert!(
newly_related_entities.is_disjoint(&entities_to_unrelate),
"`newly_related_entities` ({newly_related_entities:?}) shared entities with `entities_to_unrelate ({entities_to_unrelate:?})`"
);
assert!(
newly_related_entities.is_subset(&entities_to_relate),
"`newly_related_entities` ({newly_related_entities:?}) wasn't a subset of `entities_to_relate` ({entities_to_relate:?})"
);
if let Some(target) = self.get::<R::RelationshipTarget>() {
let existing_relationships: EntityHashSet = target.collection().iter().collect();
assert!(
existing_relationships.is_disjoint(&newly_related_entities),
"`newly_related_entities` contains an entity that wouldn't be newly related"
);
newly_related_entities.extend(existing_relationships);
newly_related_entities -= &entities_to_unrelate;
}
assert_eq!(newly_related_entities, entities_to_relate, "`entities_to_relate` ({entities_to_relate:?}) didn't contain all entities that would end up related");
};
match self.get_mut::<R::RelationshipTarget>() {
None => {
self.add_related::<R>(entities_to_relate);
return self;
}
Some(mut target) => {
// SAFETY: The invariants expected by this function mean we'll only be inserting entities that are already related.
let collection = target.collection_mut_risky();
collection.clear();
collection.extend_from_iter(entities_to_relate.iter().copied());
}
}
let this = self.id();
self.world_scope(|world| {
for unrelate in entities_to_unrelate {
world.entity_mut(*unrelate).remove::<R>();
}
for new_relation in newly_related_entities {
// We changed the target collection manually so don't run the insert hook
world
.entity_mut(*new_relation)
.modify_or_insert_relation_with_relationship_hook_mode::<R>(
this,
RelationshipHookMode::Skip,
);
}
});
self
}
/// Relates the given entity to this with the relation `R`.
///
/// See [`add_related`](Self::add_related) if you want to relate more than one entity.
pub fn add_one_related<R: Relationship>(&mut self, entity: Entity) -> &mut Self {
self.add_related::<R>(&[entity])
}
/// Despawns entities that relate to this one via the given [`RelationshipTarget`].
/// This entity will not be despawned.
pub fn despawn_related<S: RelationshipTarget>(&mut self) -> &mut Self {
if let Some(sources) = self.get::<S>() {
// We have to collect here to defer removal, allowing observers and hooks to see this data
// before it is finally removed.
let sources = sources.iter().collect::<Vec<_>>();
self.world_scope(|world| {
for entity in sources {
if let Ok(entity_mut) = world.get_entity_mut(entity) {
entity_mut.despawn();
};
}
});
}
self
}
/// Despawns the children of this entity.
/// This entity will not be despawned.
///
/// This is a specialization of [`despawn_related`](EntityWorldMut::despawn_related), a more general method for despawning via relationships.
pub fn despawn_children(&mut self) -> &mut Self {
self.despawn_related::<Children>();
self
}
/// Inserts a component or bundle of components into the entity and all related entities,
/// traversing the relationship tracked in `S` in a breadth-first manner.
///
/// # Warning
///
/// This method should only be called on relationships that form a tree-like structure.
/// Any cycles will cause this method to loop infinitely.
// We could keep track of a list of visited entities and track cycles,
// but this is not a very well-defined operation (or hard to write) for arbitrary relationships.
pub fn insert_recursive<S: RelationshipTarget>(
&mut self,
bundle: impl Bundle + Clone,
) -> &mut Self {
self.insert(bundle.clone());
if let Some(relationship_target) = self.get::<S>() {
let related_vec: Vec<Entity> = relationship_target.iter().collect();
for related in related_vec {
self.world_scope(|world| {
world
.entity_mut(related)
.insert_recursive::<S>(bundle.clone());
});
}
}
self
}
/// Removes a component or bundle of components of type `B` from the entity and all related entities,
/// traversing the relationship tracked in `S` in a breadth-first manner.
///
/// # Warning
///
/// This method should only be called on relationships that form a tree-like structure.
/// Any cycles will cause this method to loop infinitely.
pub fn remove_recursive<S: RelationshipTarget, B: Bundle>(&mut self) -> &mut Self {
self.remove::<B>();
if let Some(relationship_target) = self.get::<S>() {
let related_vec: Vec<Entity> = relationship_target.iter().collect();
for related in related_vec {
self.world_scope(|world| {
world.entity_mut(related).remove_recursive::<S, B>();
});
}
}
self
}
fn modify_or_insert_relation_with_relationship_hook_mode<R: Relationship>(
&mut self,
entity: Entity,
relationship_hook_mode: RelationshipHookMode,
) {
// Check if the relation edge holds additional data
if size_of::<R>() > size_of::<Entity>() {
self.assert_not_despawned();
let this = self.id();
let modified = self.world_scope(|world| {
let modified = DeferredWorld::from(&mut *world)
.modify_component_with_relationship_hook_mode::<R, _>(
this,
relationship_hook_mode,
|r| r.set_risky(entity),
)
.expect("entity access must be valid")
.is_some();
world.flush();
modified
});
if modified {
return;
}
}
self.insert_with_relationship_hook_mode(R::from(entity), relationship_hook_mode);
}
}
impl<'a> EntityCommands<'a> {
/// Spawns a entity related to this entity (with the `R` relationship) by taking a bundle
pub fn with_related<R: Relationship>(&mut self, bundle: impl Bundle) -> &mut Self {
let parent = self.id();
self.commands.spawn((bundle, R::from(parent)));
self
}
/// Spawns entities related to this entity (with the `R` relationship) by taking a function that operates on a [`RelatedSpawner`].
pub fn with_related_entities<R: Relationship>(
&mut self,
func: impl FnOnce(&mut RelatedSpawnerCommands<R>),
) -> &mut Self {
let id = self.id();
func(&mut RelatedSpawnerCommands::new(self.commands(), id));
self
}
/// Relates the given entities to this entity with the relation `R`.
///
/// See [`add_one_related`](Self::add_one_related) if you want relate only one entity.
pub fn add_related<R: Relationship>(&mut self, related: &[Entity]) -> &mut Self {
let related: Box<[Entity]> = related.into();
self.queue(move |mut entity: EntityWorldMut| {
entity.add_related::<R>(&related);
})
}
/// Removes the relation `R` between this entity and all its related entities.
pub fn detach_all_related<R: Relationship>(&mut self) -> &mut Self {
self.queue(|mut entity: EntityWorldMut| {
entity.detach_all_related::<R>();
})
}
/// Relates the given entities to this entity with the relation `R`, starting at this particular index.
///
/// If the `related` has duplicates, a related entity will take the index of its last occurrence in `related`.
/// If the indices go out of bounds, they will be clamped into bounds.
/// This will not re-order existing related entities unless they are in `related`.
pub fn insert_related<R: Relationship>(&mut self, index: usize, related: &[Entity]) -> &mut Self
where
<R::RelationshipTarget as RelationshipTarget>::Collection:
OrderedRelationshipSourceCollection,
{
let related: Box<[Entity]> = related.into();
self.queue(move |mut entity: EntityWorldMut| {
entity.insert_related::<R>(index, &related);
})
}
/// Relates the given entity to this with the relation `R`.
///
/// See [`add_related`](Self::add_related) if you want to relate more than one entity.
pub fn add_one_related<R: Relationship>(&mut self, entity: Entity) -> &mut Self {
self.add_related::<R>(&[entity])
}
/// Removes the relation `R` between this entity and the given entities.
pub fn remove_related<R: Relationship>(&mut self, related: &[Entity]) -> &mut Self {
let related: Box<[Entity]> = related.into();
self.queue(move |mut entity: EntityWorldMut| {
entity.remove_related::<R>(&related);
})
}
/// Replaces all the related entities with the given set of new related entities.
pub fn replace_related<R: Relationship>(&mut self, related: &[Entity]) -> &mut Self {
let related: Box<[Entity]> = related.into();
self.queue(move |mut entity: EntityWorldMut| {
entity.replace_related::<R>(&related);
})
}
/// 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 enable, an invariant is are broken and the command is executed.
pub fn replace_related_with_difference<R: Relationship>(
&mut self,
entities_to_unrelate: &[Entity],
entities_to_relate: &[Entity],
newly_related_entities: &[Entity],
) -> &mut Self {
let entities_to_unrelate: Box<[Entity]> = entities_to_unrelate.into();
let entities_to_relate: Box<[Entity]> = entities_to_relate.into();
let newly_related_entities: Box<[Entity]> = newly_related_entities.into();
self.queue(move |mut entity: EntityWorldMut| {
entity.replace_related_with_difference::<R>(
&entities_to_unrelate,
&entities_to_relate,
&newly_related_entities,
);
})
}
/// Despawns entities that relate to this one via the given [`RelationshipTarget`].
/// This entity will not be despawned.
pub fn despawn_related<S: RelationshipTarget>(&mut self) -> &mut Self {
self.queue(move |mut entity: EntityWorldMut| {
entity.despawn_related::<S>();
})
}
/// Despawns the children of this entity.
/// This entity will not be despawned.
///
/// This is a specialization of [`despawn_related`](EntityCommands::despawn_related), a more general method for despawning via relationships.
pub fn despawn_children(&mut self) -> &mut Self {
self.despawn_related::<Children>()
}
/// Inserts a component or bundle of components into the entity and all related entities,
/// traversing the relationship tracked in `S` in a breadth-first manner.
///
/// # Warning
///
/// This method should only be called on relationships that form a tree-like structure.
/// Any cycles will cause this method to loop infinitely.
pub fn insert_recursive<S: RelationshipTarget>(
&mut self,
bundle: impl Bundle + Clone,
) -> &mut Self {
self.queue(move |mut entity: EntityWorldMut| {
entity.insert_recursive::<S>(bundle);
})
}
/// Removes a component or bundle of components of type `B` from the entity and all related entities,
/// traversing the relationship tracked in `S` in a breadth-first manner.
///
/// # Warning
///
/// This method should only be called on relationships that form a tree-like structure.
/// Any cycles will cause this method to loop infinitely.
pub fn remove_recursive<S: RelationshipTarget, B: Bundle>(&mut self) -> &mut Self {
self.queue(move |mut entity: EntityWorldMut| {
entity.remove_recursive::<S, B>();
})
}
}
/// Directly spawns related "source" entities with the given [`Relationship`], targeting
/// a specific entity.
pub struct RelatedSpawner<'w, R: Relationship> {
target: Entity,
world: &'w mut World,
_marker: PhantomData<R>,
}
impl<'w, R: Relationship> RelatedSpawner<'w, R> {
/// Creates a new instance that will spawn entities targeting the `target` entity.
pub fn new(world: &'w mut World, target: Entity) -> Self {
Self {
world,
target,
_marker: PhantomData,
}
}
/// Spawns an entity with the given `bundle` and an `R` relationship targeting the `target`
/// entity this spawner was initialized with.
pub fn spawn(&mut self, bundle: impl Bundle) -> EntityWorldMut<'_> {
self.world.spawn((R::from(self.target), bundle))
}
/// Spawns an entity with an `R` relationship targeting the `target`
/// entity this spawner was initialized with.
pub fn spawn_empty(&mut self) -> EntityWorldMut<'_> {
self.world.spawn(R::from(self.target))
}
/// Returns the "target entity" used when spawning entities with an `R` [`Relationship`].
pub fn target_entity(&self) -> Entity {
self.target
}
/// Returns a reference to the underlying [`World`].
pub fn world(&self) -> &World {
self.world
}
/// Returns a mutable reference to the underlying [`World`].
pub fn world_mut(&mut self) -> &mut World {
self.world
}
}
/// Uses commands to spawn related "source" entities with the given [`Relationship`], targeting
/// a specific entity.
pub struct RelatedSpawnerCommands<'w, R: Relationship> {
target: Entity,
commands: Commands<'w, 'w>,
_marker: PhantomData<R>,
}
impl<'w, R: Relationship> RelatedSpawnerCommands<'w, R> {
/// Creates a new instance that will spawn entities targeting the `target` entity.
pub fn new(commands: Commands<'w, 'w>, target: Entity) -> Self {
Self {
commands,
target,
_marker: PhantomData,
}
}
/// Spawns an entity with the given `bundle` and an `R` relationship targeting the `target`
/// entity this spawner was initialized with.
pub fn spawn(&mut self, bundle: impl Bundle) -> EntityCommands<'_> {
self.commands.spawn((R::from(self.target), bundle))
}
/// Spawns an entity with an `R` relationship targeting the `target`
/// entity this spawner was initialized with.
pub fn spawn_empty(&mut self) -> EntityCommands<'_> {
self.commands.spawn(R::from(self.target))
}
/// Returns the "target entity" used when spawning entities with an `R` [`Relationship`].
pub fn target_entity(&self) -> Entity {
self.target
}
/// Returns the underlying [`Commands`].
pub fn commands(&mut self) -> Commands<'_, '_> {
self.commands.reborrow()
}
/// Returns a mutable reference to the underlying [`Commands`].
pub fn commands_mut(&mut self) -> &mut Commands<'w, 'w> {
&mut self.commands
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::prelude::{ChildOf, Children, Component};
#[derive(Component, Clone, Copy)]
struct TestComponent;
#[test]
fn insert_and_remove_recursive() {
let mut world = World::new();
let a = world.spawn_empty().id();
let b = world.spawn(ChildOf(a)).id();
let c = world.spawn(ChildOf(a)).id();
let d = world.spawn(ChildOf(b)).id();
world
.entity_mut(a)
.insert_recursive::<Children>(TestComponent);
for entity in [a, b, c, d] {
assert!(world.entity(entity).contains::<TestComponent>());
}
world
.entity_mut(b)
.remove_recursive::<Children, TestComponent>();
// Parent
assert!(world.entity(a).contains::<TestComponent>());
// Target
assert!(!world.entity(b).contains::<TestComponent>());
// Sibling
assert!(world.entity(c).contains::<TestComponent>());
// Child
assert!(!world.entity(d).contains::<TestComponent>());
world
.entity_mut(a)
.remove_recursive::<Children, TestComponent>();
for entity in [a, b, c, d] {
assert!(!world.entity(entity).contains::<TestComponent>());
}
}
#[test]
fn remove_all_related() {
let mut world = World::new();
let a = world.spawn_empty().id();
let b = world.spawn(ChildOf(a)).id();
let c = world.spawn(ChildOf(a)).id();
world.entity_mut(a).detach_all_related::<ChildOf>();
assert_eq!(world.entity(a).get::<Children>(), None);
assert_eq!(world.entity(b).get::<ChildOf>(), None);
assert_eq!(world.entity(c).get::<ChildOf>(), None);
}
#[test]
fn replace_related_works() {
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 parent = world.spawn_empty();
parent.add_children(&[child1, child2]);
let child_value = ChildOf(parent.id());
let some_child = Some(&child_value);
parent.replace_children(&[child2, child3]);
let children = parent.get::<Children>().unwrap().collection();
assert_eq!(children, &[child2, child3]);
assert_eq!(parent.world().get::<ChildOf>(child1), None);
assert_eq!(parent.world().get::<ChildOf>(child2), some_child);
assert_eq!(parent.world().get::<ChildOf>(child3), some_child);
parent.replace_children_with_difference(&[child3], &[child1, child2], &[child1]);
let children = parent.get::<Children>().unwrap().collection();
assert_eq!(children, &[child1, child2]);
assert_eq!(parent.world().get::<ChildOf>(child1), some_child);
assert_eq!(parent.world().get::<ChildOf>(child2), some_child);
assert_eq!(parent.world().get::<ChildOf>(child3), None);
}
#[test]
fn add_related_keeps_relationship_data() {
#[derive(Component, PartialEq, Debug)]
#[relationship(relationship_target = Parent)]
struct Child {
#[relationship]
parent: Entity,
data: u8,
}
#[derive(Component)]
#[relationship_target(relationship = Child)]
struct Parent(Vec<Entity>);
let mut world = World::new();
let parent1 = world.spawn_empty().id();
let parent2 = world.spawn_empty().id();
let child = world
.spawn(Child {
parent: parent1,
data: 42,
})
.id();
world.entity_mut(parent2).add_related::<Child>(&[child]);
assert_eq!(
world.get::<Child>(child),
Some(&Child {
parent: parent2,
data: 42
})
);
}
#[test]
fn insert_related_keeps_relationship_data() {
#[derive(Component, PartialEq, Debug)]
#[relationship(relationship_target = Parent)]
struct Child {
#[relationship]
parent: Entity,
data: u8,
}
#[derive(Component)]
#[relationship_target(relationship = Child)]
struct Parent(Vec<Entity>);
let mut world = World::new();
let parent1 = world.spawn_empty().id();
let parent2 = world.spawn_empty().id();
let child = world
.spawn(Child {
parent: parent1,
data: 42,
})
.id();
world
.entity_mut(parent2)
.insert_related::<Child>(0, &[child]);
assert_eq!(
world.get::<Child>(child),
Some(&Child {
parent: parent2,
data: 42
})
);
}
#[test]
fn replace_related_keeps_relationship_data() {
#[derive(Component, PartialEq, Debug)]
#[relationship(relationship_target = Parent)]
struct Child {
#[relationship]
parent: Entity,
data: u8,
}
#[derive(Component)]
#[relationship_target(relationship = Child)]
struct Parent(Vec<Entity>);
let mut world = World::new();
let parent1 = world.spawn_empty().id();
let parent2 = world.spawn_empty().id();
let child = world
.spawn(Child {
parent: parent1,
data: 42,
})
.id();
world
.entity_mut(parent2)
.replace_related_with_difference::<Child>(&[], &[child], &[child]);
assert_eq!(
world.get::<Child>(child),
Some(&Child {
parent: parent2,
data: 42
})
);
world.entity_mut(parent1).replace_related::<Child>(&[child]);
assert_eq!(
world.get::<Child>(child),
Some(&Child {
parent: parent1,
data: 42
})
);
}
#[test]
fn replace_related_keeps_relationship_target_data() {
#[derive(Component)]
#[relationship(relationship_target = Parent)]
struct Child(Entity);
#[derive(Component)]
#[relationship_target(relationship = Child)]
struct Parent {
#[relationship]
children: Vec<Entity>,
data: u8,
}
let mut world = World::new();
let child1 = world.spawn_empty().id();
let child2 = world.spawn_empty().id();
let mut parent = world.spawn_empty();
parent.add_related::<Child>(&[child1]);
parent.get_mut::<Parent>().unwrap().data = 42;
parent.replace_related_with_difference::<Child>(&[child1], &[child2], &[child2]);
let data = parent.get::<Parent>().unwrap().data;
assert_eq!(data, 42);
parent.replace_related::<Child>(&[child1]);
let data = parent.get::<Parent>().unwrap().data;
assert_eq!(data, 42);
}
#[test]
| 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/relationship/mod.rs | crates/bevy_ecs/src/relationship/mod.rs | //! This module provides functionality to link entities to each other using specialized components called "relationships". See the [`Relationship`] trait for more info.
mod related_methods;
mod relationship_query;
mod relationship_source_collection;
use alloc::boxed::Box;
use bevy_ptr::Ptr;
use core::marker::PhantomData;
use alloc::format;
use bevy_utils::prelude::DebugName;
pub use related_methods::*;
pub use relationship_query::*;
pub use relationship_source_collection::*;
use crate::{
component::{Component, ComponentCloneBehavior, Mutable},
entity::{ComponentCloneCtx, Entity},
error::CommandWithEntity,
lifecycle::HookContext,
world::{DeferredWorld, EntityWorldMut},
};
use log::warn;
/// A [`Component`] on a "source" [`Entity`] that references another target [`Entity`], creating a "relationship" between them. Every [`Relationship`]
/// has a corresponding [`RelationshipTarget`] type (and vice-versa), which exists on the "target" entity of a relationship and contains the list of all
/// "source" entities that relate to the given "target"
///
/// The [`Relationship`] component is the "source of truth" and the [`RelationshipTarget`] component reflects that source of truth. When a [`Relationship`]
/// component is inserted on an [`Entity`], the corresponding [`RelationshipTarget`] component is immediately inserted on the target component if it does
/// not already exist, and the "source" entity is automatically added to the [`RelationshipTarget`] collection (this is done via "component hooks").
///
/// A common example of a [`Relationship`] is the parent / child relationship. Bevy ECS includes a canonical form of this via the [`ChildOf`](crate::hierarchy::ChildOf)
/// [`Relationship`] and the [`Children`](crate::hierarchy::Children) [`RelationshipTarget`].
///
/// [`Relationship`] and [`RelationshipTarget`] should always be derived via the [`Component`] trait to ensure the hooks are set up properly.
///
/// ## Derive
///
/// [`Relationship`] and [`RelationshipTarget`] can only be derived for structs with a single unnamed field, single named field
/// or for named structs where one field is annotated with `#[relationship]`.
/// If there are additional fields, they must all implement [`Default`].
///
/// [`RelationshipTarget`] also requires that the relationship field is private to prevent direct mutation,
/// ensuring the correctness of relationships.
/// ```
/// # use bevy_ecs::component::Component;
/// # use bevy_ecs::entity::Entity;
/// #[derive(Component)]
/// #[relationship(relationship_target = Children)]
/// pub struct ChildOf {
/// #[relationship]
/// pub parent: Entity,
/// internal: u8,
/// };
///
/// #[derive(Component)]
/// #[relationship_target(relationship = ChildOf)]
/// pub struct Children(Vec<Entity>);
/// ```
///
/// When deriving [`RelationshipTarget`] you can specify the `#[relationship_target(linked_spawn)]` attribute to
/// automatically despawn entities stored in an entity's [`RelationshipTarget`] when that entity is despawned:
///
/// ```
/// # use bevy_ecs::component::Component;
/// # use bevy_ecs::entity::Entity;
/// #[derive(Component)]
/// #[relationship(relationship_target = Children)]
/// pub struct ChildOf(pub Entity);
///
/// #[derive(Component)]
/// #[relationship_target(relationship = ChildOf, linked_spawn)]
/// pub struct Children(Vec<Entity>);
/// ```
pub trait Relationship: Component + Sized {
/// The [`Component`] added to the "target" entities of this [`Relationship`], which contains the list of all "source"
/// entities that relate to the "target".
type RelationshipTarget: RelationshipTarget<Relationship = Self>;
/// Gets the [`Entity`] ID of the related entity.
fn get(&self) -> Entity;
/// Creates this [`Relationship`] from the given `entity`.
fn from(entity: Entity) -> Self;
/// Changes the current [`Entity`] ID of the entity containing the [`RelationshipTarget`] to another one.
///
/// This is useful for updating the relationship without overwriting other fields stored in `Self`.
///
/// # Warning
///
/// This should generally not be called by user code, as modifying the related entity could invalidate the
/// relationship. If this method is used, then the hooks [`on_replace`](Relationship::on_replace) have to
/// run before and [`on_insert`](Relationship::on_insert) after it.
/// This happens automatically when this method is called with [`EntityWorldMut::modify_component`].
///
/// Prefer to use regular means of insertions when possible.
fn set_risky(&mut self, entity: Entity);
/// The `on_insert` component hook that maintains the [`Relationship`] / [`RelationshipTarget`] connection.
fn on_insert(
mut world: DeferredWorld,
HookContext {
entity,
caller,
relationship_hook_mode,
..
}: HookContext,
) {
match relationship_hook_mode {
RelationshipHookMode::Run => {}
RelationshipHookMode::Skip => return,
RelationshipHookMode::RunIfNotLinked => {
if <Self::RelationshipTarget as RelationshipTarget>::LINKED_SPAWN {
return;
}
}
}
let target_entity = world.entity(entity).get::<Self>().unwrap().get();
if target_entity == entity {
warn!(
"{}The {}({target_entity:?}) relationship on entity {entity:?} points to itself. The invalid {} relationship has been removed.",
caller.map(|location|format!("{location}: ")).unwrap_or_default(),
DebugName::type_name::<Self>(),
DebugName::type_name::<Self>()
);
world.commands().entity(entity).remove::<Self>();
return;
}
// For one-to-one relationships, remove existing relationship before adding new one
let current_source_to_remove = world
.get_entity(target_entity)
.ok()
.and_then(|target_entity_ref| target_entity_ref.get::<Self::RelationshipTarget>())
.and_then(|relationship_target| {
relationship_target
.collection()
.source_to_remove_before_add()
});
if let Some(current_source) = current_source_to_remove {
world.commands().entity(current_source).try_remove::<Self>();
}
if let Ok(mut entity_commands) = world.commands().get_entity(target_entity) {
// Deferring is necessary for batch mode
entity_commands
.entry::<Self::RelationshipTarget>()
.and_modify(move |mut relationship_target| {
relationship_target.collection_mut_risky().add(entity);
})
.or_insert_with(move || {
let mut target = Self::RelationshipTarget::with_capacity(1);
target.collection_mut_risky().add(entity);
target
});
} else {
warn!(
"{}The {}({target_entity:?}) relationship on entity {entity:?} relates to an entity that does not exist. The invalid {} relationship has been removed.",
caller.map(|location|format!("{location}: ")).unwrap_or_default(),
DebugName::type_name::<Self>(),
DebugName::type_name::<Self>()
);
world.commands().entity(entity).remove::<Self>();
}
}
/// The `on_replace` component hook that maintains the [`Relationship`] / [`RelationshipTarget`] connection.
// note: think of this as "on_drop"
fn on_replace(
mut world: DeferredWorld,
HookContext {
entity,
relationship_hook_mode,
..
}: HookContext,
) {
match relationship_hook_mode {
RelationshipHookMode::Run => {}
RelationshipHookMode::Skip => return,
RelationshipHookMode::RunIfNotLinked => {
if <Self::RelationshipTarget as RelationshipTarget>::LINKED_SPAWN {
return;
}
}
}
let target_entity = world.entity(entity).get::<Self>().unwrap().get();
if let Ok(mut target_entity_mut) = world.get_entity_mut(target_entity)
&& let Some(mut relationship_target) =
target_entity_mut.get_mut::<Self::RelationshipTarget>()
{
relationship_target.collection_mut_risky().remove(entity);
if relationship_target.len() == 0 {
let command = |mut entity: EntityWorldMut| {
// this "remove" operation must check emptiness because in the event that an identical
// relationship is inserted on top, this despawn would result in the removal of that identical
// relationship ... not what we want!
if entity
.get::<Self::RelationshipTarget>()
.is_some_and(RelationshipTarget::is_empty)
{
entity.remove::<Self::RelationshipTarget>();
}
};
world
.commands()
.queue_silenced(command.with_entity(target_entity));
}
}
}
}
/// The iterator type for the source entities in a [`RelationshipTarget`] collection,
/// as defined in the [`RelationshipSourceCollection`] trait.
pub type SourceIter<'w, R> =
<<R as RelationshipTarget>::Collection as RelationshipSourceCollection>::SourceIter<'w>;
/// A [`Component`] containing the collection of entities that relate to this [`Entity`] via the associated `Relationship` type.
/// See the [`Relationship`] documentation for more information.
pub trait RelationshipTarget: Component<Mutability = Mutable> + Sized {
/// If this is true, when despawning or cloning (when [linked cloning is enabled](crate::entity::EntityClonerBuilder::linked_cloning)), the related entities targeting this entity will also be despawned or cloned.
///
/// For example, this is set to `true` for Bevy's built-in parent-child relation, defined by [`ChildOf`](crate::prelude::ChildOf) and [`Children`](crate::prelude::Children).
/// This means that when a parent is despawned, any children targeting that parent are also despawned (and the same applies to cloning).
///
/// To get around this behavior, you can first break the relationship between entities, and *then* despawn or clone.
/// This defaults to false when derived.
const LINKED_SPAWN: bool;
/// The [`Relationship`] that populates this [`RelationshipTarget`] collection.
type Relationship: Relationship<RelationshipTarget = Self>;
/// The collection type that stores the "source" entities for this [`RelationshipTarget`] component.
///
/// Check the list of types which implement [`RelationshipSourceCollection`] for the data structures that can be used inside of your component.
/// If you need a new collection type, you can implement the [`RelationshipSourceCollection`] trait
/// for a type you own which wraps the collection you want to use (to avoid the orphan rule),
/// or open an issue on the Bevy repository to request first-party support for your collection type.
type Collection: RelationshipSourceCollection;
/// Returns a reference to the stored [`RelationshipTarget::Collection`].
fn collection(&self) -> &Self::Collection;
/// Returns a mutable reference to the stored [`RelationshipTarget::Collection`].
///
/// # Warning
/// This should generally not be called by user code, as modifying the internal collection could invalidate the relationship.
/// The collection should not contain duplicates.
fn collection_mut_risky(&mut self) -> &mut Self::Collection;
/// Creates a new [`RelationshipTarget`] from the given [`RelationshipTarget::Collection`].
///
/// # Warning
/// This should generally not be called by user code, as constructing the internal collection could invalidate the relationship.
/// The collection should not contain duplicates.
fn from_collection_risky(collection: Self::Collection) -> Self;
/// The `on_replace` component hook that maintains the [`Relationship`] / [`RelationshipTarget`] connection.
// note: think of this as "on_drop"
fn on_replace(
mut world: DeferredWorld,
HookContext {
entity,
relationship_hook_mode,
..
}: HookContext,
) {
match relationship_hook_mode {
RelationshipHookMode::Run => {}
// For RelationshipTarget we don't want to run this hook even if it isn't linked, but for Relationship we do.
RelationshipHookMode::Skip | RelationshipHookMode::RunIfNotLinked => return,
}
let (entities, mut commands) = world.entities_and_commands();
let relationship_target = entities.get(entity).unwrap().get::<Self>().unwrap();
for source_entity in relationship_target.iter() {
commands
.entity(source_entity)
.try_remove::<Self::Relationship>();
}
}
/// The `on_despawn` component hook that despawns entities stored in an entity's [`RelationshipTarget`] when
/// that entity is despawned.
// note: think of this as "on_drop"
fn on_despawn(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
let (entities, mut commands) = world.entities_and_commands();
let relationship_target = entities.get(entity).unwrap().get::<Self>().unwrap();
for source_entity in relationship_target.iter() {
commands.entity(source_entity).try_despawn();
}
}
/// Creates this [`RelationshipTarget`] with the given pre-allocated entity capacity.
fn with_capacity(capacity: usize) -> Self {
let collection =
<Self::Collection as RelationshipSourceCollection>::with_capacity(capacity);
Self::from_collection_risky(collection)
}
/// Iterates the entities stored in this collection.
#[inline]
fn iter(&self) -> SourceIter<'_, Self> {
self.collection().iter()
}
/// Returns the number of entities in this collection.
#[inline]
fn len(&self) -> usize {
self.collection().len()
}
/// Returns true if this entity collection is empty.
#[inline]
fn is_empty(&self) -> bool {
self.collection().is_empty()
}
}
/// The "clone behavior" for [`RelationshipTarget`]. The [`RelationshipTarget`] will be populated with the proper components
/// when the corresponding [`Relationship`] sources of truth are inserted. Cloning the actual entities
/// in the original [`RelationshipTarget`] would result in duplicates, so we don't do that!
///
/// This will also queue up clones of the relationship sources if the [`EntityCloner`](crate::entity::EntityCloner) is configured
/// to spawn recursively.
pub fn clone_relationship_target<T: RelationshipTarget>(
component: &T,
cloned: &mut T,
context: &mut ComponentCloneCtx,
) {
if context.linked_cloning() && T::LINKED_SPAWN {
let collection = cloned.collection_mut_risky();
for entity in component.iter() {
collection.add(entity);
context.queue_entity_clone(entity);
}
} else if context.moving() {
let target = context.target();
let collection = cloned.collection_mut_risky();
for entity in component.iter() {
collection.add(entity);
context.queue_deferred(move |world, _mapper| {
// We don't want relationships hooks to run because we are manually constructing the collection here
_ = DeferredWorld::from(world)
.modify_component_with_relationship_hook_mode::<T::Relationship, ()>(
entity,
RelationshipHookMode::Skip,
|r| r.set_risky(target),
);
});
}
}
}
/// Configures the conditions under which the Relationship insert/replace hooks will be run.
#[derive(Copy, Clone, Debug)]
pub enum RelationshipHookMode {
/// Relationship insert/replace hooks will always run
Run,
/// Relationship insert/replace hooks will run if [`RelationshipTarget::LINKED_SPAWN`] is false
RunIfNotLinked,
/// Relationship insert/replace hooks will always be skipped
Skip,
}
/// Wrapper for components clone specialization using autoderef.
#[doc(hidden)]
pub struct RelationshipCloneBehaviorSpecialization<T>(PhantomData<T>);
impl<T> Default for RelationshipCloneBehaviorSpecialization<T> {
fn default() -> Self {
Self(PhantomData)
}
}
/// Base trait for relationship clone specialization using autoderef.
#[doc(hidden)]
pub trait RelationshipCloneBehaviorBase {
fn default_clone_behavior(&self) -> ComponentCloneBehavior;
}
impl<C> RelationshipCloneBehaviorBase for RelationshipCloneBehaviorSpecialization<C> {
fn default_clone_behavior(&self) -> ComponentCloneBehavior {
// Relationships currently must have `Clone`/`Reflect`-based handler for cloning/moving logic to properly work.
ComponentCloneBehavior::Ignore
}
}
/// Specialized trait for relationship clone specialization using autoderef.
#[doc(hidden)]
pub trait RelationshipCloneBehaviorViaReflect {
fn default_clone_behavior(&self) -> ComponentCloneBehavior;
}
#[cfg(feature = "bevy_reflect")]
impl<C: Relationship + bevy_reflect::Reflect> RelationshipCloneBehaviorViaReflect
for &RelationshipCloneBehaviorSpecialization<C>
{
fn default_clone_behavior(&self) -> ComponentCloneBehavior {
ComponentCloneBehavior::reflect()
}
}
/// Specialized trait for relationship clone specialization using autoderef.
#[doc(hidden)]
pub trait RelationshipCloneBehaviorViaClone {
fn default_clone_behavior(&self) -> ComponentCloneBehavior;
}
impl<C: Relationship + Clone> RelationshipCloneBehaviorViaClone
for &&RelationshipCloneBehaviorSpecialization<C>
{
fn default_clone_behavior(&self) -> ComponentCloneBehavior {
ComponentCloneBehavior::clone::<C>()
}
}
/// Specialized trait for relationship target clone specialization using autoderef.
#[doc(hidden)]
pub trait RelationshipTargetCloneBehaviorViaReflect {
fn default_clone_behavior(&self) -> ComponentCloneBehavior;
}
#[cfg(feature = "bevy_reflect")]
impl<C: RelationshipTarget + bevy_reflect::Reflect + bevy_reflect::TypePath>
RelationshipTargetCloneBehaviorViaReflect for &&&RelationshipCloneBehaviorSpecialization<C>
{
fn default_clone_behavior(&self) -> ComponentCloneBehavior {
ComponentCloneBehavior::Custom(|source, context| {
if let Some(component) = source.read::<C>()
&& let Ok(mut cloned) = component.reflect_clone_and_take::<C>()
{
cloned.collection_mut_risky().clear();
clone_relationship_target(component, &mut cloned, context);
context.write_target_component(cloned);
}
})
}
}
/// Specialized trait for relationship target clone specialization using autoderef.
#[doc(hidden)]
pub trait RelationshipTargetCloneBehaviorViaClone {
fn default_clone_behavior(&self) -> ComponentCloneBehavior;
}
impl<C: RelationshipTarget + Clone> RelationshipTargetCloneBehaviorViaClone
for &&&&RelationshipCloneBehaviorSpecialization<C>
{
fn default_clone_behavior(&self) -> ComponentCloneBehavior {
ComponentCloneBehavior::Custom(|source, context| {
if let Some(component) = source.read::<C>() {
let mut cloned = component.clone();
cloned.collection_mut_risky().clear();
clone_relationship_target(component, &mut cloned, context);
context.write_target_component(cloned);
}
})
}
}
/// We know there's no additional data on Children, so this handler is an optimization to avoid cloning the entire Collection.
#[doc(hidden)]
pub trait RelationshipTargetCloneBehaviorHierarchy {
fn default_clone_behavior(&self) -> ComponentCloneBehavior;
}
impl RelationshipTargetCloneBehaviorHierarchy
for &&&&&RelationshipCloneBehaviorSpecialization<crate::hierarchy::Children>
{
fn default_clone_behavior(&self) -> ComponentCloneBehavior {
ComponentCloneBehavior::Custom(|source, context| {
if let Some(component) = source.read::<crate::hierarchy::Children>() {
let mut cloned = crate::hierarchy::Children::with_capacity(component.len());
clone_relationship_target(component, &mut cloned, context);
context.write_target_component(cloned);
}
})
}
}
/// This enum describes a way to access the entities of [`Relationship`] and [`RelationshipTarget`] components
/// in a type-erased context.
#[derive(Debug, Clone, Copy)]
pub enum RelationshipAccessor {
/// This component is a [`Relationship`].
Relationship {
/// Offset of the field containing [`Entity`] from the base of the component.
///
/// Dynamic equivalent of [`Relationship::get`].
entity_field_offset: usize,
/// Value of [`RelationshipTarget::LINKED_SPAWN`] for the [`Relationship::RelationshipTarget`] of this [`Relationship`].
linked_spawn: bool,
},
/// This component is a [`RelationshipTarget`].
RelationshipTarget {
/// Function that returns an iterator over all [`Entity`]s of this [`RelationshipTarget`]'s collection.
///
/// Dynamic equivalent of [`RelationshipTarget::iter`].
/// # Safety
/// Passed pointer must point to the value of the same component as the one that this accessor was registered to.
iter: for<'a> unsafe fn(Ptr<'a>) -> Box<dyn Iterator<Item = Entity> + 'a>,
/// Value of [`RelationshipTarget::LINKED_SPAWN`] of this [`RelationshipTarget`].
linked_spawn: bool,
},
}
/// A type-safe convenience wrapper over [`RelationshipAccessor`].
pub struct ComponentRelationshipAccessor<C: ?Sized> {
pub(crate) accessor: RelationshipAccessor,
phantom: PhantomData<C>,
}
impl<C> ComponentRelationshipAccessor<C> {
/// Create a new [`ComponentRelationshipAccessor`] for a [`Relationship`] component.
/// # Safety
/// `entity_field_offset` should be the offset from the base of this component and point to a field that stores value of type [`Entity`].
/// This value can be obtained using the [`core::mem::offset_of`] macro.
pub unsafe fn relationship(entity_field_offset: usize) -> Self
where
C: Relationship,
{
Self {
accessor: RelationshipAccessor::Relationship {
entity_field_offset,
linked_spawn: C::RelationshipTarget::LINKED_SPAWN,
},
phantom: Default::default(),
}
}
/// Create a new [`ComponentRelationshipAccessor`] for a [`RelationshipTarget`] component.
pub fn relationship_target() -> Self
where
C: RelationshipTarget,
{
Self {
accessor: RelationshipAccessor::RelationshipTarget {
// Safety: caller ensures that `ptr` is of type `C`.
iter: |ptr| unsafe { Box::new(RelationshipTarget::iter(ptr.deref::<C>())) },
linked_spawn: C::LINKED_SPAWN,
},
phantom: Default::default(),
}
}
}
#[cfg(test)]
mod tests {
use core::marker::PhantomData;
use crate::prelude::{ChildOf, Children};
use crate::relationship::RelationshipAccessor;
use crate::world::World;
use crate::{component::Component, entity::Entity};
use alloc::vec::Vec;
#[test]
fn custom_relationship() {
#[derive(Component)]
#[relationship(relationship_target = LikedBy)]
struct Likes(pub Entity);
#[derive(Component)]
#[relationship_target(relationship = Likes)]
struct LikedBy(Vec<Entity>);
let mut world = World::new();
let a = world.spawn_empty().id();
let b = world.spawn(Likes(a)).id();
let c = world.spawn(Likes(a)).id();
assert_eq!(world.entity(a).get::<LikedBy>().unwrap().0, &[b, c]);
}
#[test]
fn self_relationship_fails() {
#[derive(Component)]
#[relationship(relationship_target = RelTarget)]
struct Rel(Entity);
#[derive(Component)]
#[relationship_target(relationship = Rel)]
struct RelTarget(Vec<Entity>);
let mut world = World::new();
let a = world.spawn_empty().id();
world.entity_mut(a).insert(Rel(a));
assert!(!world.entity(a).contains::<Rel>());
assert!(!world.entity(a).contains::<RelTarget>());
}
#[test]
fn relationship_with_missing_target_fails() {
#[derive(Component)]
#[relationship(relationship_target = RelTarget)]
struct Rel(Entity);
#[derive(Component)]
#[relationship_target(relationship = Rel)]
struct RelTarget(Vec<Entity>);
let mut world = World::new();
let a = world.spawn_empty().id();
world.despawn(a);
let b = world.spawn(Rel(a)).id();
assert!(!world.entity(b).contains::<Rel>());
assert!(!world.entity(b).contains::<RelTarget>());
}
#[test]
fn relationship_with_multiple_non_target_fields_compiles() {
#[expect(
dead_code,
reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed."
)]
#[derive(Component)]
#[relationship(relationship_target=Target)]
struct Source {
#[relationship]
target: Entity,
foo: u8,
bar: u8,
}
#[expect(
dead_code,
reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed."
)]
#[derive(Component)]
#[relationship_target(relationship=Source)]
struct Target(Vec<Entity>);
// No assert necessary, looking to make sure compilation works with the macros
}
#[test]
fn relationship_target_with_multiple_non_target_fields_compiles() {
#[expect(
dead_code,
reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed."
)]
#[derive(Component)]
#[relationship(relationship_target=Target)]
struct Source(Entity);
#[expect(
dead_code,
reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed."
)]
#[derive(Component)]
#[relationship_target(relationship=Source)]
struct Target {
#[relationship]
target: Vec<Entity>,
foo: u8,
bar: u8,
}
// No assert necessary, looking to make sure compilation works with the macros
}
#[test]
fn relationship_with_multiple_unnamed_non_target_fields_compiles() {
#[expect(
dead_code,
reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed."
)]
#[derive(Component)]
#[relationship(relationship_target=Target<T>)]
struct Source<T: Send + Sync + 'static>(#[relationship] Entity, PhantomData<T>);
#[expect(
dead_code,
reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed."
)]
#[derive(Component)]
#[relationship_target(relationship=Source<T>)]
struct Target<T: Send + Sync + 'static>(#[relationship] Vec<Entity>, PhantomData<T>);
// No assert necessary, looking to make sure compilation works with the macros
}
#[test]
fn parent_child_relationship_with_custom_relationship() {
#[derive(Component)]
#[relationship(relationship_target = RelTarget)]
struct Rel(Entity);
#[derive(Component)]
#[relationship_target(relationship = Rel)]
struct RelTarget(Entity);
let mut world = World::new();
// Rel on Parent
// Despawn Parent
let mut commands = world.commands();
let child = commands.spawn_empty().id();
let parent = commands.spawn(Rel(child)).add_child(child).id();
commands.entity(parent).despawn();
world.flush();
assert!(world.get_entity(child).is_err());
assert!(world.get_entity(parent).is_err());
// Rel on Parent
// Despawn Child
let mut commands = world.commands();
let child = commands.spawn_empty().id();
let parent = commands.spawn(Rel(child)).add_child(child).id();
commands.entity(child).despawn();
world.flush();
assert!(world.get_entity(child).is_err());
assert!(!world.entity(parent).contains::<Rel>());
// Rel on Child
// Despawn Parent
let mut commands = world.commands();
let parent = commands.spawn_empty().id();
let child = commands.spawn((ChildOf(parent), Rel(parent))).id();
commands.entity(parent).despawn();
world.flush();
assert!(world.get_entity(child).is_err());
assert!(world.get_entity(parent).is_err());
// Rel on Child
// Despawn Child
let mut commands = world.commands();
let parent = commands.spawn_empty().id();
let child = commands.spawn((ChildOf(parent), Rel(parent))).id();
commands.entity(child).despawn();
world.flush();
assert!(world.get_entity(child).is_err());
assert!(!world.entity(parent).contains::<RelTarget>());
}
#[test]
fn spawn_batch_with_relationship() {
let mut world = World::new();
let parent = world.spawn_empty().id();
let children = world
.spawn_batch((0..10).map(|_| ChildOf(parent)))
.collect::<Vec<_>>();
for &child in &children {
assert!(world
.get::<ChildOf>(child)
.is_some_and(|child_of| child_of.parent() == parent));
}
assert!(world
.get::<Children>(parent)
.is_some_and(|children| children.len() == 10));
}
#[test]
fn insert_batch_with_relationship() {
let mut world = World::new();
let parent = world.spawn_empty().id();
let child = world.spawn_empty().id();
world.insert_batch([(child, ChildOf(parent))]);
world.flush();
assert!(world.get::<ChildOf>(child).is_some());
assert!(world.get::<Children>(parent).is_some());
}
#[test]
fn dynamically_traverse_hierarchy() {
let mut world = World::new();
let child_of_id = world.register_component::<ChildOf>();
let children_id = world.register_component::<Children>();
let parent = world.spawn_empty().id();
let child = world.spawn_empty().id();
world.entity_mut(child).insert(ChildOf(parent));
world.flush();
let children_ptr = world.get_by_id(parent, children_id).unwrap();
let RelationshipAccessor::RelationshipTarget { iter, .. } = world
.components()
.get_info(children_id)
.unwrap()
.relationship_accessor()
.unwrap()
else {
unreachable!()
};
// Safety: `children_ptr` contains value of the same type as the one this accessor was registered for.
let children: Vec<_> = unsafe { iter(children_ptr).collect() };
assert_eq!(children, alloc::vec![child]);
let child_of_ptr = world.get_by_id(child, child_of_id).unwrap();
let RelationshipAccessor::Relationship {
entity_field_offset,
..
} = world
.components()
.get_info(child_of_id)
.unwrap()
.relationship_accessor()
.unwrap()
else {
unreachable!()
};
// Safety:
// - offset is in bounds, aligned and has the same lifetime as the original pointer.
// - value at offset is guaranteed to be a valid Entity
let child_of_entity: Entity =
unsafe { *child_of_ptr.byte_add(*entity_field_offset).deref() };
| 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/relationship/relationship_source_collection.rs | crates/bevy_ecs/src/relationship/relationship_source_collection.rs | use alloc::collections::{btree_set, BTreeSet};
use core::{
hash::BuildHasher,
ops::{Deref, DerefMut},
};
use crate::entity::{Entity, EntityHashSet, EntityIndexSet};
use alloc::vec::Vec;
use indexmap::IndexSet;
use smallvec::SmallVec;
/// The internal [`Entity`] collection used by a [`RelationshipTarget`](crate::relationship::RelationshipTarget) component.
/// This is not intended to be modified directly by users, as it could invalidate the correctness of relationships.
pub trait RelationshipSourceCollection {
/// The type of iterator returned by the `iter` method.
///
/// This is an associated type (rather than using a method that returns an opaque return-position impl trait)
/// to ensure that all methods and traits (like [`DoubleEndedIterator`]) of the underlying collection's iterator
/// are available to the user when implemented without unduly restricting the possible collections.
///
/// The [`SourceIter`](super::SourceIter) type alias can be helpful to reduce confusion when working with this associated type.
type SourceIter<'a>: Iterator<Item = Entity>
where
Self: 'a;
/// Creates a new empty instance.
fn new() -> Self;
/// Returns an instance with the given pre-allocated entity `capacity`.
///
/// Some collections will ignore the provided `capacity` and return a default instance.
fn with_capacity(capacity: usize) -> Self;
/// Reserves capacity for at least `additional` more entities to be inserted.
///
/// Not all collections support this operation, in which case it is a no-op.
fn reserve(&mut self, additional: usize);
/// Adds the given `entity` to the collection.
///
/// Returns whether the entity was added to the collection.
/// Mainly useful when dealing with collections that don't allow
/// multiple instances of the same entity ([`EntityHashSet`]).
fn add(&mut self, entity: Entity) -> bool;
/// Removes the given `entity` from the collection.
///
/// Returns whether the collection actually contained
/// the entity.
fn remove(&mut self, entity: Entity) -> bool;
/// Iterates all entities in the collection.
fn iter(&self) -> Self::SourceIter<'_>;
/// Returns the current length of the collection.
fn len(&self) -> usize;
/// Clears the collection.
fn clear(&mut self);
/// Attempts to save memory by shrinking the capacity to fit the current length.
///
/// This operation is a no-op for collections that do not support it.
fn shrink_to_fit(&mut self);
/// Returns true if the collection contains no entities.
#[inline]
fn is_empty(&self) -> bool {
self.len() == 0
}
/// For one-to-one relationships, returns the entity that should be removed before adding a new one.
/// Returns `None` for one-to-many relationships or when no entity needs to be removed.
fn source_to_remove_before_add(&self) -> Option<Entity> {
None
}
/// Add multiple entities to collection at once.
///
/// May be faster than repeatedly calling [`Self::add`].
fn extend_from_iter(&mut self, entities: impl IntoIterator<Item = Entity>);
}
/// This trait signals that a [`RelationshipSourceCollection`] is ordered.
pub trait OrderedRelationshipSourceCollection: RelationshipSourceCollection {
/// Inserts the entity at a specific index.
/// If the index is too large, the entity will be added to the end of the collection.
fn insert(&mut self, index: usize, entity: Entity);
/// Removes the entity at the specified index if it exists.
fn remove_at(&mut self, index: usize) -> Option<Entity>;
/// Inserts the entity at a specific index.
/// This will never reorder other entities.
/// If the index is too large, the entity will be added to the end of the collection.
fn insert_stable(&mut self, index: usize, entity: Entity);
/// Removes the entity at the specified index if it exists.
/// This will never reorder other entities.
fn remove_at_stable(&mut self, index: usize) -> Option<Entity>;
/// Sorts the source collection.
fn sort(&mut self);
/// Inserts the entity at the proper place to maintain sorting.
fn insert_sorted(&mut self, entity: Entity);
/// This places the most recently added entity at the particular index.
fn place_most_recent(&mut self, index: usize);
/// This places the given entity at the particular index.
/// This will do nothing if the entity is not in the collection.
/// If the index is out of bounds, this will put the entity at the end.
fn place(&mut self, entity: Entity, index: usize);
/// Adds the entity at index 0.
fn push_front(&mut self, entity: Entity) {
self.insert(0, entity);
}
/// Adds the entity to the back of the collection.
fn push_back(&mut self, entity: Entity) {
self.insert(usize::MAX, entity);
}
/// Removes the first entity.
fn pop_front(&mut self) -> Option<Entity> {
self.remove_at(0)
}
/// Removes the last entity.
fn pop_back(&mut self) -> Option<Entity> {
if self.is_empty() {
None
} else {
self.remove_at(self.len() - 1)
}
}
}
impl RelationshipSourceCollection for Vec<Entity> {
type SourceIter<'a> = core::iter::Copied<core::slice::Iter<'a, Entity>>;
fn new() -> Self {
Vec::new()
}
fn reserve(&mut self, additional: usize) {
Vec::reserve(self, additional);
}
fn with_capacity(capacity: usize) -> Self {
Vec::with_capacity(capacity)
}
fn add(&mut self, entity: Entity) -> bool {
Vec::push(self, entity);
true
}
fn remove(&mut self, entity: Entity) -> bool {
if let Some(index) = <[Entity]>::iter(self).position(|e| *e == entity) {
Vec::remove(self, index);
return true;
}
false
}
fn iter(&self) -> Self::SourceIter<'_> {
<[Entity]>::iter(self).copied()
}
fn len(&self) -> usize {
Vec::len(self)
}
fn clear(&mut self) {
self.clear();
}
fn shrink_to_fit(&mut self) {
Vec::shrink_to_fit(self);
}
fn extend_from_iter(&mut self, entities: impl IntoIterator<Item = Entity>) {
self.extend(entities);
}
}
impl OrderedRelationshipSourceCollection for Vec<Entity> {
fn insert(&mut self, index: usize, entity: Entity) {
self.push(entity);
let len = self.len();
if index < len {
self.swap(index, len - 1);
}
}
fn remove_at(&mut self, index: usize) -> Option<Entity> {
(index < self.len()).then(|| self.swap_remove(index))
}
fn insert_stable(&mut self, index: usize, entity: Entity) {
if index < self.len() {
Vec::insert(self, index, entity);
} else {
self.push(entity);
}
}
fn remove_at_stable(&mut self, index: usize) -> Option<Entity> {
(index < self.len()).then(|| self.remove(index))
}
fn sort(&mut self) {
self.sort_unstable();
}
fn insert_sorted(&mut self, entity: Entity) {
let index = self.partition_point(|e| e <= &entity);
self.insert_stable(index, entity);
}
fn place_most_recent(&mut self, index: usize) {
if let Some(entity) = self.pop() {
let index = index.min(self.len());
self.insert(index, entity);
}
}
fn place(&mut self, entity: Entity, index: usize) {
if let Some(current) = <[Entity]>::iter(self).position(|e| *e == entity) {
let index = index.min(self.len());
Vec::remove(self, current);
self.insert(index, entity);
};
}
}
impl RelationshipSourceCollection for EntityHashSet {
type SourceIter<'a> = core::iter::Copied<crate::entity::hash_set::Iter<'a>>;
fn new() -> Self {
EntityHashSet::new()
}
fn reserve(&mut self, additional: usize) {
self.0.reserve(additional);
}
fn with_capacity(capacity: usize) -> Self {
EntityHashSet::with_capacity(capacity)
}
fn add(&mut self, entity: Entity) -> bool {
self.insert(entity)
}
fn remove(&mut self, entity: Entity) -> bool {
// We need to call the remove method on the underlying hash set,
// which takes its argument by reference
self.0.remove(&entity)
}
fn iter(&self) -> Self::SourceIter<'_> {
self.iter().copied()
}
fn len(&self) -> usize {
self.len()
}
fn clear(&mut self) {
self.0.clear();
}
fn shrink_to_fit(&mut self) {
self.0.shrink_to_fit();
}
fn extend_from_iter(&mut self, entities: impl IntoIterator<Item = Entity>) {
self.extend(entities);
}
}
impl<const N: usize> RelationshipSourceCollection for SmallVec<[Entity; N]> {
type SourceIter<'a> = core::iter::Copied<core::slice::Iter<'a, Entity>>;
fn new() -> Self {
SmallVec::new()
}
fn reserve(&mut self, additional: usize) {
SmallVec::reserve(self, additional);
}
fn with_capacity(capacity: usize) -> Self {
SmallVec::with_capacity(capacity)
}
fn add(&mut self, entity: Entity) -> bool {
SmallVec::push(self, entity);
true
}
fn remove(&mut self, entity: Entity) -> bool {
if let Some(index) = <[Entity]>::iter(self).position(|e| *e == entity) {
SmallVec::remove(self, index);
return true;
}
false
}
fn iter(&self) -> Self::SourceIter<'_> {
<[Entity]>::iter(self).copied()
}
fn len(&self) -> usize {
SmallVec::len(self)
}
fn clear(&mut self) {
self.clear();
}
fn shrink_to_fit(&mut self) {
SmallVec::shrink_to_fit(self);
}
fn extend_from_iter(&mut self, entities: impl IntoIterator<Item = Entity>) {
self.extend(entities);
}
}
impl RelationshipSourceCollection for Entity {
type SourceIter<'a> = core::option::IntoIter<Entity>;
fn new() -> Self {
Entity::PLACEHOLDER
}
fn reserve(&mut self, _: usize) {}
fn with_capacity(_capacity: usize) -> Self {
Self::new()
}
fn add(&mut self, entity: Entity) -> bool {
*self = entity;
true
}
fn remove(&mut self, entity: Entity) -> bool {
if *self == entity {
*self = Entity::PLACEHOLDER;
return true;
}
false
}
fn iter(&self) -> Self::SourceIter<'_> {
if *self == Entity::PLACEHOLDER {
None.into_iter()
} else {
Some(*self).into_iter()
}
}
fn len(&self) -> usize {
if *self == Entity::PLACEHOLDER {
return 0;
}
1
}
fn clear(&mut self) {
*self = Entity::PLACEHOLDER;
}
fn shrink_to_fit(&mut self) {}
fn extend_from_iter(&mut self, entities: impl IntoIterator<Item = Entity>) {
for entity in entities {
*self = entity;
}
}
fn source_to_remove_before_add(&self) -> Option<Entity> {
if *self != Entity::PLACEHOLDER {
Some(*self)
} else {
None
}
}
}
impl<const N: usize> OrderedRelationshipSourceCollection for SmallVec<[Entity; N]> {
fn insert(&mut self, index: usize, entity: Entity) {
self.push(entity);
let len = self.len();
if index < len {
self.swap(index, len - 1);
}
}
fn remove_at(&mut self, index: usize) -> Option<Entity> {
(index < self.len()).then(|| self.swap_remove(index))
}
fn insert_stable(&mut self, index: usize, entity: Entity) {
if index < self.len() {
SmallVec::<[Entity; N]>::insert(self, index, entity);
} else {
self.push(entity);
}
}
fn remove_at_stable(&mut self, index: usize) -> Option<Entity> {
(index < self.len()).then(|| self.remove(index))
}
fn sort(&mut self) {
self.sort_unstable();
}
fn insert_sorted(&mut self, entity: Entity) {
let index = self.partition_point(|e| e <= &entity);
self.insert_stable(index, entity);
}
fn place_most_recent(&mut self, index: usize) {
if let Some(entity) = self.pop() {
let index = index.min(self.len() - 1);
self.insert(index, entity);
}
}
fn place(&mut self, entity: Entity, index: usize) {
if let Some(current) = <[Entity]>::iter(self).position(|e| *e == entity) {
// The len is at least 1, so the subtraction is safe.
let index = index.min(self.len() - 1);
SmallVec::<[Entity; N]>::remove(self, current);
self.insert(index, entity);
};
}
}
impl<S: BuildHasher + Default> RelationshipSourceCollection for IndexSet<Entity, S> {
type SourceIter<'a>
= core::iter::Copied<indexmap::set::Iter<'a, Entity>>
where
S: 'a;
fn new() -> Self {
IndexSet::default()
}
fn reserve(&mut self, additional: usize) {
self.reserve(additional);
}
fn with_capacity(capacity: usize) -> Self {
IndexSet::with_capacity_and_hasher(capacity, S::default())
}
fn add(&mut self, entity: Entity) -> bool {
self.insert(entity)
}
fn remove(&mut self, entity: Entity) -> bool {
self.shift_remove(&entity)
}
fn iter(&self) -> Self::SourceIter<'_> {
self.iter().copied()
}
fn len(&self) -> usize {
self.len()
}
fn clear(&mut self) {
self.clear();
}
fn shrink_to_fit(&mut self) {
self.shrink_to_fit();
}
fn extend_from_iter(&mut self, entities: impl IntoIterator<Item = Entity>) {
self.extend(entities);
}
}
impl RelationshipSourceCollection for EntityIndexSet {
type SourceIter<'a> = core::iter::Copied<crate::entity::index_set::Iter<'a>>;
fn new() -> Self {
EntityIndexSet::new()
}
fn reserve(&mut self, additional: usize) {
self.deref_mut().reserve(additional);
}
fn with_capacity(capacity: usize) -> Self {
EntityIndexSet::with_capacity(capacity)
}
fn add(&mut self, entity: Entity) -> bool {
self.insert(entity)
}
fn remove(&mut self, entity: Entity) -> bool {
self.deref_mut().shift_remove(&entity)
}
fn iter(&self) -> Self::SourceIter<'_> {
self.iter().copied()
}
fn len(&self) -> usize {
self.deref().len()
}
fn clear(&mut self) {
self.deref_mut().clear();
}
fn shrink_to_fit(&mut self) {
self.deref_mut().shrink_to_fit();
}
fn extend_from_iter(&mut self, entities: impl IntoIterator<Item = Entity>) {
self.extend(entities);
}
}
impl RelationshipSourceCollection for BTreeSet<Entity> {
type SourceIter<'a> = core::iter::Copied<btree_set::Iter<'a, Entity>>;
fn new() -> Self {
BTreeSet::new()
}
fn with_capacity(_: usize) -> Self {
// BTreeSet doesn't have a capacity
Self::new()
}
fn reserve(&mut self, _: usize) {
// BTreeSet doesn't have a capacity
}
fn add(&mut self, entity: Entity) -> bool {
self.insert(entity)
}
fn remove(&mut self, entity: Entity) -> bool {
self.remove(&entity)
}
fn iter(&self) -> Self::SourceIter<'_> {
self.iter().copied()
}
fn len(&self) -> usize {
self.len()
}
fn clear(&mut self) {
self.clear();
}
fn shrink_to_fit(&mut self) {
// BTreeSet doesn't have a capacity
}
fn extend_from_iter(&mut self, entities: impl IntoIterator<Item = Entity>) {
self.extend(entities);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::prelude::{Component, World};
use crate::relationship::RelationshipTarget;
#[test]
fn vec_relationship_source_collection() {
#[derive(Component)]
#[relationship(relationship_target = RelTarget)]
struct Rel(Entity);
#[derive(Component)]
#[relationship_target(relationship = Rel, linked_spawn)]
struct RelTarget(Vec<Entity>);
let mut world = World::new();
let a = world.spawn_empty().id();
let b = world.spawn_empty().id();
world.entity_mut(a).insert(Rel(b));
let rel_target = world.get::<RelTarget>(b).unwrap();
let collection = rel_target.collection();
assert_eq!(collection, &alloc::vec!(a));
}
#[test]
fn smallvec_relationship_source_collection() {
#[derive(Component)]
#[relationship(relationship_target = RelTarget)]
struct Rel(Entity);
#[derive(Component)]
#[relationship_target(relationship = Rel, linked_spawn)]
struct RelTarget(SmallVec<[Entity; 4]>);
let mut world = World::new();
let a = world.spawn_empty().id();
let b = world.spawn_empty().id();
world.entity_mut(a).insert(Rel(b));
let rel_target = world.get::<RelTarget>(b).unwrap();
let collection = rel_target.collection();
assert_eq!(collection, &SmallVec::from_buf([a]));
}
#[test]
fn entity_relationship_source_collection() {
#[derive(Component)]
#[relationship(relationship_target = RelTarget)]
struct Rel(Entity);
#[derive(Component)]
#[relationship_target(relationship = Rel)]
struct RelTarget(Entity);
let mut world = World::new();
let a = world.spawn_empty().id();
let b = world.spawn_empty().id();
world.entity_mut(a).insert(Rel(b));
let rel_target = world.get::<RelTarget>(b).unwrap();
let collection = rel_target.collection();
assert_eq!(collection, &a);
}
#[test]
fn one_to_one_relationships() {
#[derive(Component)]
#[relationship(relationship_target = Below)]
struct Above(Entity);
#[derive(Component)]
#[relationship_target(relationship = Above)]
struct Below(Entity);
let mut world = World::new();
let a = world.spawn_empty().id();
let b = world.spawn_empty().id();
world.entity_mut(a).insert(Above(b));
assert_eq!(a, world.get::<Below>(b).unwrap().0);
// Verify removing target removes relationship
world.entity_mut(b).remove::<Below>();
assert!(world.get::<Above>(a).is_none());
// Verify removing relationship removes target
world.entity_mut(a).insert(Above(b));
world.entity_mut(a).remove::<Above>();
assert!(world.get::<Below>(b).is_none());
// Actually - a is above c now! Verify relationship was updated correctly
let c = world.spawn_empty().id();
world.entity_mut(a).insert(Above(c));
assert!(world.get::<Below>(b).is_none());
assert_eq!(a, world.get::<Below>(c).unwrap().0);
}
#[test]
fn entity_index_map() {
for add_before in [false, true] {
#[derive(Component)]
#[relationship(relationship_target = RelTarget)]
struct Rel(Entity);
#[derive(Component)]
#[relationship_target(relationship = Rel, linked_spawn)]
struct RelTarget(Vec<Entity>);
let mut world = World::new();
if add_before {
let _ = world.spawn_empty().id();
}
let a = world.spawn_empty().id();
let b = world.spawn_empty().id();
let c = world.spawn_empty().id();
let d = world.spawn_empty().id();
world.entity_mut(a).add_related::<Rel>(&[b, c, d]);
let rel_target = world.get::<RelTarget>(a).unwrap();
let collection = rel_target.collection();
// Insertions should maintain ordering
assert!(collection.iter().eq([b, c, d]));
world.entity_mut(c).despawn();
let rel_target = world.get::<RelTarget>(a).unwrap();
let collection = rel_target.collection();
// Removals should maintain ordering
assert!(collection.iter().eq([b, d]));
}
}
#[test]
fn one_to_one_relationship_shared_target() {
#[derive(Component)]
#[relationship(relationship_target = Below)]
struct Above(Entity);
#[derive(Component)]
#[relationship_target(relationship = Above)]
struct Below(Entity);
let mut world = World::new();
let a = world.spawn_empty().id();
let b = world.spawn_empty().id();
let c = world.spawn_empty().id();
world.entity_mut(a).insert(Above(c));
world.entity_mut(b).insert(Above(c));
// The original relationship (a -> c) should be removed and the new relationship (b -> c) should be established
assert!(
world.get::<Above>(a).is_none(),
"Original relationship should be removed"
);
assert_eq!(
world.get::<Above>(b).unwrap().0,
c,
"New relationship should be established"
);
assert_eq!(
world.get::<Below>(c).unwrap().0,
b,
"Target should point to new source"
);
}
#[test]
fn one_to_one_relationship_reinsert() {
#[derive(Component)]
#[relationship(relationship_target = Below)]
struct Above(Entity);
#[derive(Component)]
#[relationship_target(relationship = Above)]
struct Below(Entity);
let mut world = World::new();
let a = world.spawn_empty().id();
let b = world.spawn_empty().id();
world.entity_mut(a).insert(Above(b));
world.entity_mut(a).insert(Above(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/world/command_queue.rs | crates/bevy_ecs/src/world/command_queue.rs | use crate::{
change_detection::MaybeLocation,
system::{Command, SystemBuffer, SystemMeta},
world::{DeferredWorld, World},
};
use alloc::{boxed::Box, vec::Vec};
use bevy_ptr::{OwningPtr, Unaligned};
use core::{
fmt::Debug,
mem::{size_of, MaybeUninit},
panic::AssertUnwindSafe,
ptr::{addr_of_mut, NonNull},
};
use log::warn;
struct CommandMeta {
/// SAFETY: The `value` must point to a value of type `T: Command`,
/// where `T` is some specific type that was used to produce this metadata.
///
/// `world` is optional to allow this one function pointer to perform double-duty as a drop.
///
/// Advances `cursor` by the size of `T` in bytes.
consume_command_and_get_size:
unsafe fn(value: OwningPtr<Unaligned>, world: Option<NonNull<World>>, cursor: &mut usize),
}
/// Densely and efficiently stores a queue of heterogenous types implementing [`Command`].
// NOTE: [`CommandQueue`] is implemented via a `Vec<MaybeUninit<u8>>` instead of a `Vec<Box<dyn Command>>`
// as an optimization. Since commands are used frequently in systems as a way to spawn
// entities/components/resources, and it's not currently possible to parallelize these
// due to mutable [`World`] access, maximizing performance for [`CommandQueue`] is
// preferred to simplicity of implementation.
pub struct CommandQueue {
// This buffer densely stores all queued commands.
//
// For each command, one `CommandMeta` is stored, followed by zero or more bytes
// to store the command itself. To interpret these bytes, a pointer must
// be passed to the corresponding `CommandMeta.apply_command_and_get_size` fn pointer.
pub(crate) bytes: Vec<MaybeUninit<u8>>,
pub(crate) cursor: usize,
pub(crate) panic_recovery: Vec<MaybeUninit<u8>>,
pub(crate) caller: MaybeLocation,
}
impl Default for CommandQueue {
#[track_caller]
fn default() -> Self {
Self {
bytes: Default::default(),
cursor: Default::default(),
panic_recovery: Default::default(),
caller: MaybeLocation::caller(),
}
}
}
/// Wraps pointers to a [`CommandQueue`], used internally to avoid stacked borrow rules when
/// partially applying the world's command queue recursively
#[derive(Clone)]
pub(crate) struct RawCommandQueue {
pub(crate) bytes: NonNull<Vec<MaybeUninit<u8>>>,
pub(crate) cursor: NonNull<usize>,
pub(crate) panic_recovery: NonNull<Vec<MaybeUninit<u8>>>,
}
// CommandQueue needs to implement Debug manually, rather than deriving it, because the derived impl just prints
// [core::mem::maybe_uninit::MaybeUninit<u8>, core::mem::maybe_uninit::MaybeUninit<u8>, ..] for every byte in the vec,
// which gets extremely verbose very quickly, while also providing no useful information.
// It is not possible to soundly print the values of the contained bytes, as some of them may be padding or uninitialized (#4863)
// So instead, the manual impl just prints the length of vec.
impl Debug for CommandQueue {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("CommandQueue")
.field("len_bytes", &self.bytes.len())
.field("caller", &self.caller)
.finish_non_exhaustive()
}
}
// SAFETY: All commands [`Command`] implement [`Send`]
unsafe impl Send for CommandQueue {}
// SAFETY: `&CommandQueue` never gives access to the inner commands.
unsafe impl Sync for CommandQueue {}
impl CommandQueue {
/// Push a [`Command`] onto the queue.
#[inline]
pub fn push(&mut self, command: impl Command) {
// SAFETY: self is guaranteed to live for the lifetime of this method
unsafe {
self.get_raw().push(command);
}
}
/// Execute the queued [`Command`]s in the world after applying any commands in the world's internal queue.
/// This clears the queue.
#[inline]
pub fn apply(&mut self, world: &mut World) {
// flush the world's internal queue
world.flush_commands();
// SAFETY: A reference is always a valid pointer
unsafe {
self.get_raw().apply_or_drop_queued(Some(world.into()));
}
}
/// Take all commands from `other` and append them to `self`, leaving `other` empty
pub fn append(&mut self, other: &mut CommandQueue) {
self.bytes.append(&mut other.bytes);
}
/// Returns false if there are any commands in the queue
#[inline]
pub fn is_empty(&self) -> bool {
self.cursor >= self.bytes.len()
}
/// Returns a [`RawCommandQueue`] instance sharing the underlying command queue.
pub(crate) fn get_raw(&mut self) -> RawCommandQueue {
// SAFETY: self is always valid memory
unsafe {
RawCommandQueue {
bytes: NonNull::new_unchecked(addr_of_mut!(self.bytes)),
cursor: NonNull::new_unchecked(addr_of_mut!(self.cursor)),
panic_recovery: NonNull::new_unchecked(addr_of_mut!(self.panic_recovery)),
}
}
}
}
impl RawCommandQueue {
/// Returns a new `RawCommandQueue` instance, this must be manually dropped.
pub(crate) fn new() -> Self {
// SAFETY: Pointers returned by `Box::into_raw` are guaranteed to be non null
unsafe {
Self {
bytes: NonNull::new_unchecked(Box::into_raw(Box::default())),
cursor: NonNull::new_unchecked(Box::into_raw(Box::new(0usize))),
panic_recovery: NonNull::new_unchecked(Box::into_raw(Box::default())),
}
}
}
/// Returns true if the queue is empty.
///
/// # Safety
///
/// * Caller ensures that `bytes` and `cursor` point to valid memory
pub unsafe fn is_empty(&self) -> bool {
// SAFETY: Pointers are guaranteed to be valid by requirements on `.clone_unsafe`
(unsafe { *self.cursor.as_ref() }) >= (unsafe { self.bytes.as_ref() }).len()
}
/// Push a [`Command`] onto the queue.
///
/// # Safety
///
/// * Caller ensures that `self` has not outlived the underlying queue
#[inline]
pub unsafe fn push<C: Command>(&mut self, command: C) {
// Stores a command alongside its metadata.
// `repr(C)` prevents the compiler from reordering the fields,
// while `repr(packed)` prevents the compiler from inserting padding bytes.
#[repr(C, packed)]
struct Packed<C: Command> {
meta: CommandMeta,
command: C,
}
let meta = CommandMeta {
consume_command_and_get_size: |command, world, cursor| {
*cursor += size_of::<C>();
// SAFETY: According to the invariants of `CommandMeta.consume_command_and_get_size`,
// `command` must point to a value of type `C`.
let command: C = unsafe { command.read_unaligned() };
match world {
// Apply command to the provided world...
Some(mut world) => {
// SAFETY: Caller ensures pointer is not null
let world = unsafe { world.as_mut() };
command.apply(world);
// The command may have queued up world commands, which we flush here to ensure they are also picked up.
// If the current command queue already the World Command queue, this will still behave appropriately because the global cursor
// is still at the current `stop`, ensuring only the newly queued Commands will be applied.
world.flush();
}
// ...or discard it.
None => drop(command),
}
},
};
// SAFETY: There are no outstanding references to self.bytes
let bytes = unsafe { self.bytes.as_mut() };
let old_len = bytes.len();
// Reserve enough bytes for both the metadata and the command itself.
bytes.reserve(size_of::<Packed<C>>());
// Pointer to the bytes at the end of the buffer.
// SAFETY: We know it is within bounds of the allocation, due to the call to `.reserve()`.
let ptr = unsafe { bytes.as_mut_ptr().add(old_len) };
// Write the metadata into the buffer, followed by the command.
// We are using a packed struct to write them both as one operation.
// SAFETY: `ptr` must be non-null, since it is within a non-null buffer.
// The call to `reserve()` ensures that the buffer has enough space to fit a value of type `C`,
// and it is valid to write any bit pattern since the underlying buffer is of type `MaybeUninit<u8>`.
unsafe {
ptr.cast::<Packed<C>>()
.write_unaligned(Packed { meta, command });
}
// Extend the length of the buffer to include the data we just wrote.
// SAFETY: The new length is guaranteed to fit in the vector's capacity,
// due to the call to `.reserve()` above.
unsafe {
bytes.set_len(old_len + size_of::<Packed<C>>());
}
}
/// If `world` is [`Some`], this will apply the queued [commands](`Command`).
/// If `world` is [`None`], this will drop the queued [commands](`Command`) (without applying them).
/// This clears the queue.
///
/// # Safety
///
/// * Caller ensures that `self` has not outlived the underlying queue
#[inline]
pub(crate) unsafe fn apply_or_drop_queued(&mut self, world: Option<NonNull<World>>) {
// SAFETY: If this is the command queue on world, world will not be dropped as we have a mutable reference
// If this is not the command queue on world we have exclusive ownership and self will not be mutated
let start = *self.cursor.as_ref();
let stop = self.bytes.as_ref().len();
let mut local_cursor = start;
// SAFETY: we are setting the global cursor to the current length to prevent the executing commands from applying
// the remaining commands currently in this list. This is safe.
*self.cursor.as_mut() = stop;
while local_cursor < stop {
// SAFETY: The cursor is either at the start of the buffer, or just after the previous command.
// Since we know that the cursor is in bounds, it must point to the start of a new command.
let meta = unsafe {
self.bytes
.as_mut()
.as_mut_ptr()
.add(local_cursor)
.cast::<CommandMeta>()
.read_unaligned()
};
// Advance to the bytes just after `meta`, which represent a type-erased command.
local_cursor += size_of::<CommandMeta>();
// Construct an owned pointer to the command.
// SAFETY: It is safe to transfer ownership out of `self.bytes`, since the increment of `cursor` above
// guarantees that nothing stored in the buffer will get observed after this function ends.
// `cmd` points to a valid address of a stored command, so it must be non-null.
let cmd = unsafe {
OwningPtr::<Unaligned>::new(NonNull::new_unchecked(
self.bytes.as_mut().as_mut_ptr().add(local_cursor).cast(),
))
};
let f = AssertUnwindSafe(|| {
// SAFETY: The data underneath the cursor must correspond to the type erased in metadata,
// since they were stored next to each other by `.push()`.
// For ZSTs, the type doesn't matter as long as the pointer is non-null.
// This also advances the cursor past the command. For ZSTs, the cursor will not move.
// At this point, it will either point to the next `CommandMeta`,
// or the cursor will be out of bounds and the loop will end.
unsafe { (meta.consume_command_and_get_size)(cmd, world, &mut local_cursor) };
});
#[cfg(feature = "std")]
{
let result = std::panic::catch_unwind(f);
if let Err(payload) = result {
// local_cursor now points to the location _after_ the panicked command.
// Add the remaining commands that _would have_ been applied to the
// panic_recovery queue.
//
// This uses `current_stop` instead of `stop` to account for any commands
// that were queued _during_ this panic.
//
// This is implemented in such a way that if apply_or_drop_queued() are nested recursively in,
// an applied Command, the correct command order will be retained.
let panic_recovery = self.panic_recovery.as_mut();
let bytes = self.bytes.as_mut();
let current_stop = bytes.len();
panic_recovery.extend_from_slice(&bytes[local_cursor..current_stop]);
bytes.set_len(start);
*self.cursor.as_mut() = start;
// This was the "top of the apply stack". If we are _not_ at the top of the apply stack,
// when we call`resume_unwind" the caller "closer to the top" will catch the unwind and do this check,
// until we reach the top.
if start == 0 {
bytes.append(panic_recovery);
}
std::panic::resume_unwind(payload);
}
}
#[cfg(not(feature = "std"))]
(f)();
}
// Reset the buffer: all commands past the original `start` cursor have been applied.
// SAFETY: we are setting the length of bytes to the original length, minus the length of the original
// list of commands being considered. All bytes remaining in the Vec are still valid, unapplied commands.
unsafe {
self.bytes.as_mut().set_len(start);
*self.cursor.as_mut() = start;
};
}
}
impl Drop for CommandQueue {
fn drop(&mut self) {
if !self.bytes.is_empty() {
if let Some(caller) = self.caller.into_option() {
warn!("CommandQueue has un-applied commands being dropped. Did you forget to call SystemState::apply? caller:{caller:?}");
} else {
warn!("CommandQueue has un-applied commands being dropped. Did you forget to call SystemState::apply?");
}
}
// SAFETY: A reference is always a valid pointer
unsafe { self.get_raw().apply_or_drop_queued(None) };
}
}
impl SystemBuffer for CommandQueue {
#[inline]
fn apply(&mut self, _system_meta: &SystemMeta, world: &mut World) {
#[cfg(feature = "trace")]
let _span_guard = _system_meta.commands_span.enter();
self.apply(world);
}
#[inline]
fn queue(&mut self, _system_meta: &SystemMeta, mut world: DeferredWorld) {
world.commands().append(self);
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::{component::Component, resource::Resource};
use alloc::{borrow::ToOwned, string::String, sync::Arc};
use core::{
panic::AssertUnwindSafe,
sync::atomic::{AtomicU32, Ordering},
};
#[cfg(miri)]
use alloc::format;
struct DropCheck(Arc<AtomicU32>);
impl DropCheck {
fn new() -> (Self, Arc<AtomicU32>) {
let drops = Arc::new(AtomicU32::new(0));
(Self(drops.clone()), drops)
}
}
impl Drop for DropCheck {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::Relaxed);
}
}
impl Command for DropCheck {
fn apply(self, _: &mut World) {}
}
#[test]
fn test_command_queue_inner_drop() {
let mut queue = CommandQueue::default();
let (dropcheck_a, drops_a) = DropCheck::new();
let (dropcheck_b, drops_b) = DropCheck::new();
queue.push(dropcheck_a);
queue.push(dropcheck_b);
assert_eq!(drops_a.load(Ordering::Relaxed), 0);
assert_eq!(drops_b.load(Ordering::Relaxed), 0);
let mut world = World::new();
queue.apply(&mut world);
assert_eq!(drops_a.load(Ordering::Relaxed), 1);
assert_eq!(drops_b.load(Ordering::Relaxed), 1);
}
/// Asserts that inner [commands](`Command`) are dropped on early drop of [`CommandQueue`].
/// Originally identified as an issue in [#10676](https://github.com/bevyengine/bevy/issues/10676)
#[test]
fn test_command_queue_inner_drop_early() {
let mut queue = CommandQueue::default();
let (dropcheck_a, drops_a) = DropCheck::new();
let (dropcheck_b, drops_b) = DropCheck::new();
queue.push(dropcheck_a);
queue.push(dropcheck_b);
assert_eq!(drops_a.load(Ordering::Relaxed), 0);
assert_eq!(drops_b.load(Ordering::Relaxed), 0);
drop(queue);
assert_eq!(drops_a.load(Ordering::Relaxed), 1);
assert_eq!(drops_b.load(Ordering::Relaxed), 1);
}
#[derive(Component)]
struct A;
struct SpawnCommand;
impl Command for SpawnCommand {
fn apply(self, world: &mut World) {
world.spawn(A);
}
}
#[test]
fn test_command_queue_inner() {
let mut queue = CommandQueue::default();
queue.push(SpawnCommand);
queue.push(SpawnCommand);
let mut world = World::new();
queue.apply(&mut world);
assert_eq!(world.query::<&A>().query(&world).count(), 2);
// The previous call to `apply` cleared the queue.
// This call should do nothing.
queue.apply(&mut world);
assert_eq!(world.query::<&A>().query(&world).count(), 2);
}
#[expect(
dead_code,
reason = "The inner string is used to ensure that, when the PanicCommand gets pushed to the queue, some data is written to the `bytes` vector."
)]
struct PanicCommand(String);
impl Command for PanicCommand {
fn apply(self, _: &mut World) {
panic!("command is panicking");
}
}
#[test]
fn test_command_queue_inner_panic_safe() {
std::panic::set_hook(Box::new(|_| {}));
let mut queue = CommandQueue::default();
queue.push(PanicCommand("I panic!".to_owned()));
queue.push(SpawnCommand);
let mut world = World::new();
let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
queue.apply(&mut world);
}));
// Even though the first command panicked, it's still ok to push
// more commands.
queue.push(SpawnCommand);
queue.push(SpawnCommand);
queue.apply(&mut world);
assert_eq!(world.query::<&A>().query(&world).count(), 3);
}
#[test]
fn test_command_queue_inner_nested_panic_safe() {
std::panic::set_hook(Box::new(|_| {}));
#[derive(Resource, Default)]
struct Order(Vec<usize>);
let mut world = World::new();
world.init_resource::<Order>();
fn add_index(index: usize) -> impl Command {
move |world: &mut World| world.resource_mut::<Order>().0.push(index)
}
world.commands().queue(add_index(1));
world.commands().queue(|world: &mut World| {
world.commands().queue(add_index(2));
world.commands().queue(PanicCommand("I panic!".to_owned()));
world.commands().queue(add_index(3));
world.flush_commands();
});
world.commands().queue(add_index(4));
let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
world.flush_commands();
}));
world.commands().queue(add_index(5));
world.flush_commands();
assert_eq!(&world.resource::<Order>().0, &[1, 2, 3, 4, 5]);
}
// NOTE: `CommandQueue` is `Send` because `Command` is send.
// If the `Command` trait gets reworked to be non-send, `CommandQueue`
// should be reworked.
// This test asserts that Command types are send.
fn assert_is_send_impl(_: impl Send) {}
fn assert_is_send(command: impl Command) {
assert_is_send_impl(command);
}
#[test]
fn test_command_is_send() {
assert_is_send(SpawnCommand);
}
#[expect(
dead_code,
reason = "This struct is used to test how the CommandQueue reacts to padding added by rust's compiler."
)]
struct CommandWithPadding(u8, u16);
impl Command for CommandWithPadding {
fn apply(self, _: &mut World) {}
}
#[cfg(miri)]
#[test]
fn test_uninit_bytes() {
let mut queue = CommandQueue::default();
queue.push(CommandWithPadding(0, 0));
let _ = format!("{:?}", queue.bytes);
}
}
| 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/world/reflect.rs | crates/bevy_ecs/src/world/reflect.rs | //! Provides additional functionality for [`World`] when the `bevy_reflect` feature is enabled.
use core::any::TypeId;
use thiserror::Error;
use bevy_reflect::{Reflect, ReflectFromPtr};
use bevy_utils::prelude::DebugName;
use crate::{prelude::*, world::ComponentId};
impl World {
/// Retrieves a reference to the given `entity`'s [`Component`] of the given `type_id` using
/// reflection.
///
/// Requires implementing [`Reflect`] for the [`Component`] (e.g., using [`#[derive(Reflect)`](derive@bevy_reflect::Reflect))
/// and `app.register_type::<TheComponent>()` to have been called[^note-reflect-impl].
///
/// If you want to call this with a [`ComponentId`], see [`World::components`] and [`Components::get_id`] to get
/// the corresponding [`TypeId`].
///
/// Also see the crate documentation for [`bevy_reflect`] for more information on
/// [`Reflect`] and bevy's reflection capabilities.
///
/// # Errors
///
/// See [`GetComponentReflectError`] for the possible errors and their descriptions.
///
/// # Example
///
/// ```
/// use bevy_ecs::prelude::*;
/// use bevy_reflect::Reflect;
/// use std::any::TypeId;
///
/// // define a `Component` and derive `Reflect` for it
/// #[derive(Component, Reflect)]
/// struct MyComponent;
///
/// // create a `World` for this example
/// let mut world = World::new();
///
/// // Note: This is usually handled by `App::register_type()`, but this example cannot use `App`.
/// world.init_resource::<AppTypeRegistry>();
/// world.get_resource_mut::<AppTypeRegistry>().unwrap().write().register::<MyComponent>();
///
/// // spawn an entity with a `MyComponent`
/// let entity = world.spawn(MyComponent).id();
///
/// // retrieve a reflected reference to the entity's `MyComponent`
/// let comp_reflected: &dyn Reflect = world.get_reflect(entity, TypeId::of::<MyComponent>()).unwrap();
///
/// // make sure we got the expected type
/// assert!(comp_reflected.is::<MyComponent>());
/// ```
///
/// # Note
/// Requires the `bevy_reflect` feature (included in the default features).
///
/// [`Components::get_id`]: crate::component::Components::get_id
/// [`ReflectFromPtr`]: bevy_reflect::ReflectFromPtr
/// [`TypeData`]: bevy_reflect::TypeData
/// [`Reflect`]: bevy_reflect::Reflect
/// [`App::register_type`]: ../../bevy_app/struct.App.html#method.register_type
/// [^note-reflect-impl]: More specifically: Requires [`TypeData`] for [`ReflectFromPtr`] to be registered for the given `type_id`,
/// which is automatically handled when deriving [`Reflect`] and calling [`App::register_type`].
#[inline]
pub fn get_reflect(
&self,
entity: Entity,
type_id: TypeId,
) -> Result<&dyn Reflect, GetComponentReflectError> {
let Some(component_id) = self.components().get_valid_id(type_id) else {
return Err(GetComponentReflectError::NoCorrespondingComponentId(
type_id,
));
};
let Some(comp_ptr) = self.get_by_id(entity, component_id) else {
let component_name = self.components().get_name(component_id);
return Err(GetComponentReflectError::EntityDoesNotHaveComponent {
entity,
type_id,
component_id,
component_name,
});
};
let Some(type_registry) = self.get_resource::<AppTypeRegistry>().map(|atr| atr.read())
else {
return Err(GetComponentReflectError::MissingAppTypeRegistry);
};
let Some(reflect_from_ptr) = type_registry.get_type_data::<ReflectFromPtr>(type_id) else {
return Err(GetComponentReflectError::MissingReflectFromPtrTypeData(
type_id,
));
};
// SAFETY:
// - `comp_ptr` is guaranteed to point to an object of type `type_id`
// - `reflect_from_ptr` was constructed for type `type_id`
// - Assertion that checks this equality is present
unsafe {
assert_eq!(
reflect_from_ptr.type_id(),
type_id,
"Mismatch between Ptr's type_id and ReflectFromPtr's type_id",
);
Ok(reflect_from_ptr.as_reflect(comp_ptr))
}
}
/// Retrieves a mutable reference to the given `entity`'s [`Component`] of the given `type_id` using
/// reflection.
///
/// Requires implementing [`Reflect`] for the [`Component`] (e.g., using [`#[derive(Reflect)`](derive@bevy_reflect::Reflect))
/// and `app.register_type::<TheComponent>()` to have been called.
///
/// This is the mutable version of [`World::get_reflect`], see its docs for more information
/// and an example.
///
/// Just calling this method does not trigger [change detection](crate::change_detection).
///
/// # Errors
///
/// See [`GetComponentReflectError`] for the possible errors and their descriptions.
///
/// # Example
///
/// See the documentation for [`World::get_reflect`].
///
/// # Note
/// Requires the feature `bevy_reflect` (included in the default features).
///
/// [`Reflect`]: bevy_reflect::Reflect
#[inline]
pub fn get_reflect_mut(
&mut self,
entity: Entity,
type_id: TypeId,
) -> Result<Mut<'_, dyn Reflect>, GetComponentReflectError> {
// little clone() + read() dance so we a) don't keep a borrow of `self` and b) don't drop a
// temporary (from read()) too early.
let Some(app_type_registry) = self.get_resource::<AppTypeRegistry>().cloned() else {
return Err(GetComponentReflectError::MissingAppTypeRegistry);
};
let type_registry = app_type_registry.read();
let Some(reflect_from_ptr) = type_registry.get_type_data::<ReflectFromPtr>(type_id) else {
return Err(GetComponentReflectError::MissingReflectFromPtrTypeData(
type_id,
));
};
let Some(component_id) = self.components().get_valid_id(type_id) else {
return Err(GetComponentReflectError::NoCorrespondingComponentId(
type_id,
));
};
// HACK: Only required for the `None`-case/`else`-branch, but it borrows `self`, which will
// already be mutably borrowed by `self.get_mut_by_id()`, and I didn't find a way around it.
let component_name = self.components().get_name(component_id).clone();
let Some(comp_mut_untyped) = self.get_mut_by_id(entity, component_id) else {
return Err(GetComponentReflectError::EntityDoesNotHaveComponent {
entity,
type_id,
component_id,
component_name,
});
};
// SAFETY:
// - `comp_mut_untyped` is guaranteed to point to an object of type `type_id`
// - `reflect_from_ptr` was constructed for type `type_id`
// - Assertion that checks this equality is present
let comp_mut_typed = comp_mut_untyped.map_unchanged(|ptr_mut| unsafe {
assert_eq!(
reflect_from_ptr.type_id(),
type_id,
"Mismatch between PtrMut's type_id and ReflectFromPtr's type_id",
);
reflect_from_ptr.as_reflect_mut(ptr_mut)
});
Ok(comp_mut_typed)
}
}
/// The error type returned by [`World::get_reflect`] and [`World::get_reflect_mut`].
#[derive(Error, Debug)]
pub enum GetComponentReflectError {
/// There is no [`ComponentId`] corresponding to the given [`TypeId`].
///
/// This is usually handled by calling [`App::register_type`] for the type corresponding to
/// the given [`TypeId`].
///
/// See the documentation for [`bevy_reflect`] for more information.
///
/// [`App::register_type`]: ../../../bevy_app/struct.App.html#method.register_type
#[error("No `ComponentId` corresponding to {0:?} found (did you call App::register_type()?)")]
NoCorrespondingComponentId(TypeId),
/// The given [`Entity`] does not have a [`Component`] corresponding to the given [`TypeId`].
#[error("The given `Entity` {entity} does not have a `{component_name:?}` component ({component_id:?}, which corresponds to {type_id:?})")]
EntityDoesNotHaveComponent {
/// The given [`Entity`].
entity: Entity,
/// The given [`TypeId`].
type_id: TypeId,
/// The [`ComponentId`] corresponding to the given [`TypeId`].
component_id: ComponentId,
/// The name corresponding to the [`Component`] with the given [`TypeId`], or `None`
/// if not available.
component_name: Option<DebugName>,
},
/// The [`World`] was missing the [`AppTypeRegistry`] resource.
#[error("The `World` was missing the `AppTypeRegistry` resource")]
MissingAppTypeRegistry,
/// The [`World`]'s [`TypeRegistry`] did not contain [`TypeData`] for [`ReflectFromPtr`] for the given [`TypeId`].
///
/// This is usually handled by calling [`App::register_type`] for the type corresponding to
/// the given [`TypeId`].
///
/// See the documentation for [`bevy_reflect`] for more information.
///
/// [`TypeData`]: bevy_reflect::TypeData
/// [`TypeRegistry`]: bevy_reflect::TypeRegistry
/// [`ReflectFromPtr`]: bevy_reflect::ReflectFromPtr
/// [`App::register_type`]: ../../../bevy_app/struct.App.html#method.register_type
#[error("The `World`'s `TypeRegistry` did not contain `TypeData` for `ReflectFromPtr` for the given {0:?} (did you call `App::register_type()`?)")]
MissingReflectFromPtrTypeData(TypeId),
}
#[cfg(test)]
mod tests {
use core::any::TypeId;
use bevy_reflect::Reflect;
use crate::prelude::{AppTypeRegistry, Component, DetectChanges, World};
#[derive(Component, Reflect)]
struct RFoo(i32);
#[derive(Component)]
struct Bar;
#[test]
fn get_component_as_reflect() {
let mut world = World::new();
world.init_resource::<AppTypeRegistry>();
let app_type_registry = world.get_resource_mut::<AppTypeRegistry>().unwrap();
app_type_registry.write().register::<RFoo>();
{
let entity_with_rfoo = world.spawn(RFoo(42)).id();
let comp_reflect = world
.get_reflect(entity_with_rfoo, TypeId::of::<RFoo>())
.expect("Reflection of RFoo-component failed");
assert!(comp_reflect.is::<RFoo>());
}
{
let entity_without_rfoo = world.spawn_empty().id();
let reflect_opt = world.get_reflect(entity_without_rfoo, TypeId::of::<RFoo>());
assert!(reflect_opt.is_err());
}
{
let entity_with_bar = world.spawn(Bar).id();
let reflect_opt = world.get_reflect(entity_with_bar, TypeId::of::<Bar>());
assert!(reflect_opt.is_err());
}
}
#[test]
fn get_component_as_mut_reflect() {
let mut world = World::new();
world.init_resource::<AppTypeRegistry>();
let app_type_registry = world.get_resource_mut::<AppTypeRegistry>().unwrap();
app_type_registry.write().register::<RFoo>();
{
let entity_with_rfoo = world.spawn(RFoo(42)).id();
let mut comp_reflect = world
.get_reflect_mut(entity_with_rfoo, TypeId::of::<RFoo>())
.expect("Mutable reflection of RFoo-component failed");
let comp_rfoo_reflected = comp_reflect
.downcast_mut::<RFoo>()
.expect("Wrong type reflected (expected RFoo)");
assert_eq!(comp_rfoo_reflected.0, 42);
comp_rfoo_reflected.0 = 1337;
let rfoo_ref = world.entity(entity_with_rfoo).get_ref::<RFoo>().unwrap();
assert!(rfoo_ref.is_changed());
assert_eq!(rfoo_ref.0, 1337);
}
{
let entity_without_rfoo = world.spawn_empty().id();
let reflect_opt = world.get_reflect_mut(entity_without_rfoo, TypeId::of::<RFoo>());
assert!(reflect_opt.is_err());
}
{
let entity_with_bar = world.spawn(Bar).id();
let reflect_opt = world.get_reflect_mut(entity_with_bar, TypeId::of::<Bar>());
assert!(reflect_opt.is_err());
}
}
}
| 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/world/spawn_batch.rs | crates/bevy_ecs/src/world/spawn_batch.rs | use bevy_ptr::move_as_ptr;
use crate::{
bundle::{Bundle, BundleSpawner, NoBundleEffect},
change_detection::MaybeLocation,
entity::{AllocEntitiesIterator, Entity, EntitySetIterator},
world::World,
};
use core::iter::FusedIterator;
/// An iterator that spawns a series of entities and returns the [ID](Entity) of
/// each spawned entity.
///
/// If this iterator is not fully exhausted, any remaining entities will be spawned when this type is dropped.
pub struct SpawnBatchIter<'w, I>
where
I: Iterator,
I::Item: Bundle<Effect: NoBundleEffect>,
{
inner: I,
spawner: BundleSpawner<'w>,
allocator: AllocEntitiesIterator<'w>,
caller: MaybeLocation,
}
impl<'w, I> SpawnBatchIter<'w, I>
where
I: Iterator,
I::Item: Bundle<Effect: NoBundleEffect>,
{
#[inline]
#[track_caller]
pub(crate) fn new(world: &'w mut World, iter: I, caller: MaybeLocation) -> Self {
let change_tick = world.change_tick();
let (lower, upper) = iter.size_hint();
let length = upper.unwrap_or(lower);
let mut spawner = BundleSpawner::new::<I::Item>(world, change_tick);
spawner.reserve_storage(length);
let allocator = spawner.allocator().alloc_many(length as u32);
Self {
inner: iter,
allocator,
spawner,
caller,
}
}
}
impl<I> Drop for SpawnBatchIter<'_, I>
where
I: Iterator,
I::Item: Bundle<Effect: NoBundleEffect>,
{
fn drop(&mut self) {
// Iterate through self in order to spawn remaining bundles.
for _ in &mut *self {}
// Apply any commands from those operations.
// SAFETY: `self.spawner` will be dropped immediately after this call.
unsafe { self.spawner.flush_commands() };
}
}
impl<I> Iterator for SpawnBatchIter<'_, I>
where
I: Iterator,
I::Item: Bundle<Effect: NoBundleEffect>,
{
type Item = Entity;
fn next(&mut self) -> Option<Entity> {
let bundle = self.inner.next()?;
move_as_ptr!(bundle);
Some(if let Some(bulk) = self.allocator.next() {
// SAFETY: bundle matches spawner type and we just allocated it
unsafe {
self.spawner.spawn_at(bulk, bundle, self.caller);
}
bulk
} else {
// SAFETY: bundle matches spawner type
unsafe { self.spawner.spawn(bundle, self.caller) }
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<I, T> ExactSizeIterator for SpawnBatchIter<'_, I>
where
I: ExactSizeIterator<Item = T>,
T: Bundle<Effect: NoBundleEffect>,
{
fn len(&self) -> usize {
self.inner.len()
}
}
impl<I, T> FusedIterator for SpawnBatchIter<'_, I>
where
I: FusedIterator<Item = T>,
T: Bundle<Effect: NoBundleEffect>,
{
}
// SAFETY: Newly spawned entities are unique.
unsafe impl<I: Iterator, T> EntitySetIterator for SpawnBatchIter<'_, I>
where
I: FusedIterator<Item = T>,
T: Bundle<Effect: NoBundleEffect>,
{
}
| 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/world/entity_fetch.rs | crates/bevy_ecs/src/world/entity_fetch.rs | use alloc::vec::Vec;
use core::mem::MaybeUninit;
use crate::{
entity::{Entity, EntityHashMap, EntityHashSet, EntityNotSpawnedError},
error::Result,
world::{
error::EntityMutableFetchError, unsafe_world_cell::UnsafeWorldCell, EntityMut, EntityRef,
EntityWorldMut,
},
};
/// Provides a safe interface for non-structural access to the entities in a [`World`].
///
/// This cannot add or remove components, or spawn or despawn entities,
/// making it relatively safe to access in concert with other ECS data.
/// This type can be constructed via [`World::entities_and_commands`],
/// or [`DeferredWorld::entities_and_commands`].
///
/// [`World`]: crate::world::World
/// [`World::entities_and_commands`]: crate::world::World::entities_and_commands
/// [`DeferredWorld::entities_and_commands`]: crate::world::DeferredWorld::entities_and_commands
pub struct EntityFetcher<'w> {
cell: UnsafeWorldCell<'w>,
}
impl<'w> EntityFetcher<'w> {
// SAFETY:
// - The given `cell` has mutable access to all entities.
// - No other references to entities exist at the same time.
pub(crate) unsafe fn new(cell: UnsafeWorldCell<'w>) -> Self {
Self { cell }
}
/// Returns [`EntityRef`]s that expose read-only operations for the given
/// `entities`, returning [`Err`] if any of the given entities do not exist.
///
/// This function supports fetching a single entity or multiple entities:
/// - Pass an [`Entity`] to receive a single [`EntityRef`].
/// - Pass a slice of [`Entity`]s to receive a [`Vec<EntityRef>`].
/// - Pass an array of [`Entity`]s to receive an equally-sized array of [`EntityRef`]s.
/// - Pass a reference to a [`EntityHashSet`](crate::entity::EntityHashMap) to receive an
/// [`EntityHashMap<EntityRef>`](crate::entity::EntityHashMap).
///
/// # Errors
///
/// If any of the given `entities` do not exist in the world, the first
/// [`Entity`] found to be missing will return an [`EntityNotSpawnedError`].
///
/// # Examples
///
/// For examples, see [`World::entity`].
///
/// [`World::entity`]: crate::world::World::entity
#[inline]
pub fn get<F: WorldEntityFetch>(
&self,
entities: F,
) -> Result<F::Ref<'_>, EntityNotSpawnedError> {
// SAFETY: `&self` gives read access to all entities, and prevents mutable access.
unsafe { entities.fetch_ref(self.cell) }
}
/// Returns [`EntityMut`]s that expose read and write operations for the
/// given `entities`, returning [`Err`] if any of the given entities do not
/// exist.
///
/// This function supports fetching a single entity or multiple entities:
/// - Pass an [`Entity`] to receive a single [`EntityMut`].
/// - This reference type allows for structural changes to the entity,
/// such as adding or removing components, or despawning the entity.
/// - Pass a slice of [`Entity`]s to receive a [`Vec<EntityMut>`].
/// - Pass an array of [`Entity`]s to receive an equally-sized array of [`EntityMut`]s.
/// - Pass a reference to a [`EntityHashSet`](crate::entity::EntityHashMap) to receive an
/// [`EntityHashMap<EntityMut>`](crate::entity::EntityHashMap).
/// # Errors
///
/// - Returns [`EntityMutableFetchError::NotSpawned`] if any of the given `entities` do not exist in the world.
/// - Only the first entity found to be missing will be returned.
/// - Returns [`EntityMutableFetchError::AliasedMutability`] if the same entity is requested multiple times.
///
/// # Examples
///
/// For examples, see [`DeferredWorld::entity_mut`].
///
/// [`DeferredWorld::entity_mut`]: crate::world::DeferredWorld::entity_mut
#[inline]
pub fn get_mut<F: WorldEntityFetch>(
&mut self,
entities: F,
) -> Result<F::DeferredMut<'_>, EntityMutableFetchError> {
// SAFETY: `&mut self` gives mutable access to all entities,
// and prevents any other access to entities.
unsafe { entities.fetch_deferred_mut(self.cell) }
}
}
/// Types that can be used to fetch [`Entity`] references from a [`World`].
///
/// Provided implementations are:
/// - [`Entity`]: Fetch a single entity.
/// - `[Entity; N]`/`&[Entity; N]`: Fetch multiple entities, receiving a
/// same-sized array of references.
/// - `&[Entity]`: Fetch multiple entities, receiving a vector of references.
/// - [`&EntityHashSet`](EntityHashSet): Fetch multiple entities, receiving a
/// hash map of [`Entity`] IDs to references.
///
/// # Performance
///
/// - The slice and array implementations perform an aliased mutability check
/// in [`WorldEntityFetch::fetch_mut`] that is `O(N^2)`.
/// - The single [`Entity`] implementation performs no such check as only one
/// reference is returned.
///
/// # Safety
///
/// Implementor must ensure that:
/// - No aliased mutability is caused by the returned references.
/// - [`WorldEntityFetch::fetch_ref`] returns only read-only references.
/// - [`WorldEntityFetch::fetch_deferred_mut`] returns only non-structurally-mutable references.
///
/// [`World`]: crate::world::World
pub unsafe trait WorldEntityFetch {
/// The read-only reference type returned by [`WorldEntityFetch::fetch_ref`].
type Ref<'w>;
/// The mutable reference type returned by [`WorldEntityFetch::fetch_mut`].
type Mut<'w>;
/// The mutable reference type returned by [`WorldEntityFetch::fetch_deferred_mut`],
/// but without structural mutability.
type DeferredMut<'w>;
/// Returns read-only reference(s) to the entities with the given
/// [`Entity`] IDs, as determined by `self`.
///
/// # Safety
///
/// It is the caller's responsibility to ensure that:
/// - The given [`UnsafeWorldCell`] has read-only access to the fetched entities.
/// - No other mutable references to the fetched entities exist at the same time.
///
/// # Errors
///
/// - Returns [`EntityNotSpawnedError`] if the entity does not exist.
unsafe fn fetch_ref(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::Ref<'_>, EntityNotSpawnedError>;
/// Returns mutable reference(s) to the entities with the given [`Entity`]
/// IDs, as determined by `self`.
///
/// # Safety
///
/// It is the caller's responsibility to ensure that:
/// - The given [`UnsafeWorldCell`] has mutable access to the fetched entities.
/// - No other references to the fetched entities exist at the same time.
///
/// # Errors
///
/// - Returns [`EntityMutableFetchError::NotSpawned`] if the entity does not exist.
/// - Returns [`EntityMutableFetchError::AliasedMutability`] if the entity was
/// requested mutably more than once.
unsafe fn fetch_mut(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::Mut<'_>, EntityMutableFetchError>;
/// Returns mutable reference(s) to the entities with the given [`Entity`]
/// IDs, as determined by `self`, but without structural mutability.
///
/// No structural mutability means components cannot be removed from the
/// entity, new components cannot be added to the entity, and the entity
/// cannot be despawned.
///
/// # Safety
///
/// It is the caller's responsibility to ensure that:
/// - The given [`UnsafeWorldCell`] has mutable access to the fetched entities.
/// - No other references to the fetched entities exist at the same time.
///
/// # Errors
///
/// - Returns [`EntityMutableFetchError::NotSpawned`] if the entity does not exist.
/// - Returns [`EntityMutableFetchError::AliasedMutability`] if the entity was
/// requested mutably more than once.
unsafe fn fetch_deferred_mut(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::DeferredMut<'_>, EntityMutableFetchError>;
}
// SAFETY:
// - No aliased mutability is caused because a single reference is returned.
// - No mutable references are returned by `fetch_ref`.
// - No structurally-mutable references are returned by `fetch_deferred_mut`.
unsafe impl WorldEntityFetch for Entity {
type Ref<'w> = EntityRef<'w>;
type Mut<'w> = EntityWorldMut<'w>;
type DeferredMut<'w> = EntityMut<'w>;
#[inline]
unsafe fn fetch_ref(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::Ref<'_>, EntityNotSpawnedError> {
let ecell = cell.get_entity(self)?;
// SAFETY: caller ensures that the world cell has read-only access to the entity.
Ok(unsafe { EntityRef::new(ecell) })
}
#[inline]
unsafe fn fetch_mut(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::Mut<'_>, EntityMutableFetchError> {
let location = cell.entities().get_spawned(self)?;
// SAFETY: caller ensures that the world cell has mutable access to the entity.
let world = unsafe { cell.world_mut() };
// SAFETY: location was fetched from the same world's `Entities`.
Ok(unsafe { EntityWorldMut::new(world, self, Some(location)) })
}
#[inline]
unsafe fn fetch_deferred_mut(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::DeferredMut<'_>, EntityMutableFetchError> {
let ecell = cell.get_entity(self)?;
// SAFETY: caller ensures that the world cell has mutable access to the entity.
Ok(unsafe { EntityMut::new(ecell) })
}
}
// SAFETY:
// - No aliased mutability is caused because the array is checked for duplicates.
// - No mutable references are returned by `fetch_ref`.
// - No structurally-mutable references are returned by `fetch_deferred_mut`.
unsafe impl<const N: usize> WorldEntityFetch for [Entity; N] {
type Ref<'w> = [EntityRef<'w>; N];
type Mut<'w> = [EntityMut<'w>; N];
type DeferredMut<'w> = [EntityMut<'w>; N];
#[inline]
unsafe fn fetch_ref(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::Ref<'_>, EntityNotSpawnedError> {
// SAFETY: Upheld by caller
unsafe { <&Self>::fetch_ref(&self, cell) }
}
#[inline]
unsafe fn fetch_mut(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::Mut<'_>, EntityMutableFetchError> {
// SAFETY: Upheld by caller
unsafe { <&Self>::fetch_mut(&self, cell) }
}
#[inline]
unsafe fn fetch_deferred_mut(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::DeferredMut<'_>, EntityMutableFetchError> {
// SAFETY: Upheld by caller
unsafe { <&Self>::fetch_deferred_mut(&self, cell) }
}
}
// SAFETY:
// - No aliased mutability is caused because the array is checked for duplicates.
// - No mutable references are returned by `fetch_ref`.
// - No structurally-mutable references are returned by `fetch_deferred_mut`.
unsafe impl<const N: usize> WorldEntityFetch for &'_ [Entity; N] {
type Ref<'w> = [EntityRef<'w>; N];
type Mut<'w> = [EntityMut<'w>; N];
type DeferredMut<'w> = [EntityMut<'w>; N];
#[inline]
unsafe fn fetch_ref(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::Ref<'_>, EntityNotSpawnedError> {
let mut refs = [MaybeUninit::uninit(); N];
for (r, &id) in core::iter::zip(&mut refs, self) {
let ecell = cell.get_entity(id)?;
// SAFETY: caller ensures that the world cell has read-only access to the entity.
*r = MaybeUninit::new(unsafe { EntityRef::new(ecell) });
}
// SAFETY: Each item was initialized in the loop above.
let refs = refs.map(|r| unsafe { MaybeUninit::assume_init(r) });
Ok(refs)
}
#[inline]
unsafe fn fetch_mut(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::Mut<'_>, EntityMutableFetchError> {
// Check for duplicate entities.
for i in 0..self.len() {
for j in 0..i {
if self[i] == self[j] {
return Err(EntityMutableFetchError::AliasedMutability(self[i]));
}
}
}
let mut refs = [const { MaybeUninit::uninit() }; N];
for (r, &id) in core::iter::zip(&mut refs, self) {
let ecell = cell.get_entity(id)?;
// SAFETY: caller ensures that the world cell has mutable access to the entity.
*r = MaybeUninit::new(unsafe { EntityMut::new(ecell) });
}
// SAFETY: Each item was initialized in the loop above.
let refs = refs.map(|r| unsafe { MaybeUninit::assume_init(r) });
Ok(refs)
}
#[inline]
unsafe fn fetch_deferred_mut(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::DeferredMut<'_>, EntityMutableFetchError> {
// SAFETY: caller ensures that the world cell has mutable access to the entity,
// and `fetch_mut` does not return structurally-mutable references.
unsafe { self.fetch_mut(cell) }
}
}
// SAFETY:
// - No aliased mutability is caused because the slice is checked for duplicates.
// - No mutable references are returned by `fetch_ref`.
// - No structurally-mutable references are returned by `fetch_deferred_mut`.
unsafe impl WorldEntityFetch for &'_ [Entity] {
type Ref<'w> = Vec<EntityRef<'w>>;
type Mut<'w> = Vec<EntityMut<'w>>;
type DeferredMut<'w> = Vec<EntityMut<'w>>;
#[inline]
unsafe fn fetch_ref(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::Ref<'_>, EntityNotSpawnedError> {
let mut refs = Vec::with_capacity(self.len());
for &id in self {
let ecell = cell.get_entity(id)?;
// SAFETY: caller ensures that the world cell has read-only access to the entity.
refs.push(unsafe { EntityRef::new(ecell) });
}
Ok(refs)
}
#[inline]
unsafe fn fetch_mut(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::Mut<'_>, EntityMutableFetchError> {
// Check for duplicate entities.
for i in 0..self.len() {
for j in 0..i {
if self[i] == self[j] {
return Err(EntityMutableFetchError::AliasedMutability(self[i]));
}
}
}
let mut refs = Vec::with_capacity(self.len());
for &id in self {
let ecell = cell.get_entity(id)?;
// SAFETY: caller ensures that the world cell has mutable access to the entity.
refs.push(unsafe { EntityMut::new(ecell) });
}
Ok(refs)
}
#[inline]
unsafe fn fetch_deferred_mut(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::DeferredMut<'_>, EntityMutableFetchError> {
// SAFETY: caller ensures that the world cell has mutable access to the entity,
// and `fetch_mut` does not return structurally-mutable references.
unsafe { self.fetch_mut(cell) }
}
}
// SAFETY:
// - No aliased mutability is caused because `EntityHashSet` guarantees no duplicates.
// - No mutable references are returned by `fetch_ref`.
// - No structurally-mutable references are returned by `fetch_deferred_mut`.
unsafe impl WorldEntityFetch for &'_ EntityHashSet {
type Ref<'w> = EntityHashMap<EntityRef<'w>>;
type Mut<'w> = EntityHashMap<EntityMut<'w>>;
type DeferredMut<'w> = EntityHashMap<EntityMut<'w>>;
#[inline]
unsafe fn fetch_ref(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::Ref<'_>, EntityNotSpawnedError> {
let mut refs = EntityHashMap::with_capacity(self.len());
for &id in self {
let ecell = cell.get_entity(id)?;
// SAFETY: caller ensures that the world cell has read-only access to the entity.
refs.insert(id, unsafe { EntityRef::new(ecell) });
}
Ok(refs)
}
#[inline]
unsafe fn fetch_mut(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::Mut<'_>, EntityMutableFetchError> {
let mut refs = EntityHashMap::with_capacity(self.len());
for &id in self {
let ecell = cell.get_entity(id)?;
// SAFETY: caller ensures that the world cell has mutable access to the entity.
refs.insert(id, unsafe { EntityMut::new(ecell) });
}
Ok(refs)
}
#[inline]
unsafe fn fetch_deferred_mut(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<Self::DeferredMut<'_>, EntityMutableFetchError> {
// SAFETY: caller ensures that the world cell has mutable access to the entity,
// and `fetch_mut` does not return structurally-mutable references.
unsafe { self.fetch_mut(cell) }
}
}
| 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/world/unsafe_world_cell.rs | crates/bevy_ecs/src/world/unsafe_world_cell.rs | //! Contains types that allow disjoint mutable access to a [`World`].
use super::{Mut, Ref, World, WorldId};
use crate::{
archetype::{Archetype, Archetypes},
bundle::Bundles,
change_detection::{
ComponentTickCells, ComponentTicks, ComponentTicksMut, ComponentTicksRef, MaybeLocation,
MutUntyped, Tick,
},
component::{ComponentId, Components, Mutable, StorageType},
entity::{
ContainsEntity, Entities, Entity, EntityAllocator, EntityLocation, EntityNotSpawnedError,
},
error::{DefaultErrorHandler, ErrorHandler},
lifecycle::RemovedComponentMessages,
observer::Observers,
prelude::Component,
query::{DebugCheckedUnwrap, QueryAccessError, ReleaseStateQueryData},
resource::Resource,
storage::{ComponentSparseSet, Storages, Table},
world::RawCommandQueue,
};
use bevy_platform::sync::atomic::Ordering;
use bevy_ptr::Ptr;
use core::{any::TypeId, cell::UnsafeCell, fmt::Debug, marker::PhantomData, ptr};
use thiserror::Error;
/// Variant of the [`World`] where resource and component accesses take `&self`, and the responsibility to avoid
/// aliasing violations are given to the caller instead of being checked at compile-time by rust's unique XOR shared rule.
///
/// ### Rationale
/// In rust, having a `&mut World` means that there are absolutely no other references to the safe world alive at the same time,
/// without exceptions. Not even unsafe code can change this.
///
/// But there are situations where careful shared mutable access through a type is possible and safe. For this, rust provides the [`UnsafeCell`]
/// escape hatch, which allows you to get a `*mut T` from a `&UnsafeCell<T>` and around which safe abstractions can be built.
///
/// Access to resources and components can be done uniquely using [`World::resource_mut`] and [`World::entity_mut`], and shared using [`World::resource`] and [`World::entity`].
/// These methods use lifetimes to check at compile time that no aliasing rules are being broken.
///
/// This alone is not enough to implement bevy systems where multiple systems can access *disjoint* parts of the world concurrently. For this, bevy stores all values of
/// resources and components (and [`ComponentTicks`]) in [`UnsafeCell`]s, and carefully validates disjoint access patterns using
/// APIs like [`System::initialize`](crate::system::System::initialize).
///
/// A system then can be executed using [`System::run_unsafe`](crate::system::System::run_unsafe) with a `&World` and use methods with interior mutability to access resource values.
///
/// ### Example Usage
///
/// [`UnsafeWorldCell`] can be used as a building block for writing APIs that safely allow disjoint access into the world.
/// In the following example, the world is split into a resource access half and a component access half, where each one can
/// safely hand out mutable references.
///
/// ```
/// use bevy_ecs::world::World;
/// use bevy_ecs::change_detection::Mut;
/// use bevy_ecs::resource::Resource;
/// use bevy_ecs::world::unsafe_world_cell::UnsafeWorldCell;
///
/// // INVARIANT: existence of this struct means that users of it are the only ones being able to access resources in the world
/// struct OnlyResourceAccessWorld<'w>(UnsafeWorldCell<'w>);
/// // INVARIANT: existence of this struct means that users of it are the only ones being able to access components in the world
/// struct OnlyComponentAccessWorld<'w>(UnsafeWorldCell<'w>);
///
/// impl<'w> OnlyResourceAccessWorld<'w> {
/// fn get_resource_mut<T: Resource>(&mut self) -> Option<Mut<'_, T>> {
/// // SAFETY: resource access is allowed through this UnsafeWorldCell
/// unsafe { self.0.get_resource_mut::<T>() }
/// }
/// }
/// // impl<'w> OnlyComponentAccessWorld<'w> {
/// // ...
/// // }
///
/// // the two `UnsafeWorldCell`s borrow from the `&mut World`, so it cannot be accessed while they are live
/// fn split_world_access(world: &mut World) -> (OnlyResourceAccessWorld<'_>, OnlyComponentAccessWorld<'_>) {
/// let unsafe_world_cell = world.as_unsafe_world_cell();
/// let resource_access = OnlyResourceAccessWorld(unsafe_world_cell);
/// let component_access = OnlyComponentAccessWorld(unsafe_world_cell);
/// (resource_access, component_access)
/// }
/// ```
#[derive(Copy, Clone)]
pub struct UnsafeWorldCell<'w> {
ptr: *mut World,
#[cfg(debug_assertions)]
allows_mutable_access: bool,
_marker: PhantomData<(&'w World, &'w UnsafeCell<World>)>,
}
// SAFETY: `&World` and `&mut World` are both `Send`
unsafe impl Send for UnsafeWorldCell<'_> {}
// SAFETY: `&World` and `&mut World` are both `Sync`
unsafe impl Sync for UnsafeWorldCell<'_> {}
impl<'w> From<&'w mut World> for UnsafeWorldCell<'w> {
fn from(value: &'w mut World) -> Self {
value.as_unsafe_world_cell()
}
}
impl<'w> From<&'w World> for UnsafeWorldCell<'w> {
fn from(value: &'w World) -> Self {
value.as_unsafe_world_cell_readonly()
}
}
impl<'w> UnsafeWorldCell<'w> {
/// Creates a [`UnsafeWorldCell`] that can be used to access everything immutably
#[inline]
pub(crate) fn new_readonly(world: &'w World) -> Self {
Self {
ptr: ptr::from_ref(world).cast_mut(),
#[cfg(debug_assertions)]
allows_mutable_access: false,
_marker: PhantomData,
}
}
/// Creates [`UnsafeWorldCell`] that can be used to access everything mutably
#[inline]
pub(crate) fn new_mutable(world: &'w mut World) -> Self {
Self {
ptr: ptr::from_mut(world),
#[cfg(debug_assertions)]
allows_mutable_access: true,
_marker: PhantomData,
}
}
#[cfg_attr(debug_assertions, inline(never), track_caller)]
#[cfg_attr(not(debug_assertions), inline(always))]
pub(crate) fn assert_allows_mutable_access(self) {
// This annotation is needed because the
// allows_mutable_access field doesn't exist otherwise.
// Kinda weird, since debug_assert would never be called,
// but CI complained in https://github.com/bevyengine/bevy/pull/17393
#[cfg(debug_assertions)]
debug_assert!(
self.allows_mutable_access,
"mutating world data via `World::as_unsafe_world_cell_readonly` is forbidden"
);
}
/// Gets a mutable reference to the [`World`] this [`UnsafeWorldCell`] belongs to.
/// This is an incredibly error-prone operation and is only valid in a small number of circumstances.
///
/// Calling this method implies mutable access to the *whole* world (see first point on safety section
/// below), which includes all entities, components, and resources. Notably, calling this on
/// [`WorldQuery::init_fetch`](crate::query::WorldQuery::init_fetch) and
/// [`SystemParam::get_param`](crate::system::SystemParam::get_param) are most likely *unsound* unless
/// you can prove that the underlying [`World`] is exclusive, which in normal circumstances is not.
///
/// # Safety
/// - `self` must have been obtained from a call to [`World::as_unsafe_world_cell`]
/// (*not* `as_unsafe_world_cell_readonly` or any other method of construction that
/// does not provide mutable access to the entire world).
/// - This means that if you have an `UnsafeWorldCell` that you didn't create yourself,
/// it is likely *unsound* to call this method.
/// - The returned `&mut World` *must* be unique: it must never be allowed to exist
/// at the same time as any other borrows of the world or any accesses to its data.
/// This includes safe ways of accessing world data, such as [`UnsafeWorldCell::archetypes`].
/// - Note that the `&mut World` *may* exist at the same time as instances of `UnsafeWorldCell`,
/// so long as none of those instances are used to access world data in any way
/// while the mutable borrow is active.
///
/// [//]: # (This test fails miri.)
/// ```no_run
/// # use bevy_ecs::prelude::*;
/// # #[derive(Component)] struct Player;
/// # fn store_but_dont_use<T>(_: T) {}
/// # let mut world = World::new();
/// // Make an UnsafeWorldCell.
/// let world_cell = world.as_unsafe_world_cell();
///
/// // SAFETY: `world_cell` was originally created from `&mut World`.
/// // We must be sure not to access any world data while `world_mut` is active.
/// let world_mut = unsafe { world_cell.world_mut() };
///
/// // We can still use `world_cell` so long as we don't access the world with it.
/// store_but_dont_use(world_cell);
///
/// // !!This is unsound!! Even though this method is safe, we cannot call it until
/// // `world_mut` is no longer active.
/// let tick = world_cell.change_tick();
///
/// // Use mutable access to spawn an entity.
/// world_mut.spawn(Player);
///
/// // Since we never use `world_mut` after this, the borrow is released
/// // and we are once again allowed to access the world using `world_cell`.
/// let archetypes = world_cell.archetypes();
/// ```
#[inline]
pub unsafe fn world_mut(self) -> &'w mut World {
self.assert_allows_mutable_access();
// SAFETY:
// - caller ensures the created `&mut World` is the only borrow of world
unsafe { &mut *self.ptr }
}
/// Gets a reference to the [`&World`](World) this [`UnsafeWorldCell`] belongs to.
/// This can be used for arbitrary shared/readonly access.
///
/// # Safety
/// - must have permission to access the whole world immutably
/// - there must be no live exclusive borrows of world data
/// - there must be no live exclusive borrow of world
#[inline]
pub unsafe fn world(self) -> &'w World {
// SAFETY:
// - caller ensures there is no `&mut World` this makes it okay to make a `&World`
// - caller ensures there are no mutable borrows of world data, this means the caller cannot
// misuse the returned `&World`
unsafe { self.unsafe_world() }
}
/// Gets a reference to the [`World`] this [`UnsafeWorldCell`] belong to.
/// This can be used for arbitrary read only access of world metadata
///
/// You should attempt to use various safe methods on [`UnsafeWorldCell`] for
/// metadata access before using this method.
///
/// # Safety
/// - must only be used to access world metadata
#[inline]
pub unsafe fn world_metadata(self) -> &'w World {
// SAFETY: caller ensures that returned reference is not used to violate aliasing rules
unsafe { self.unsafe_world() }
}
/// Variant on [`UnsafeWorldCell::world`] solely used for implementing this type's methods.
/// It allows having an `&World` even with live mutable borrows of components and resources
/// so the returned `&World` should not be handed out to safe code and care should be taken
/// when working with it.
///
/// Deliberately private as the correct way to access data in a [`World`] that may have existing
/// mutable borrows of data inside it, is to use [`UnsafeWorldCell`].
///
/// # Safety
/// - must not be used in a way that would conflict with any
/// live exclusive borrows of world data
#[inline]
unsafe fn unsafe_world(self) -> &'w World {
// SAFETY:
// - caller ensures that the returned `&World` is not used in a way that would conflict
// with any existing mutable borrows of world data
unsafe { &*self.ptr }
}
/// Retrieves this world's unique [ID](WorldId).
#[inline]
pub fn id(self) -> WorldId {
// SAFETY:
// - we only access world metadata
unsafe { self.world_metadata() }.id()
}
/// Retrieves this world's [`Entities`] collection.
#[inline]
pub fn entities(self) -> &'w Entities {
// SAFETY:
// - we only access world metadata
&unsafe { self.world_metadata() }.entities
}
/// Retrieves this world's [`Entities`] collection.
#[inline]
pub fn entities_allocator(self) -> &'w EntityAllocator {
// SAFETY:
// - we only access world metadata
&unsafe { self.world_metadata() }.allocator
}
/// Retrieves this world's [`Archetypes`] collection.
#[inline]
pub fn archetypes(self) -> &'w Archetypes {
// SAFETY:
// - we only access world metadata
&unsafe { self.world_metadata() }.archetypes
}
/// Retrieves this world's [`Components`] collection.
#[inline]
pub fn components(self) -> &'w Components {
// SAFETY:
// - we only access world metadata
&unsafe { self.world_metadata() }.components
}
/// Retrieves this world's collection of [removed components](RemovedComponentMessages).
pub fn removed_components(self) -> &'w RemovedComponentMessages {
// SAFETY:
// - we only access world metadata
&unsafe { self.world_metadata() }.removed_components
}
/// Retrieves this world's [`Observers`] collection.
pub(crate) fn observers(self) -> &'w Observers {
// SAFETY:
// - we only access world metadata
&unsafe { self.world_metadata() }.observers
}
/// Retrieves this world's [`Bundles`] collection.
#[inline]
pub fn bundles(self) -> &'w Bundles {
// SAFETY:
// - we only access world metadata
&unsafe { self.world_metadata() }.bundles
}
/// Gets the current change tick of this world.
#[inline]
pub fn change_tick(self) -> Tick {
// SAFETY:
// - we only access world metadata
unsafe { self.world_metadata() }.read_change_tick()
}
/// Returns the id of the last ECS event that was fired.
/// Used internally to ensure observers don't trigger multiple times for the same event.
#[inline]
pub fn last_trigger_id(&self) -> u32 {
// SAFETY:
// - we only access world metadata
unsafe { self.world_metadata() }.last_trigger_id()
}
/// Returns the [`Tick`] indicating the last time that [`World::clear_trackers`] was called.
///
/// If this `UnsafeWorldCell` was created from inside of an exclusive system (a [`System`] that
/// takes `&mut World` as its first parameter), this will instead return the `Tick` indicating
/// the last time the system was run.
///
/// See [`World::last_change_tick()`].
///
/// [`System`]: crate::system::System
#[inline]
pub fn last_change_tick(self) -> Tick {
// SAFETY:
// - we only access world metadata
unsafe { self.world_metadata() }.last_change_tick()
}
/// Increments the world's current change tick and returns the old value.
#[inline]
pub fn increment_change_tick(self) -> Tick {
// SAFETY:
// - we only access world metadata
let change_tick = unsafe { &self.world_metadata().change_tick };
// NOTE: We can used a relaxed memory ordering here, since nothing
// other than the atomic value itself is relying on atomic synchronization
Tick::new(change_tick.fetch_add(1, Ordering::Relaxed))
}
/// Provides unchecked access to the internal data stores of the [`World`].
///
/// # Safety
///
/// The caller must ensure that this is only used to access world data
/// that this [`UnsafeWorldCell`] is allowed to.
/// As always, any mutable access to a component must not exist at the same
/// time as any other accesses to that same component.
#[inline]
pub unsafe fn storages(self) -> &'w Storages {
// SAFETY: The caller promises to only access world data allowed by this instance.
&unsafe { self.unsafe_world() }.storages
}
/// Retrieves an [`UnsafeEntityCell`] that exposes read and write operations for the given `entity`.
/// Similar to the [`UnsafeWorldCell`], you are in charge of making sure that no aliasing rules are violated.
#[inline]
pub fn get_entity(self, entity: Entity) -> Result<UnsafeEntityCell<'w>, EntityNotSpawnedError> {
let location = self.entities().get_spawned(entity)?;
Ok(UnsafeEntityCell::new(
self,
entity,
location,
self.last_change_tick(),
self.change_tick(),
))
}
/// Retrieves an [`UnsafeEntityCell`] that exposes read and write operations for the given `entity`.
/// Similar to the [`UnsafeWorldCell`], you are in charge of making sure that no aliasing rules are violated.
#[inline]
pub fn get_entity_with_ticks(
self,
entity: Entity,
last_run: Tick,
this_run: Tick,
) -> Result<UnsafeEntityCell<'w>, EntityNotSpawnedError> {
let location = self.entities().get_spawned(entity)?;
Ok(UnsafeEntityCell::new(
self, entity, location, last_run, this_run,
))
}
/// Gets a reference to the resource of the given type if it exists
///
/// # Safety
/// It is the caller's responsibility to ensure that
/// - the [`UnsafeWorldCell`] has permission to access the resource
/// - no mutable reference to the resource exists at the same time
#[inline]
pub unsafe fn get_resource<R: Resource>(self) -> Option<&'w R> {
let component_id = self.components().get_valid_resource_id(TypeId::of::<R>())?;
// SAFETY: caller ensures `self` has permission to access the resource
// caller also ensure that no mutable reference to the resource exists
unsafe {
self.get_resource_by_id(component_id)
// SAFETY: `component_id` was obtained from the type ID of `R`.
.map(|ptr| ptr.deref::<R>())
}
}
/// Gets a reference including change detection to the resource of the given type if it exists.
///
/// # Safety
/// It is the caller's responsibility to ensure that
/// - the [`UnsafeWorldCell`] has permission to access the resource
/// - no mutable reference to the resource exists at the same time
#[inline]
pub unsafe fn get_resource_ref<R: Resource>(self) -> Option<Ref<'w, R>> {
let component_id = self.components().get_valid_resource_id(TypeId::of::<R>())?;
// SAFETY: caller ensures `self` has permission to access the resource
// caller also ensures that no mutable reference to the resource exists
let (ptr, ticks) = unsafe { self.get_resource_with_ticks(component_id)? };
// SAFETY: `component_id` was obtained from the type ID of `R`
let value = unsafe { ptr.deref::<R>() };
// SAFETY: caller ensures that no mutable reference to the resource exists
let ticks = unsafe {
ComponentTicksRef::from_tick_cells(ticks, self.last_change_tick(), self.change_tick())
};
Some(Ref { value, ticks })
}
/// Gets a pointer to the resource with the id [`ComponentId`] if it exists.
/// The returned pointer must not be used to modify the resource, and must not be
/// dereferenced after the borrow of the [`World`] ends.
///
/// **You should prefer to use the typed API [`UnsafeWorldCell::get_resource`] where possible and only
/// use this in cases where the actual types are not known at compile time.**
///
/// # Safety
/// It is the caller's responsibility to ensure that
/// - the [`UnsafeWorldCell`] has permission to access the resource
/// - no mutable reference to the resource exists at the same time
#[inline]
pub unsafe fn get_resource_by_id(self, component_id: ComponentId) -> Option<Ptr<'w>> {
// SAFETY: caller ensures that `self` has permission to access `R`
// caller ensures that no mutable reference exists to `R`
unsafe { self.storages() }
.resources
.get(component_id)?
.get_data()
}
/// Gets a reference to the non-send resource of the given type if it exists
///
/// # Safety
/// It is the caller's responsibility to ensure that
/// - the [`UnsafeWorldCell`] has permission to access the resource
/// - no mutable reference to the resource exists at the same time
#[inline]
pub unsafe fn get_non_send_resource<R: 'static>(self) -> Option<&'w R> {
let component_id = self.components().get_valid_resource_id(TypeId::of::<R>())?;
// SAFETY: caller ensures that `self` has permission to access `R`
// caller ensures that no mutable reference exists to `R`
unsafe {
self.get_non_send_resource_by_id(component_id)
// SAFETY: `component_id` was obtained from `TypeId::of::<R>()`
.map(|ptr| ptr.deref::<R>())
}
}
/// Gets a `!Send` resource to the resource with the id [`ComponentId`] if it exists.
/// The returned pointer must not be used to modify the resource, and must not be
/// dereferenced after the immutable borrow of the [`World`] ends.
///
/// **You should prefer to use the typed API [`UnsafeWorldCell::get_non_send_resource`] where possible and only
/// use this in cases where the actual types are not known at compile time.**
///
/// # Panics
/// This function will panic if it isn't called from the same thread that the resource was inserted from.
///
/// # Safety
/// It is the caller's responsibility to ensure that
/// - the [`UnsafeWorldCell`] has permission to access the resource
/// - no mutable reference to the resource exists at the same time
#[inline]
pub unsafe fn get_non_send_resource_by_id(self, component_id: ComponentId) -> Option<Ptr<'w>> {
// SAFETY: we only access data on world that the caller has ensured is unaliased and we have
// permission to access.
unsafe { self.storages() }
.non_send_resources
.get(component_id)?
.get_data()
}
/// Gets a mutable reference to the resource of the given type if it exists
///
/// # Safety
/// It is the caller's responsibility to ensure that
/// - the [`UnsafeWorldCell`] has permission to access the resource mutably
/// - no other references to the resource exist at the same time
#[inline]
pub unsafe fn get_resource_mut<R: Resource>(self) -> Option<Mut<'w, R>> {
self.assert_allows_mutable_access();
let component_id = self.components().get_valid_resource_id(TypeId::of::<R>())?;
// SAFETY:
// - caller ensures `self` has permission to access the resource mutably
// - caller ensures no other references to the resource exist
unsafe {
self.get_resource_mut_by_id(component_id)
// `component_id` was gotten from `TypeId::of::<R>()`
.map(|ptr| ptr.with_type::<R>())
}
}
/// Gets a pointer to the resource with the id [`ComponentId`] if it exists.
/// The returned pointer may be used to modify the resource, as long as the mutable borrow
/// of the [`UnsafeWorldCell`] is still valid.
///
/// **You should prefer to use the typed API [`UnsafeWorldCell::get_resource_mut`] where possible and only
/// use this in cases where the actual types are not known at compile time.**
///
/// # Safety
/// It is the caller's responsibility to ensure that
/// - the [`UnsafeWorldCell`] has permission to access the resource mutably
/// - no other references to the resource exist at the same time
#[inline]
pub unsafe fn get_resource_mut_by_id(
self,
component_id: ComponentId,
) -> Option<MutUntyped<'w>> {
self.assert_allows_mutable_access();
// SAFETY: we only access data that the caller has ensured is unaliased and `self`
// has permission to access.
let (ptr, ticks) = unsafe { self.storages() }
.resources
.get(component_id)?
.get_with_ticks()?;
// SAFETY:
// - index is in-bounds because the column is initialized and non-empty
// - the caller promises that no other reference to the ticks of the same row can exist at the same time
let ticks = unsafe {
ComponentTicksMut::from_tick_cells(ticks, self.last_change_tick(), self.change_tick())
};
Some(MutUntyped {
// SAFETY:
// - caller ensures that `self` has permission to access the resource
// - caller ensures that the resource is unaliased
value: unsafe { ptr.assert_unique() },
ticks,
})
}
/// Gets a mutable reference to the non-send resource of the given type if it exists
///
/// # Safety
/// It is the caller's responsibility to ensure that
/// - the [`UnsafeWorldCell`] has permission to access the resource mutably
/// - no other references to the resource exist at the same time
#[inline]
pub unsafe fn get_non_send_resource_mut<R: 'static>(self) -> Option<Mut<'w, R>> {
self.assert_allows_mutable_access();
let component_id = self.components().get_valid_resource_id(TypeId::of::<R>())?;
// SAFETY:
// - caller ensures that `self` has permission to access the resource
// - caller ensures that the resource is unaliased
unsafe {
self.get_non_send_resource_mut_by_id(component_id)
// SAFETY: `component_id` was gotten by `TypeId::of::<R>()`
.map(|ptr| ptr.with_type::<R>())
}
}
/// Gets a `!Send` resource to the resource with the id [`ComponentId`] if it exists.
/// The returned pointer may be used to modify the resource, as long as the mutable borrow
/// of the [`World`] is still valid.
///
/// **You should prefer to use the typed API [`UnsafeWorldCell::get_non_send_resource_mut`] where possible and only
/// use this in cases where the actual types are not known at compile time.**
///
/// # Panics
/// This function will panic if it isn't called from the same thread that the resource was inserted from.
///
/// # Safety
/// It is the caller's responsibility to ensure that
/// - the [`UnsafeWorldCell`] has permission to access the resource mutably
/// - no other references to the resource exist at the same time
#[inline]
pub unsafe fn get_non_send_resource_mut_by_id(
self,
component_id: ComponentId,
) -> Option<MutUntyped<'w>> {
self.assert_allows_mutable_access();
let change_tick = self.change_tick();
// SAFETY: we only access data that the caller has ensured is unaliased and `self`
// has permission to access.
let (ptr, ticks) = unsafe { self.storages() }
.non_send_resources
.get(component_id)?
.get_with_ticks()?;
let ticks =
// SAFETY: This function has exclusive access to the world so nothing aliases `ticks`.
// - index is in-bounds because the column is initialized and non-empty
// - no other reference to the ticks of the same row can exist at the same time
unsafe { ComponentTicksMut::from_tick_cells(ticks, self.last_change_tick(), change_tick) };
Some(MutUntyped {
// SAFETY: This function has exclusive access to the world so nothing aliases `ptr`.
value: unsafe { ptr.assert_unique() },
ticks,
})
}
// Shorthand helper function for getting the data and change ticks for a resource.
/// # Safety
/// It is the caller's responsibility to ensure that
/// - the [`UnsafeWorldCell`] has permission to access the resource mutably
/// - no mutable references to the resource exist at the same time
#[inline]
pub(crate) unsafe fn get_resource_with_ticks(
self,
component_id: ComponentId,
) -> Option<(Ptr<'w>, ComponentTickCells<'w>)> {
// SAFETY:
// - caller ensures there is no `&mut World`
// - caller ensures there are no mutable borrows of this resource
// - caller ensures that we have permission to access this resource
unsafe { self.storages() }
.resources
.get(component_id)?
.get_with_ticks()
}
// Shorthand helper function for getting the data and change ticks for a resource.
/// # Panics
/// This function will panic if it isn't called from the same thread that the resource was inserted from.
///
/// # Safety
/// It is the caller's responsibility to ensure that
/// - the [`UnsafeWorldCell`] has permission to access the resource mutably
/// - no mutable references to the resource exist at the same time
#[inline]
pub(crate) unsafe fn get_non_send_with_ticks(
self,
component_id: ComponentId,
) -> Option<(Ptr<'w>, ComponentTickCells<'w>)> {
// SAFETY:
// - caller ensures there is no `&mut World`
// - caller ensures there are no mutable borrows of this resource
// - caller ensures that we have permission to access this resource
unsafe { self.storages() }
.non_send_resources
.get(component_id)?
.get_with_ticks()
}
// Returns a mutable reference to the underlying world's [`CommandQueue`].
/// # Safety
/// It is the caller's responsibility to ensure that
/// - the [`UnsafeWorldCell`] has permission to access the queue mutably
/// - no mutable references to the queue exist at the same time
pub(crate) unsafe fn get_raw_command_queue(self) -> RawCommandQueue {
self.assert_allows_mutable_access();
// SAFETY:
// - caller ensures there are no existing mutable references
// - caller ensures that we have permission to access the queue
unsafe { (*self.ptr).command_queue.clone() }
}
/// # Safety
/// It is the caller's responsibility to ensure that there are no outstanding
/// references to `last_trigger_id`.
pub(crate) unsafe fn increment_trigger_id(self) {
self.assert_allows_mutable_access();
// SAFETY: Caller ensure there are no outstanding references
unsafe {
(*self.ptr).last_trigger_id = (*self.ptr).last_trigger_id.wrapping_add(1);
}
}
/// Convenience method for accessing the world's default error handler,
///
/// # Safety
/// Must have read access to [`DefaultErrorHandler`].
#[inline]
pub unsafe fn default_error_handler(&self) -> ErrorHandler {
// SAFETY: Upheld by caller
unsafe { self.get_resource::<DefaultErrorHandler>() }
.copied()
.unwrap_or_default()
.0
}
}
impl Debug for UnsafeWorldCell<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
// SAFETY: World's Debug implementation only accesses metadata.
Debug::fmt(unsafe { self.world_metadata() }, f)
}
}
/// An interior-mutable reference to a particular [`Entity`] and all of its components
#[derive(Copy, Clone)]
pub struct UnsafeEntityCell<'w> {
world: UnsafeWorldCell<'w>,
entity: Entity,
location: EntityLocation,
last_run: Tick,
this_run: Tick,
}
impl<'w> UnsafeEntityCell<'w> {
#[inline]
pub(crate) fn new(
world: UnsafeWorldCell<'w>,
entity: Entity,
location: EntityLocation,
last_run: Tick,
this_run: Tick,
) -> Self {
UnsafeEntityCell {
world,
entity,
location,
last_run,
this_run,
}
}
/// Returns the [ID](Entity) of the current entity.
#[inline]
#[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
pub fn id(self) -> Entity {
self.entity
}
/// Gets metadata indicating the location where the current entity is stored.
#[inline]
pub fn location(self) -> EntityLocation {
self.location
}
/// Returns the archetype that the current entity belongs to.
#[inline]
pub fn archetype(self) -> &'w Archetype {
&self.world.archetypes()[self.location.archetype_id]
}
/// Gets the world that the current entity belongs to.
#[inline]
pub fn world(self) -> UnsafeWorldCell<'w> {
self.world
}
/// Returns `true` if the current entity has a component of type `T`.
/// Otherwise, this returns `false`.
///
/// ## Notes
///
/// If you do not know the concrete type of a component, consider using
/// [`Self::contains_id`] or [`Self::contains_type_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/world/error.rs | crates/bevy_ecs/src/world/error.rs | //! Contains error types returned by bevy's schedule.
use alloc::vec::Vec;
use bevy_utils::prelude::DebugName;
use crate::{
component::ComponentId,
entity::{Entity, EntityNotSpawnedError},
schedule::InternedScheduleLabel,
};
/// The error type returned by [`World::try_run_schedule`] if the provided schedule does not exist.
///
/// [`World::try_run_schedule`]: crate::world::World::try_run_schedule
#[derive(thiserror::Error, Debug)]
#[error("The schedule with the label {0:?} was not found.")]
pub struct TryRunScheduleError(pub InternedScheduleLabel);
/// The error type returned by [`World::try_insert_batch`] and [`World::try_insert_batch_if_new`]
/// if any of the provided entities do not exist.
///
/// [`World::try_insert_batch`]: crate::world::World::try_insert_batch
/// [`World::try_insert_batch_if_new`]: crate::world::World::try_insert_batch_if_new
#[derive(thiserror::Error, Debug, Clone)]
#[error("Could not insert bundles of type {bundle_type} into the entities with the following IDs because they do not exist: {entities:?}")]
pub struct TryInsertBatchError {
/// The bundles' type name.
pub bundle_type: DebugName,
/// The IDs of the provided entities that do not exist.
pub entities: Vec<Entity>,
}
/// An error that occurs when a specified [`Entity`] could not be despawned.
#[derive(thiserror::Error, Debug, Clone, Copy)]
#[error("Could not despawn entity: {0}")]
pub struct EntityDespawnError(#[from] pub EntityNotSpawnedError);
/// An error that occurs when dynamically retrieving components from an entity.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
pub enum EntityComponentError {
/// The component with the given [`ComponentId`] does not exist on the entity.
#[error("The component with ID {0:?} does not exist on the entity.")]
MissingComponent(ComponentId),
/// The component with the given [`ComponentId`] was requested mutably more than once.
#[error("The component with ID {0:?} was requested mutably more than once.")]
AliasedMutability(ComponentId),
}
/// An error that occurs when fetching entities mutably from a world.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
pub enum EntityMutableFetchError {
/// The entity is not spawned.
#[error(
"{0}\n
If you were attempting to apply a command to this entity,
and want to handle this error gracefully, consider using `EntityCommands::queue_handled` or `queue_silenced`."
)]
NotSpawned(#[from] EntityNotSpawnedError),
/// The entity with the given ID was requested mutably more than once.
#[error("The entity with ID {0} was requested mutably more than once")]
AliasedMutability(Entity),
}
/// An error that occurs when getting a resource of a given type in a world.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResourceFetchError {
/// The resource has never been initialized or registered with the world.
#[error("The resource has never been initialized or registered with the world. Did you forget to add it using `app.insert_resource` / `app.init_resource`?")]
NotRegistered,
/// The resource with the given [`ComponentId`] does not currently exist in the world.
#[error("The resource with ID {0:?} does not currently exist in the world.")]
DoesNotExist(ComponentId),
/// Cannot get access to the resource with the given [`ComponentId`] in the world as it conflicts with an on going operation.
#[error("Cannot get access to the resource with ID {0:?} in the world as it conflicts with an on going operation.")]
NoResourceAccess(ComponentId),
}
#[cfg(test)]
mod tests {
use crate::{
prelude::*,
system::{command::trigger, RunSystemOnce},
};
// Inspired by https://github.com/bevyengine/bevy/issues/19623
#[test]
fn fixing_panicking_entity_commands() {
#[derive(EntityEvent)]
struct Kill(Entity);
#[derive(EntityEvent)]
struct FollowupEvent(Entity);
fn despawn(kill: On<Kill>, mut commands: Commands) {
commands.entity(kill.event_target()).despawn();
}
fn followup(kill: On<Kill>, mut commands: Commands) {
// When using a simple .trigger() here, this panics because the entity has already been despawned.
// Instead, we need to use `.queue_handled` or `.queue_silenced` to avoid the panic.
commands.queue_silenced(trigger(FollowupEvent(kill.event_target())));
}
let mut world = World::new();
// This test would pass if the order of these statements were swapped,
// even with panicking entity commands
world.add_observer(followup);
world.add_observer(despawn);
// Create an entity to test these observers with
world.spawn_empty();
// Trigger a kill event on the entity
fn kill_everything(mut commands: Commands, query: Query<Entity>) {
for id in query.iter() {
commands.trigger(Kill(id));
}
}
world.run_system_once(kill_everything).unwrap();
}
}
| 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/world/identifier.rs | crates/bevy_ecs/src/world/identifier.rs | use crate::{
change_detection::Tick,
query::FilteredAccessSet,
storage::SparseSetIndex,
system::{ExclusiveSystemParam, ReadOnlySystemParam, SystemMeta, SystemParam},
world::{FromWorld, World},
};
use bevy_platform::sync::atomic::{AtomicUsize, Ordering};
use super::unsafe_world_cell::UnsafeWorldCell;
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
// We use usize here because that is the largest `Atomic` we want to require
/// A unique identifier for a [`World`].
///
/// The trait [`FromWorld`] is implemented for this type, which returns the
/// ID of the world passed to [`FromWorld::from_world`].
// Note that this *is* used by external crates as well as for internal safety checks
pub struct WorldId(usize);
/// The next [`WorldId`].
static MAX_WORLD_ID: AtomicUsize = AtomicUsize::new(0);
impl WorldId {
/// Create a new, unique [`WorldId`]. Returns [`None`] if the supply of unique
/// [`WorldId`]s has been exhausted
///
/// Please note that the [`WorldId`]s created from this method are unique across
/// time - if a given [`WorldId`] is [`Drop`]ped its value still cannot be reused
pub fn new() -> Option<Self> {
MAX_WORLD_ID
// We use `Relaxed` here since this atomic only needs to be consistent with itself
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |val| {
val.checked_add(1)
})
.map(WorldId)
.ok()
}
}
impl FromWorld for WorldId {
#[inline]
fn from_world(world: &mut World) -> Self {
world.id()
}
}
// SAFETY: No world data is accessed.
unsafe impl ReadOnlySystemParam for WorldId {}
// SAFETY: No world data is accessed.
unsafe impl SystemParam for WorldId {
type State = ();
type Item<'world, 'state> = WorldId;
fn init_state(_: &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<'world, 'state>(
_: &'state mut Self::State,
_: &SystemMeta,
world: UnsafeWorldCell<'world>,
_: Tick,
) -> Self::Item<'world, 'state> {
world.id()
}
}
impl ExclusiveSystemParam for WorldId {
type State = WorldId;
type Item<'s> = WorldId;
fn init(world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {
world.id()
}
fn get_param<'s>(state: &'s mut Self::State, _system_meta: &SystemMeta) -> Self::Item<'s> {
*state
}
}
impl SparseSetIndex for WorldId {
#[inline]
fn sparse_set_index(&self) -> usize {
self.0
}
#[inline]
fn get_sparse_set_index(value: usize) -> Self {
Self(value)
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec::Vec;
#[test]
fn world_ids_unique() {
let ids = core::iter::repeat_with(WorldId::new)
.take(50)
.map(Option::unwrap)
.collect::<Vec<_>>();
for (i, &id1) in ids.iter().enumerate() {
// For the first element, i is 0 - so skip 1
for &id2 in ids.iter().skip(i + 1) {
assert_ne!(id1, id2, "WorldIds should not repeat");
}
}
}
#[test]
fn world_id_system_param() {
fn test_system(world_id: WorldId) -> WorldId {
world_id
}
let mut world = World::default();
let system_id = world.register_system(test_system);
let world_id = world.run_system(system_id).unwrap();
assert_eq!(world.id(), world_id);
}
#[test]
fn world_id_exclusive_system_param() {
fn test_system(_world: &mut World, world_id: WorldId) -> WorldId {
world_id
}
let mut world = World::default();
let system_id = world.register_system(test_system);
let world_id = world.run_system(system_id).unwrap();
assert_eq!(world.id(), world_id);
}
// We cannot use this test as-is, as it causes other tests to panic due to using the same atomic variable.
// #[test]
// #[should_panic]
// fn panic_on_overflow() {
// MAX_WORLD_ID.store(usize::MAX - 50, Ordering::Relaxed);
// core::iter::repeat_with(WorldId::new)
// .take(500)
// .for_each(|_| ());
// }
}
| 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/world/mod.rs | crates/bevy_ecs/src/world/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."
)]
//! Defines the [`World`] and APIs for accessing it directly.
pub(crate) mod command_queue;
mod deferred_world;
mod entity_access;
mod entity_fetch;
mod filtered_resource;
mod identifier;
mod spawn_batch;
pub mod error;
#[cfg(feature = "bevy_reflect")]
pub mod reflect;
pub mod unsafe_world_cell;
pub use crate::{
change_detection::{Mut, Ref, CHECK_TICK_THRESHOLD},
world::command_queue::CommandQueue,
};
pub use bevy_ecs_macros::FromWorld;
pub use deferred_world::DeferredWorld;
pub use entity_access::{
ComponentEntry, DynamicComponentFetch, EntityMut, EntityMutExcept, EntityRef, EntityRefExcept,
EntityWorldMut, FilteredEntityMut, FilteredEntityRef, OccupiedComponentEntry,
TryFromFilteredError, UnsafeFilteredEntityMut, VacantComponentEntry,
};
pub use entity_fetch::{EntityFetcher, WorldEntityFetch};
pub use filtered_resource::*;
pub use identifier::WorldId;
pub use spawn_batch::*;
use crate::{
archetype::{ArchetypeId, Archetypes},
bundle::{
Bundle, BundleId, BundleInfo, BundleInserter, BundleSpawner, Bundles, InsertMode,
NoBundleEffect,
},
change_detection::{
CheckChangeTicks, ComponentTicks, ComponentTicksMut, MaybeLocation, MutUntyped, Tick,
},
component::{
Component, ComponentDescriptor, ComponentId, ComponentIds, ComponentInfo, Components,
ComponentsQueuedRegistrator, ComponentsRegistrator, Mutable, RequiredComponents,
RequiredComponentsError,
},
entity::{Entities, Entity, EntityAllocator, EntityNotSpawnedError, SpawnError},
entity_disabling::DefaultQueryFilters,
error::{DefaultErrorHandler, ErrorHandler},
lifecycle::{ComponentHooks, RemovedComponentMessages, ADD, DESPAWN, INSERT, REMOVE, REPLACE},
message::{Message, MessageId, Messages, WriteBatchIds},
observer::Observers,
prelude::{Add, Despawn, Insert, Remove, Replace},
query::{DebugCheckedUnwrap, QueryData, QueryFilter, QueryState},
relationship::RelationshipHookMode,
resource::Resource,
schedule::{Schedule, ScheduleLabel, Schedules},
storage::{ResourceData, Storages},
system::Commands,
world::{
command_queue::RawCommandQueue,
error::{
EntityDespawnError, EntityMutableFetchError, TryInsertBatchError, TryRunScheduleError,
},
},
};
use alloc::{boxed::Box, vec::Vec};
use bevy_platform::sync::atomic::{AtomicU32, Ordering};
use bevy_ptr::{move_as_ptr, MovingPtr, OwningPtr, Ptr};
use bevy_utils::prelude::DebugName;
use core::{any::TypeId, fmt};
use log::warn;
use unsafe_world_cell::UnsafeWorldCell;
/// Stores and exposes operations on [entities](Entity), [components](Component), resources,
/// and their associated metadata.
///
/// Each [`Entity`] has a set of unique components, based on their type.
/// Entity components can be created, updated, removed, and queried using a given [`World`].
///
/// For complex access patterns involving [`SystemParam`](crate::system::SystemParam),
/// consider using [`SystemState`](crate::system::SystemState).
///
/// To mutate different parts of the world simultaneously,
/// use [`World::resource_scope`] or [`SystemState`](crate::system::SystemState).
///
/// ## Resources
///
/// Worlds can also store [`Resource`]s,
/// which are unique instances of a given type that don't belong to a specific Entity.
/// There are also *non send resources*, which can only be accessed on the main thread.
/// See [`Resource`] for usage.
pub struct World {
id: WorldId,
pub(crate) entities: Entities,
pub(crate) allocator: EntityAllocator,
pub(crate) components: Components,
pub(crate) component_ids: ComponentIds,
pub(crate) archetypes: Archetypes,
pub(crate) storages: Storages,
pub(crate) bundles: Bundles,
pub(crate) observers: Observers,
pub(crate) removed_components: RemovedComponentMessages,
pub(crate) change_tick: AtomicU32,
pub(crate) last_change_tick: Tick,
pub(crate) last_check_tick: Tick,
pub(crate) last_trigger_id: u32,
pub(crate) command_queue: RawCommandQueue,
}
impl Default for World {
fn default() -> Self {
let mut world = Self {
id: WorldId::new().expect("More `bevy` `World`s have been created than is supported"),
entities: Entities::new(),
allocator: EntityAllocator::default(),
components: Default::default(),
archetypes: Archetypes::new(),
storages: Default::default(),
bundles: Default::default(),
observers: Observers::default(),
removed_components: Default::default(),
// Default value is `1`, and `last_change_tick`s default to `0`, such that changes
// are detected on first system runs and for direct world queries.
change_tick: AtomicU32::new(1),
last_change_tick: Tick::new(0),
last_check_tick: Tick::new(0),
last_trigger_id: 0,
command_queue: RawCommandQueue::new(),
component_ids: ComponentIds::default(),
};
world.bootstrap();
world
}
}
impl Drop for World {
fn drop(&mut self) {
// SAFETY: Not passing a pointer so the argument is always valid
unsafe { self.command_queue.apply_or_drop_queued(None) };
// SAFETY: Pointers in internal command queue are only invalidated here
drop(unsafe { Box::from_raw(self.command_queue.bytes.as_ptr()) });
// SAFETY: Pointers in internal command queue are only invalidated here
drop(unsafe { Box::from_raw(self.command_queue.cursor.as_ptr()) });
// SAFETY: Pointers in internal command queue are only invalidated here
drop(unsafe { Box::from_raw(self.command_queue.panic_recovery.as_ptr()) });
}
}
impl World {
/// This performs initialization that _must_ happen for every [`World`] immediately upon creation (such as claiming specific component ids).
/// This _must_ be run as part of constructing a [`World`], before it is returned to the caller.
#[inline]
fn bootstrap(&mut self) {
// The order that we register these events is vital to ensure that the constants are correct!
let on_add = self.register_event_key::<Add>();
assert_eq!(ADD, on_add);
let on_insert = self.register_event_key::<Insert>();
assert_eq!(INSERT, on_insert);
let on_replace = self.register_event_key::<Replace>();
assert_eq!(REPLACE, on_replace);
let on_remove = self.register_event_key::<Remove>();
assert_eq!(REMOVE, on_remove);
let on_despawn = self.register_event_key::<Despawn>();
assert_eq!(DESPAWN, on_despawn);
// This sets up `Disabled` as a disabling component, via the FromWorld impl
self.init_resource::<DefaultQueryFilters>();
}
/// Creates a new empty [`World`].
///
/// # Panics
///
/// If [`usize::MAX`] [`World`]s have been created.
/// This guarantee allows System Parameters to safely uniquely identify a [`World`],
/// since its [`WorldId`] is unique
#[inline]
pub fn new() -> World {
World::default()
}
/// Retrieves this [`World`]'s unique ID
#[inline]
pub fn id(&self) -> WorldId {
self.id
}
/// Creates a new [`UnsafeWorldCell`] view with complete read+write access.
#[inline]
pub fn as_unsafe_world_cell(&mut self) -> UnsafeWorldCell<'_> {
UnsafeWorldCell::new_mutable(self)
}
/// Creates a new [`UnsafeWorldCell`] view with only read access to everything.
#[inline]
pub fn as_unsafe_world_cell_readonly(&self) -> UnsafeWorldCell<'_> {
UnsafeWorldCell::new_readonly(self)
}
/// Retrieves this world's [`Entities`] collection.
#[inline]
pub fn entities(&self) -> &Entities {
&self.entities
}
/// Retrieves this world's [`EntityAllocator`] collection.
#[inline]
pub fn entities_allocator(&self) -> &EntityAllocator {
&self.allocator
}
/// Retrieves this world's [`EntityAllocator`] collection mutably.
#[inline]
pub fn entities_allocator_mut(&mut self) -> &mut EntityAllocator {
&mut self.allocator
}
/// Retrieves this world's [`Entities`] collection mutably.
///
/// # Safety
/// Mutable reference must not be used to put the [`Entities`] data
/// in an invalid state for this [`World`]
#[inline]
pub unsafe fn entities_mut(&mut self) -> &mut Entities {
&mut self.entities
}
/// Retrieves the number of [`Entities`] in the world.
///
/// This is helpful as a diagnostic, but it can also be used effectively in tests.
#[inline]
pub fn entity_count(&self) -> u32 {
self.entities.count_spawned()
}
/// Retrieves this world's [`Archetypes`] collection.
#[inline]
pub fn archetypes(&self) -> &Archetypes {
&self.archetypes
}
/// Retrieves this world's [`Components`] collection.
#[inline]
pub fn components(&self) -> &Components {
&self.components
}
/// Prepares a [`ComponentsQueuedRegistrator`] for the world.
/// **NOTE:** [`ComponentsQueuedRegistrator`] is easily misused.
/// See its docs for important notes on when and how it should be used.
#[inline]
pub fn components_queue(&self) -> ComponentsQueuedRegistrator<'_> {
// SAFETY: These are from the same world.
unsafe { ComponentsQueuedRegistrator::new(&self.components, &self.component_ids) }
}
/// Prepares a [`ComponentsRegistrator`] for the world.
#[inline]
pub fn components_registrator(&mut self) -> ComponentsRegistrator<'_> {
// SAFETY: These are from the same world.
unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) }
}
/// Retrieves this world's [`Storages`] collection.
#[inline]
pub fn storages(&self) -> &Storages {
&self.storages
}
/// Retrieves this world's [`Bundles`] collection.
#[inline]
pub fn bundles(&self) -> &Bundles {
&self.bundles
}
/// Retrieves this world's [`RemovedComponentMessages`] collection
#[inline]
pub fn removed_components(&self) -> &RemovedComponentMessages {
&self.removed_components
}
/// Retrieves this world's [`Observers`] list
#[inline]
pub fn observers(&self) -> &Observers {
&self.observers
}
/// Creates a new [`Commands`] instance that writes to the world's command queue
/// Use [`World::flush`] to apply all queued commands
#[inline]
pub fn commands(&mut self) -> Commands<'_, '_> {
// SAFETY: command_queue is stored on world and always valid while the world exists
unsafe {
Commands::new_raw_from_entities(
self.command_queue.clone(),
&self.allocator,
&self.entities,
)
}
}
/// Registers a new [`Component`] type and returns the [`ComponentId`] created for it.
///
/// # Usage Notes
/// In most cases, you don't need to call this method directly since component registration
/// happens automatically during system initialization.
pub fn register_component<T: Component>(&mut self) -> ComponentId {
self.components_registrator().register_component::<T>()
}
/// Registers a component type as "disabling",
/// using [default query filters](DefaultQueryFilters) to exclude entities with the component from queries.
pub fn register_disabling_component<C: Component>(&mut self) {
let component_id = self.register_component::<C>();
let mut dqf = self.resource_mut::<DefaultQueryFilters>();
dqf.register_disabling_component(component_id);
}
/// Returns a mutable reference to the [`ComponentHooks`] for a [`Component`] type.
///
/// Will panic if `T` exists in any archetypes.
#[must_use]
pub fn register_component_hooks<T: Component>(&mut self) -> &mut ComponentHooks {
let index = self.register_component::<T>();
assert!(!self.archetypes.archetypes.iter().any(|a| a.contains(index)), "Components hooks cannot be modified if the component already exists in an archetype, use register_component if {} may already be in use", core::any::type_name::<T>());
// SAFETY: We just created this component
unsafe { self.components.get_hooks_mut(index).debug_checked_unwrap() }
}
/// Returns a mutable reference to the [`ComponentHooks`] for a [`Component`] with the given id if it exists.
///
/// Will panic if `id` exists in any archetypes.
pub fn register_component_hooks_by_id(
&mut self,
id: ComponentId,
) -> Option<&mut ComponentHooks> {
assert!(!self.archetypes.archetypes.iter().any(|a| a.contains(id)), "Components hooks cannot be modified if the component already exists in an archetype, use register_component if the component with id {id:?} may already be in use");
self.components.get_hooks_mut(id)
}
/// Registers the given component `R` as a [required component] for `T`.
///
/// When `T` is added to an entity, `R` and its own required components will also be added
/// if `R` was not already provided. The [`Default`] `constructor` will be used for the creation of `R`.
/// If a custom constructor is desired, use [`World::register_required_components_with`] instead.
///
/// For the non-panicking version, see [`World::try_register_required_components`].
///
/// Note that requirements must currently be registered before `T` is inserted into the world
/// for the first time. This limitation may be fixed in the future.
///
/// [required component]: Component#required-components
///
/// # Panics
///
/// Panics if `R` is already a directly required component for `T`, or if `T` has ever been added
/// on an entity before the registration.
///
/// Indirect requirements through other components are allowed. In those cases, any existing requirements
/// will only be overwritten if the new requirement is more specific.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// struct A;
///
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
/// struct B(usize);
///
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
/// struct C(u32);
///
/// # let mut world = World::default();
/// // Register B as required by A and C as required by B.
/// world.register_required_components::<A, B>();
/// world.register_required_components::<B, C>();
///
/// // This will implicitly also insert B and C with their Default constructors.
/// let id = world.spawn(A).id();
/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
/// ```
pub fn register_required_components<T: Component, R: Component + Default>(&mut self) {
self.try_register_required_components::<T, R>().unwrap();
}
/// Registers the given component `R` as a [required component] for `T`.
///
/// When `T` is added to an entity, `R` and its own required components will also be added
/// if `R` was not already provided. The given `constructor` will be used for the creation of `R`.
/// If a [`Default`] constructor is desired, use [`World::register_required_components`] instead.
///
/// For the non-panicking version, see [`World::try_register_required_components_with`].
///
/// Note that requirements must currently be registered before `T` is inserted into the world
/// for the first time. This limitation may be fixed in the future.
///
/// [required component]: Component#required-components
///
/// # Panics
///
/// Panics if `R` is already a directly required component for `T`, or if `T` has ever been added
/// on an entity before the registration.
///
/// Indirect requirements through other components are allowed. In those cases, any existing requirements
/// will only be overwritten if the new requirement is more specific.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// struct A;
///
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
/// struct B(usize);
///
/// #[derive(Component, PartialEq, Eq, Debug)]
/// struct C(u32);
///
/// # let mut world = World::default();
/// // Register B and C as required by A and C as required by B.
/// // A requiring C directly will overwrite the indirect requirement through B.
/// world.register_required_components::<A, B>();
/// world.register_required_components_with::<B, C>(|| C(1));
/// world.register_required_components_with::<A, C>(|| C(2));
///
/// // This will implicitly also insert B with its Default constructor and C
/// // with the custom constructor defined by A.
/// let id = world.spawn(A).id();
/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
/// assert_eq!(&C(2), world.entity(id).get::<C>().unwrap());
/// ```
pub fn register_required_components_with<T: Component, R: Component>(
&mut self,
constructor: fn() -> R,
) {
self.try_register_required_components_with::<T, R>(constructor)
.unwrap();
}
/// Tries to register the given component `R` as a [required component] for `T`.
///
/// When `T` is added to an entity, `R` and its own required components will also be added
/// if `R` was not already provided. The [`Default`] `constructor` will be used for the creation of `R`.
/// If a custom constructor is desired, use [`World::register_required_components_with`] instead.
///
/// For the panicking version, see [`World::register_required_components`].
///
/// Note that requirements must currently be registered before `T` is inserted into the world
/// for the first time. This limitation may be fixed in the future.
///
/// [required component]: Component#required-components
///
/// # Errors
///
/// Returns a [`RequiredComponentsError`] if `R` is already a directly required component for `T`, or if `T` has ever been added
/// on an entity before the registration.
///
/// Indirect requirements through other components are allowed. In those cases, any existing requirements
/// will only be overwritten if the new requirement is more specific.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// struct A;
///
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
/// struct B(usize);
///
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
/// struct C(u32);
///
/// # let mut world = World::default();
/// // Register B as required by A and C as required by B.
/// world.register_required_components::<A, B>();
/// world.register_required_components::<B, C>();
///
/// // Duplicate registration! This will fail.
/// assert!(world.try_register_required_components::<A, B>().is_err());
///
/// // This will implicitly also insert B and C with their Default constructors.
/// let id = world.spawn(A).id();
/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
/// ```
pub fn try_register_required_components<T: Component, R: Component + Default>(
&mut self,
) -> Result<(), RequiredComponentsError> {
self.try_register_required_components_with::<T, R>(R::default)
}
/// Tries to register the given component `R` as a [required component] for `T`.
///
/// When `T` is added to an entity, `R` and its own required components will also be added
/// if `R` was not already provided. The given `constructor` will be used for the creation of `R`.
/// If a [`Default`] constructor is desired, use [`World::register_required_components`] instead.
///
/// For the panicking version, see [`World::register_required_components_with`].
///
/// Note that requirements must currently be registered before `T` is inserted into the world
/// for the first time. This limitation may be fixed in the future.
///
/// [required component]: Component#required-components
///
/// # Errors
///
/// Returns a [`RequiredComponentsError`] if `R` is already a directly required component for `T`, or if `T` has ever been added
/// on an entity before the registration.
///
/// Indirect requirements through other components are allowed. In those cases, any existing requirements
/// will only be overwritten if the new requirement is more specific.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// struct A;
///
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
/// struct B(usize);
///
/// #[derive(Component, PartialEq, Eq, Debug)]
/// struct C(u32);
///
/// # let mut world = World::default();
/// // Register B and C as required by A and C as required by B.
/// // A requiring C directly will overwrite the indirect requirement through B.
/// world.register_required_components::<A, B>();
/// world.register_required_components_with::<B, C>(|| C(1));
/// world.register_required_components_with::<A, C>(|| C(2));
///
/// // Duplicate registration! Even if the constructors were different, this would fail.
/// assert!(world.try_register_required_components_with::<B, C>(|| C(1)).is_err());
///
/// // This will implicitly also insert B with its Default constructor and C
/// // with the custom constructor defined by A.
/// let id = world.spawn(A).id();
/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
/// assert_eq!(&C(2), world.entity(id).get::<C>().unwrap());
/// ```
pub fn try_register_required_components_with<T: Component, R: Component>(
&mut self,
constructor: fn() -> R,
) -> Result<(), RequiredComponentsError> {
let requiree = self.register_component::<T>();
// TODO: Remove this panic and update archetype edges accordingly when required components are added
if self.archetypes().component_index().contains_key(&requiree) {
return Err(RequiredComponentsError::ArchetypeExists(requiree));
}
let required = self.register_component::<R>();
// SAFETY: We just created the `required` and `requiree` components.
unsafe {
self.components
.register_required_components::<R>(requiree, required, constructor)
}
}
/// Retrieves the [required components](RequiredComponents) for the given component type, if it exists.
pub fn get_required_components<C: Component>(&self) -> Option<&RequiredComponents> {
let id = self.components().valid_component_id::<C>()?;
let component_info = self.components().get_info(id)?;
Some(component_info.required_components())
}
/// Retrieves the [required components](RequiredComponents) for the component of the given [`ComponentId`], if it exists.
pub fn get_required_components_by_id(&self, id: ComponentId) -> Option<&RequiredComponents> {
let component_info = self.components().get_info(id)?;
Some(component_info.required_components())
}
/// Registers a new [`Component`] type and returns the [`ComponentId`] created for it.
///
/// This method differs from [`World::register_component`] in that it uses a [`ComponentDescriptor`]
/// to register the new component type instead of statically available type information. This
/// enables the dynamic registration of new component definitions at runtime for advanced use cases.
///
/// While the option to register a component from a descriptor is useful in type-erased
/// contexts, the standard [`World::register_component`] function should always be used instead
/// when type information is available at compile time.
pub fn register_component_with_descriptor(
&mut self,
descriptor: ComponentDescriptor,
) -> ComponentId {
self.components_registrator()
.register_component_with_descriptor(descriptor)
}
/// Returns the [`ComponentId`] of the given [`Component`] type `T`.
///
/// The returned `ComponentId` is specific to the `World` instance
/// it was retrieved from and should not be used with another `World` instance.
///
/// Returns [`None`] if the `Component` type has not yet been initialized within
/// the `World` using [`World::register_component`].
///
/// ```
/// use bevy_ecs::prelude::*;
///
/// let mut world = World::new();
///
/// #[derive(Component)]
/// struct ComponentA;
///
/// let component_a_id = world.register_component::<ComponentA>();
///
/// assert_eq!(component_a_id, world.component_id::<ComponentA>().unwrap())
/// ```
///
/// # See also
///
/// * [`ComponentIdFor`](crate::component::ComponentIdFor)
/// * [`Components::component_id()`]
/// * [`Components::get_id()`]
#[inline]
pub fn component_id<T: Component>(&self) -> Option<ComponentId> {
self.components.component_id::<T>()
}
/// Registers a new [`Resource`] type and returns the [`ComponentId`] created for it.
///
/// The [`Resource`] doesn't have a value in the [`World`], it's only registered. If you want
/// to insert the [`Resource`] in the [`World`], use [`World::init_resource`] or
/// [`World::insert_resource`] instead.
pub fn register_resource<R: Resource>(&mut self) -> ComponentId {
self.components_registrator().register_resource::<R>()
}
/// Returns the [`ComponentId`] of the given [`Resource`] type `T`.
///
/// The returned [`ComponentId`] is specific to the [`World`] instance it was retrieved from
/// and should not be used with another [`World`] instance.
///
/// Returns [`None`] if the [`Resource`] type has not yet been initialized within the
/// [`World`] using [`World::register_resource`], [`World::init_resource`] or [`World::insert_resource`].
pub fn resource_id<T: Resource>(&self) -> Option<ComponentId> {
self.components.get_resource_id(TypeId::of::<T>())
}
/// Returns [`EntityRef`]s that expose read-only operations for the given
/// `entities`. This will panic if any of the given entities do not exist. Use
/// [`World::get_entity`] if you want to check for entity existence instead
/// of implicitly panicking.
///
/// This function supports fetching a single entity or multiple entities:
/// - Pass an [`Entity`] to receive a single [`EntityRef`].
/// - Pass a slice of [`Entity`]s to receive a [`Vec<EntityRef>`].
/// - Pass an array of [`Entity`]s to receive an equally-sized array of [`EntityRef`]s.
///
/// # Panics
///
/// If any of the given `entities` do not exist in the world.
///
/// # Examples
///
/// ## Single [`Entity`]
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// let mut world = World::new();
/// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
///
/// let position = world.entity(entity).get::<Position>().unwrap();
/// assert_eq!(position.x, 0.0);
/// ```
///
/// ## Array of [`Entity`]s
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// let mut world = World::new();
/// let e1 = world.spawn(Position { x: 0.0, y: 0.0 }).id();
/// let e2 = world.spawn(Position { x: 1.0, y: 1.0 }).id();
///
/// let [e1_ref, e2_ref] = world.entity([e1, e2]);
/// let e1_position = e1_ref.get::<Position>().unwrap();
/// assert_eq!(e1_position.x, 0.0);
/// let e2_position = e2_ref.get::<Position>().unwrap();
/// assert_eq!(e2_position.x, 1.0);
/// ```
///
/// ## Slice of [`Entity`]s
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// let mut world = World::new();
/// let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
/// let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
/// let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
///
/// let ids = vec![e1, e2, e3];
/// for eref in world.entity(&ids[..]) {
/// assert_eq!(eref.get::<Position>().unwrap().y, 1.0);
/// }
/// ```
///
/// ## [`EntityHashSet`](crate::entity::EntityHashSet)
///
/// ```
/// # use bevy_ecs::{prelude::*, entity::EntityHashSet};
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// let mut world = World::new();
/// let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
/// let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
/// let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
///
/// let ids = EntityHashSet::from_iter([e1, e2, e3]);
/// for (_id, eref) in world.entity(&ids) {
/// assert_eq!(eref.get::<Position>().unwrap().y, 1.0);
/// }
/// ```
///
/// [`EntityHashSet`]: crate::entity::EntityHashSet
#[inline]
#[track_caller]
pub fn entity<F: WorldEntityFetch>(&self, entities: F) -> F::Ref<'_> {
match self.get_entity(entities) {
Ok(res) => res,
Err(err) => panic!("{err}"),
}
}
/// Returns [`EntityMut`]s that expose read and write operations for the
/// given `entities`. This will panic if any of the given entities do not
/// exist. Use [`World::get_entity_mut`] if you want to check for entity
/// existence instead of implicitly panicking.
///
/// This function supports fetching a single entity or multiple entities:
/// - Pass an [`Entity`] to receive a single [`EntityWorldMut`].
/// - This reference type allows for structural changes to the entity,
/// such as adding or removing components, or despawning the entity.
/// - Pass a slice of [`Entity`]s to receive a [`Vec<EntityMut>`].
/// - Pass an array of [`Entity`]s to receive an equally-sized array of [`EntityMut`]s.
/// - Pass a reference to a [`EntityHashSet`](crate::entity::EntityHashMap) to receive an
/// [`EntityHashMap<EntityMut>`](crate::entity::EntityHashMap).
///
/// In order to perform structural changes on the returned entity reference,
/// such as adding or removing components, or despawning the entity, only a
/// single [`Entity`] can be passed to this function. Allowing multiple
/// entities at the same time with structural access would lead to undefined
/// behavior, so [`EntityMut`] is returned when requesting multiple entities.
///
/// # Panics
///
/// If any of the given `entities` do not exist in the world.
///
/// # Examples
///
/// ## Single [`Entity`]
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// let mut world = World::new();
/// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
///
/// let mut entity_mut = world.entity_mut(entity);
/// let mut position = entity_mut.get_mut::<Position>().unwrap();
/// position.y = 1.0;
/// assert_eq!(position.x, 0.0);
/// entity_mut.despawn();
/// # assert!(world.get_entity_mut(entity).is_err());
/// ```
///
/// ## Array of [`Entity`]s
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// let mut world = World::new();
/// let e1 = world.spawn(Position { x: 0.0, y: 0.0 }).id();
/// let e2 = world.spawn(Position { x: 1.0, y: 1.0 }).id();
///
/// let [mut e1_ref, mut e2_ref] = world.entity_mut([e1, e2]);
/// let mut e1_position = e1_ref.get_mut::<Position>().unwrap();
| 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/world/deferred_world.rs | crates/bevy_ecs/src/world/deferred_world.rs | use core::ops::Deref;
use bevy_utils::prelude::DebugName;
use crate::{
archetype::Archetype,
change_detection::{MaybeLocation, MutUntyped},
component::{ComponentId, Mutable},
entity::Entity,
event::{EntityComponentsTrigger, Event, EventKey, Trigger},
lifecycle::{HookContext, Insert, Replace, INSERT, REPLACE},
message::{Message, MessageId, Messages, WriteBatchIds},
observer::TriggerContext,
prelude::{Component, QueryState},
query::{QueryData, QueryFilter},
relationship::RelationshipHookMode,
resource::Resource,
system::{Commands, Query},
world::{error::EntityMutableFetchError, EntityFetcher, WorldEntityFetch},
};
use super::{unsafe_world_cell::UnsafeWorldCell, Mut, World};
/// A [`World`] reference that disallows structural ECS changes.
/// This includes initializing resources, registering components or spawning entities.
///
/// This means that in order to add entities, for example, you will need to use commands instead of the world directly.
pub struct DeferredWorld<'w> {
// SAFETY: Implementers must not use this reference to make structural changes
world: UnsafeWorldCell<'w>,
}
impl<'w> Deref for DeferredWorld<'w> {
type Target = World;
fn deref(&self) -> &Self::Target {
// SAFETY: Structural changes cannot be made through &World
unsafe { self.world.world() }
}
}
impl<'w> UnsafeWorldCell<'w> {
/// Turn self into a [`DeferredWorld`]
///
/// # Safety
/// Caller must ensure there are no outstanding mutable references to world and no
/// outstanding references to the world's command queue, resource or component data
#[inline]
pub unsafe fn into_deferred(self) -> DeferredWorld<'w> {
DeferredWorld { world: self }
}
}
impl<'w> From<&'w mut World> for DeferredWorld<'w> {
fn from(world: &'w mut World) -> DeferredWorld<'w> {
DeferredWorld {
world: world.as_unsafe_world_cell(),
}
}
}
impl<'w> DeferredWorld<'w> {
/// Reborrow self as a new instance of [`DeferredWorld`]
#[inline]
pub fn reborrow(&mut self) -> DeferredWorld<'_> {
DeferredWorld { world: self.world }
}
/// Creates a [`Commands`] instance that pushes to the world's command queue
#[inline]
pub fn commands(&mut self) -> Commands<'_, '_> {
// SAFETY: &mut self ensure that there are no outstanding accesses to the queue
let command_queue = unsafe { self.world.get_raw_command_queue() };
// SAFETY: command_queue is stored on world and always valid while the world exists
unsafe {
Commands::new_raw_from_entities(
command_queue,
self.world.entities_allocator(),
self.world.entities(),
)
}
}
/// Retrieves a mutable reference to the given `entity`'s [`Component`] of the given type.
/// Returns `None` if the `entity` does not have a [`Component`] of the given type.
#[inline]
pub fn get_mut<T: Component<Mutability = Mutable>>(
&mut self,
entity: Entity,
) -> Option<Mut<'_, T>> {
self.get_entity_mut(entity).ok()?.into_mut()
}
/// Temporarily removes a [`Component`] `T` from the provided [`Entity`] and
/// runs the provided closure on it, returning the result if `T` was available.
/// This will trigger the `Remove` and `Replace` component hooks without
/// causing an archetype move.
///
/// This is most useful with immutable components, where removal and reinsertion
/// is the only way to modify a value.
///
/// If you do not need to ensure the above hooks are triggered, and your component
/// is mutable, prefer using [`get_mut`](DeferredWorld::get_mut).
#[inline]
#[track_caller]
pub(crate) fn modify_component_with_relationship_hook_mode<T: Component, R>(
&mut self,
entity: Entity,
relationship_hook_mode: RelationshipHookMode,
f: impl FnOnce(&mut T) -> R,
) -> Result<Option<R>, EntityMutableFetchError> {
// If the component is not registered, then it doesn't exist on this entity, so no action required.
let Some(component_id) = self.component_id::<T>() else {
return Ok(None);
};
self.modify_component_by_id_with_relationship_hook_mode(
entity,
component_id,
relationship_hook_mode,
move |component| {
// SAFETY: component matches the component_id collected in the above line
let mut component = unsafe { component.with_type::<T>() };
f(&mut component)
},
)
}
/// Temporarily removes a [`Component`] identified by the provided
/// [`ComponentId`] from the provided [`Entity`] and runs the provided
/// closure on it, returning the result if the component was available.
/// This will trigger the `Remove` and `Replace` component hooks without
/// causing an archetype move.
///
/// This is most useful with immutable components, where removal and reinsertion
/// is the only way to modify a value.
///
/// If you do not need to ensure the above hooks are triggered, and your component
/// is mutable, prefer using [`get_mut_by_id`](DeferredWorld::get_mut_by_id).
///
/// You should prefer the typed [`modify_component_with_relationship_hook_mode`](DeferredWorld::modify_component_with_relationship_hook_mode)
/// whenever possible.
#[inline]
#[track_caller]
pub(crate) fn modify_component_by_id_with_relationship_hook_mode<R>(
&mut self,
entity: Entity,
component_id: ComponentId,
relationship_hook_mode: RelationshipHookMode,
f: impl for<'a> FnOnce(MutUntyped<'a>) -> R,
) -> Result<Option<R>, EntityMutableFetchError> {
let entity_cell = self.get_entity_mut(entity)?;
if !entity_cell.contains_id(component_id) {
return Ok(None);
}
let archetype = &raw const *entity_cell.archetype();
// SAFETY:
// - DeferredWorld ensures archetype pointer will remain valid as no
// relocations will occur.
// - component_id exists on this world and this entity
// - REPLACE is able to accept ZST events
unsafe {
let archetype = &*archetype;
self.trigger_on_replace(
archetype,
entity,
[component_id].into_iter(),
MaybeLocation::caller(),
relationship_hook_mode,
);
if archetype.has_replace_observer() {
// SAFETY: the REPLACE event_key corresponds to the Replace event's type
self.trigger_raw(
REPLACE,
&mut Replace { entity },
&mut EntityComponentsTrigger {
components: &[component_id],
},
MaybeLocation::caller(),
);
}
}
let mut entity_cell = self
.get_entity_mut(entity)
.expect("entity access confirmed above");
// SAFETY: we will run the required hooks to simulate removal/replacement.
let mut component = unsafe {
entity_cell
.get_mut_assume_mutable_by_id(component_id)
.expect("component access confirmed above")
};
let result = f(component.reborrow());
// Simulate adding this component by updating the relevant ticks
*component.ticks.added = *component.ticks.changed;
// SAFETY:
// - DeferredWorld ensures archetype pointer will remain valid as no
// relocations will occur.
// - component_id exists on this world and this entity
// - REPLACE is able to accept ZST events
unsafe {
let archetype = &*archetype;
self.trigger_on_insert(
archetype,
entity,
[component_id].into_iter(),
MaybeLocation::caller(),
relationship_hook_mode,
);
if archetype.has_insert_observer() {
// SAFETY: the INSERT event_key corresponds to the Insert event's type
self.trigger_raw(
INSERT,
&mut Insert { entity },
&mut EntityComponentsTrigger {
components: &[component_id],
},
MaybeLocation::caller(),
);
}
}
Ok(Some(result))
}
/// Returns [`EntityMut`]s that expose read and write operations for the
/// given `entities`, returning [`Err`] if any of the given entities do not
/// exist. Instead of immediately unwrapping the value returned from this
/// function, prefer [`World::entity_mut`].
///
/// This function supports fetching a single entity or multiple entities:
/// - Pass an [`Entity`] to receive a single [`EntityMut`].
/// - Pass a slice of [`Entity`]s to receive a [`Vec<EntityMut>`].
/// - Pass an array of [`Entity`]s to receive an equally-sized array of [`EntityMut`]s.
/// - Pass an [`&EntityHashSet`] to receive an [`EntityHashMap<EntityMut>`].
///
/// **As [`DeferredWorld`] does not allow structural changes, all returned
/// references are [`EntityMut`]s, which do not allow structural changes
/// (i.e. adding/removing components or despawning the entity).**
///
/// # Errors
///
/// - Returns [`EntityMutableFetchError::NotSpawned`] if any of the given `entities` do not exist in the world.
/// - Only the first entity found to be missing will be returned.
/// - Returns [`EntityMutableFetchError::AliasedMutability`] if the same entity is requested multiple times.
///
/// # Examples
///
/// For examples, see [`DeferredWorld::entity_mut`].
///
/// [`EntityMut`]: crate::world::EntityMut
/// [`&EntityHashSet`]: crate::entity::EntityHashSet
/// [`EntityHashMap<EntityMut>`]: crate::entity::EntityHashMap
/// [`Vec<EntityMut>`]: alloc::vec::Vec
#[inline]
pub fn get_entity_mut<F: WorldEntityFetch>(
&mut self,
entities: F,
) -> Result<F::DeferredMut<'_>, EntityMutableFetchError> {
let cell = self.as_unsafe_world_cell();
// SAFETY: `&mut self` gives mutable access to the entire world,
// and prevents any other access to the world.
unsafe { entities.fetch_deferred_mut(cell) }
}
/// Returns [`EntityMut`]s that expose read and write operations for the
/// given `entities`. This will panic if any of the given entities do not
/// exist. Use [`DeferredWorld::get_entity_mut`] if you want to check for
/// entity existence instead of implicitly panicking.
///
/// This function supports fetching a single entity or multiple entities:
/// - Pass an [`Entity`] to receive a single [`EntityMut`].
/// - Pass a slice of [`Entity`]s to receive a [`Vec<EntityMut>`].
/// - Pass an array of [`Entity`]s to receive an equally-sized array of [`EntityMut`]s.
/// - Pass an [`&EntityHashSet`] to receive an [`EntityHashMap<EntityMut>`].
///
/// **As [`DeferredWorld`] does not allow structural changes, all returned
/// references are [`EntityMut`]s, which do not allow structural changes
/// (i.e. adding/removing components or despawning the entity).**
///
/// # Panics
///
/// If any of the given `entities` do not exist in the world.
///
/// # Examples
///
/// ## Single [`Entity`]
///
/// ```
/// # use bevy_ecs::{prelude::*, world::DeferredWorld};
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// # let mut world = World::new();
/// # let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
/// let mut world: DeferredWorld = // ...
/// # DeferredWorld::from(&mut world);
///
/// let mut entity_mut = world.entity_mut(entity);
/// let mut position = entity_mut.get_mut::<Position>().unwrap();
/// position.y = 1.0;
/// assert_eq!(position.x, 0.0);
/// ```
///
/// ## Array of [`Entity`]s
///
/// ```
/// # use bevy_ecs::{prelude::*, world::DeferredWorld};
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// # let mut world = World::new();
/// # let e1 = world.spawn(Position { x: 0.0, y: 0.0 }).id();
/// # let e2 = world.spawn(Position { x: 1.0, y: 1.0 }).id();
/// let mut world: DeferredWorld = // ...
/// # DeferredWorld::from(&mut world);
///
/// let [mut e1_ref, mut e2_ref] = world.entity_mut([e1, e2]);
/// let mut e1_position = e1_ref.get_mut::<Position>().unwrap();
/// e1_position.x = 1.0;
/// assert_eq!(e1_position.x, 1.0);
/// let mut e2_position = e2_ref.get_mut::<Position>().unwrap();
/// e2_position.x = 2.0;
/// assert_eq!(e2_position.x, 2.0);
/// ```
///
/// ## Slice of [`Entity`]s
///
/// ```
/// # use bevy_ecs::{prelude::*, world::DeferredWorld};
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// # let mut world = World::new();
/// # let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
/// # let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
/// # let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
/// let mut world: DeferredWorld = // ...
/// # DeferredWorld::from(&mut world);
///
/// let ids = vec![e1, e2, e3];
/// for mut eref in world.entity_mut(&ids[..]) {
/// let mut pos = eref.get_mut::<Position>().unwrap();
/// pos.y = 2.0;
/// assert_eq!(pos.y, 2.0);
/// }
/// ```
///
/// ## [`&EntityHashSet`]
///
/// ```
/// # use bevy_ecs::{prelude::*, entity::EntityHashSet, world::DeferredWorld};
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// # let mut world = World::new();
/// # let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
/// # let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
/// # let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
/// let mut world: DeferredWorld = // ...
/// # DeferredWorld::from(&mut world);
///
/// let ids = EntityHashSet::from_iter([e1, e2, e3]);
/// for (_id, mut eref) in world.entity_mut(&ids) {
/// let mut pos = eref.get_mut::<Position>().unwrap();
/// pos.y = 2.0;
/// assert_eq!(pos.y, 2.0);
/// }
/// ```
///
/// [`EntityMut`]: crate::world::EntityMut
/// [`&EntityHashSet`]: crate::entity::EntityHashSet
/// [`EntityHashMap<EntityMut>`]: crate::entity::EntityHashMap
/// [`Vec<EntityMut>`]: alloc::vec::Vec
#[inline]
pub fn entity_mut<F: WorldEntityFetch>(&mut self, entities: F) -> F::DeferredMut<'_> {
self.get_entity_mut(entities).unwrap()
}
/// Simultaneously provides access to entity data and a command queue, which
/// will be applied when the [`World`] is next flushed.
///
/// This allows using borrowed entity data to construct commands where the
/// borrow checker would otherwise prevent it.
///
/// See [`World::entities_and_commands`] for the non-deferred version.
///
/// # Example
///
/// ```rust
/// # use bevy_ecs::{prelude::*, world::DeferredWorld};
/// #[derive(Component)]
/// struct Targets(Vec<Entity>);
/// #[derive(Component)]
/// struct TargetedBy(Entity);
///
/// # let mut _world = World::new();
/// # let e1 = _world.spawn_empty().id();
/// # let e2 = _world.spawn_empty().id();
/// # let eid = _world.spawn(Targets(vec![e1, e2])).id();
/// let mut world: DeferredWorld = // ...
/// # DeferredWorld::from(&mut _world);
/// let (entities, mut commands) = world.entities_and_commands();
///
/// let entity = entities.get(eid).unwrap();
/// for &target in entity.get::<Targets>().unwrap().0.iter() {
/// commands.entity(target).insert(TargetedBy(eid));
/// }
/// # _world.flush();
/// # assert_eq!(_world.get::<TargetedBy>(e1).unwrap().0, eid);
/// # assert_eq!(_world.get::<TargetedBy>(e2).unwrap().0, eid);
/// ```
pub fn entities_and_commands(&mut self) -> (EntityFetcher<'_>, Commands<'_, '_>) {
let cell = self.as_unsafe_world_cell();
// SAFETY: `&mut self` gives mutable access to the entire world, and prevents simultaneous access.
let fetcher = unsafe { EntityFetcher::new(cell) };
// SAFETY:
// - `&mut self` gives mutable access to the entire world, and prevents simultaneous access.
// - Command queue access does not conflict with entity access.
let raw_queue = unsafe { cell.get_raw_command_queue() };
// SAFETY: `&mut self` ensures the commands does not outlive the world.
let commands = unsafe {
Commands::new_raw_from_entities(raw_queue, cell.entities_allocator(), cell.entities())
};
(fetcher, commands)
}
/// Returns [`Query`] for the given [`QueryState`], which is used to efficiently
/// run queries on the [`World`] by storing and reusing the [`QueryState`].
///
/// # Panics
/// If state is from a different world then self
#[inline]
pub fn query<'s, D: QueryData, F: QueryFilter>(
&mut self,
state: &'s mut QueryState<D, F>,
) -> Query<'_, 's, D, F> {
// SAFETY: We have mutable access to the entire world
unsafe { state.query_unchecked(self.world) }
}
/// Gets a mutable reference to the resource of the given type
///
/// # Panics
///
/// Panics if the resource does not exist.
/// Use [`get_resource_mut`](DeferredWorld::get_resource_mut) instead if you want to handle this case.
#[inline]
#[track_caller]
pub fn resource_mut<R: Resource>(&mut self) -> Mut<'_, R> {
match self.get_resource_mut() {
Some(x) => x,
None => panic!(
"Requested resource {} does not exist in the `World`.
Did you forget to add it using `app.insert_resource` / `app.init_resource`?
Resources are also implicitly added via `app.add_message`,
and can be added by plugins.",
DebugName::type_name::<R>()
),
}
}
/// Gets a mutable reference to the resource of the given type if it exists
#[inline]
pub fn get_resource_mut<R: Resource>(&mut self) -> Option<Mut<'_, R>> {
// SAFETY: &mut self ensure that there are no outstanding accesses to the resource
unsafe { self.world.get_resource_mut() }
}
/// Gets a mutable reference to the non-send resource of the given type, if it exists.
///
/// # Panics
///
/// Panics if the resource does not exist.
/// Use [`get_non_send_resource_mut`](World::get_non_send_resource_mut) instead if you want to handle this case.
///
/// This function will panic if it isn't called from the same thread that the resource was inserted from.
#[inline]
#[track_caller]
pub fn non_send_resource_mut<R: 'static>(&mut self) -> Mut<'_, R> {
match self.get_non_send_resource_mut() {
Some(x) => x,
None => panic!(
"Requested non-send resource {} does not exist in the `World`.
Did you forget to add it using `app.insert_non_send_resource` / `app.init_non_send_resource`?
Non-send resources can also be added by plugins.",
DebugName::type_name::<R>()
),
}
}
/// Gets a mutable reference to the non-send resource of the given type, if it exists.
/// Otherwise returns `None`.
///
/// # Panics
/// This function will panic if it isn't called from the same thread that the resource was inserted from.
#[inline]
pub fn get_non_send_resource_mut<R: 'static>(&mut self) -> Option<Mut<'_, R>> {
// SAFETY: &mut self ensure that there are no outstanding accesses to the resource
unsafe { self.world.get_non_send_resource_mut() }
}
/// Writes a [`Message`].
/// This method returns the [`MessageId`] of the written `message`,
/// or [`None`] if the `message` could not be written.
#[inline]
pub fn write_message<M: Message>(&mut self, message: M) -> Option<MessageId<M>> {
self.write_message_batch(core::iter::once(message))?.next()
}
/// Writes the default value of the [`Message`] of type `E`.
/// This method returns the [`MessageId`] of the written `event`,
/// or [`None`] if the `event` could not be written.
#[inline]
pub fn write_message_default<E: Message + Default>(&mut self) -> Option<MessageId<E>> {
self.write_message(E::default())
}
/// Writes a batch of [`Message`]s from an iterator.
/// This method returns the [IDs](`MessageId`) of the written `events`,
/// or [`None`] if the `event` could not be written.
#[inline]
pub fn write_message_batch<E: Message>(
&mut self,
events: impl IntoIterator<Item = E>,
) -> Option<WriteBatchIds<E>> {
let Some(mut events_resource) = self.get_resource_mut::<Messages<E>>() else {
log::error!(
"Unable to send message `{}`\n\tMessages must be added to the app with `add_message()`\n\thttps://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_message ",
DebugName::type_name::<E>()
);
return None;
};
Some(events_resource.write_batch(events))
}
/// Gets a pointer to the resource with the id [`ComponentId`] if it exists.
/// The returned pointer may be used to modify the resource, as long as the mutable borrow
/// of the [`World`] is still valid.
///
/// **You should prefer to use the typed API [`World::get_resource_mut`] where possible and only
/// use this in cases where the actual types are not known at compile time.**
#[inline]
pub fn get_resource_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
// SAFETY: &mut self ensure that there are no outstanding accesses to the resource
unsafe { self.world.get_resource_mut_by_id(component_id) }
}
/// Gets a `!Send` resource to the resource with the id [`ComponentId`] if it exists.
/// The returned pointer may be used to modify the resource, as long as the mutable borrow
/// of the [`World`] is still valid.
///
/// **You should prefer to use the typed API [`World::get_resource_mut`] where possible and only
/// use this in cases where the actual types are not known at compile time.**
///
/// # Panics
/// This function will panic if it isn't called from the same thread that the resource was inserted from.
#[inline]
pub fn get_non_send_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
// SAFETY: &mut self ensure that there are no outstanding accesses to the resource
unsafe { self.world.get_non_send_resource_mut_by_id(component_id) }
}
/// Retrieves a mutable untyped reference to the given `entity`'s [`Component`] of the given [`ComponentId`].
/// Returns `None` if the `entity` does not have a [`Component`] of the given type.
///
/// **You should prefer to use the typed API [`World::get_mut`] where possible and only
/// use this in cases where the actual types are not known at compile time.**
#[inline]
pub fn get_mut_by_id(
&mut self,
entity: Entity,
component_id: ComponentId,
) -> Option<MutUntyped<'_>> {
self.get_entity_mut(entity)
.ok()?
.into_mut_by_id(component_id)
.ok()
}
/// Triggers all `on_add` hooks for [`ComponentId`] in target.
///
/// # Safety
/// Caller must ensure [`ComponentId`] in target exist in self.
#[inline]
pub(crate) unsafe fn trigger_on_add(
&mut self,
archetype: &Archetype,
entity: Entity,
targets: impl Iterator<Item = ComponentId>,
caller: MaybeLocation,
) {
if archetype.has_add_hook() {
for component_id in targets {
// SAFETY: Caller ensures that these components exist
let hooks = unsafe { self.components().get_info_unchecked(component_id) }.hooks();
if let Some(hook) = hooks.on_add {
hook(
DeferredWorld { world: self.world },
HookContext {
entity,
component_id,
caller,
relationship_hook_mode: RelationshipHookMode::Run,
},
);
}
}
}
}
/// Triggers all `on_insert` hooks for [`ComponentId`] in target.
///
/// # Safety
/// Caller must ensure [`ComponentId`] in target exist in self.
#[inline]
pub(crate) unsafe fn trigger_on_insert(
&mut self,
archetype: &Archetype,
entity: Entity,
targets: impl Iterator<Item = ComponentId>,
caller: MaybeLocation,
relationship_hook_mode: RelationshipHookMode,
) {
if archetype.has_insert_hook() {
for component_id in targets {
// SAFETY: Caller ensures that these components exist
let hooks = unsafe { self.components().get_info_unchecked(component_id) }.hooks();
if let Some(hook) = hooks.on_insert {
hook(
DeferredWorld { world: self.world },
HookContext {
entity,
component_id,
caller,
relationship_hook_mode,
},
);
}
}
}
}
/// Triggers all `on_replace` hooks for [`ComponentId`] in target.
///
/// # Safety
/// Caller must ensure [`ComponentId`] in target exist in self.
#[inline]
pub(crate) unsafe fn trigger_on_replace(
&mut self,
archetype: &Archetype,
entity: Entity,
targets: impl Iterator<Item = ComponentId>,
caller: MaybeLocation,
relationship_hook_mode: RelationshipHookMode,
) {
if archetype.has_replace_hook() {
for component_id in targets {
// SAFETY: Caller ensures that these components exist
let hooks = unsafe { self.components().get_info_unchecked(component_id) }.hooks();
if let Some(hook) = hooks.on_replace {
hook(
DeferredWorld { world: self.world },
HookContext {
entity,
component_id,
caller,
relationship_hook_mode,
},
);
}
}
}
}
/// Triggers all `on_remove` hooks for [`ComponentId`] in target.
///
/// # Safety
/// Caller must ensure [`ComponentId`] in target exist in self.
#[inline]
pub(crate) unsafe fn trigger_on_remove(
&mut self,
archetype: &Archetype,
entity: Entity,
targets: impl Iterator<Item = ComponentId>,
caller: MaybeLocation,
) {
if archetype.has_remove_hook() {
for component_id in targets {
// SAFETY: Caller ensures that these components exist
let hooks = unsafe { self.components().get_info_unchecked(component_id) }.hooks();
if let Some(hook) = hooks.on_remove {
hook(
DeferredWorld { world: self.world },
HookContext {
entity,
component_id,
caller,
relationship_hook_mode: RelationshipHookMode::Run,
},
);
}
}
}
}
/// Triggers all `on_despawn` hooks for [`ComponentId`] in target.
///
/// # Safety
/// Caller must ensure [`ComponentId`] in target exist in self.
#[inline]
pub(crate) unsafe fn trigger_on_despawn(
&mut self,
archetype: &Archetype,
entity: Entity,
targets: impl Iterator<Item = ComponentId>,
caller: MaybeLocation,
) {
if archetype.has_despawn_hook() {
for component_id in targets {
// SAFETY: Caller ensures that these components exist
let hooks = unsafe { self.components().get_info_unchecked(component_id) }.hooks();
if let Some(hook) = hooks.on_despawn {
hook(
DeferredWorld { world: self.world },
HookContext {
entity,
component_id,
caller,
relationship_hook_mode: RelationshipHookMode::Run,
},
);
}
}
}
}
/// Triggers all `event` observers for the given `targets`
///
/// # Safety
/// - Caller must ensure `E` is accessible as the type represented by `event_key`
#[inline]
pub unsafe fn trigger_raw<'a, E: Event>(
&mut self,
event_key: EventKey,
event: &mut E,
trigger: &mut E::Trigger<'a>,
caller: MaybeLocation,
) {
// SAFETY: You cannot get a mutable reference to `observers` from `DeferredWorld`
let (mut world, observers) = unsafe {
let world = self.as_unsafe_world_cell();
let observers = world.observers();
let Some(observers) = observers.try_get_observers(event_key) else {
return;
};
// SAFETY: The only outstanding reference to world is `observers`
(world.into_deferred(), observers)
};
let context = TriggerContext { event_key, caller };
// SAFETY:
// - `observers` comes from `world`, and corresponds to the `event_key`, as it was looked up above
// - trigger_context contains the correct event_key for `event`, as enforced by the call to `trigger_raw`
// - This method is being called for an `event` whose `Event::Trigger` matches, as the input trigger is E::Trigger.
unsafe {
trigger.trigger(world.reborrow(), observers, &context, event);
}
}
/// Sends a global [`Event`] without any targets.
///
/// This will run any [`Observer`] of the given [`Event`] that isn't scoped to specific targets.
///
/// [`Observer`]: crate::observer::Observer
pub fn trigger<'a>(&mut self, event: impl Event<Trigger<'a>: Default>) {
self.commands().trigger(event);
}
/// Gets an [`UnsafeWorldCell`] containing the underlying world.
///
/// # Safety
/// - must only be used to make non-structural ECS changes
#[inline]
pub fn as_unsafe_world_cell(&mut self) -> UnsafeWorldCell<'_> {
self.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/world/filtered_resource.rs | crates/bevy_ecs/src/world/filtered_resource.rs | use crate::{
change_detection::{ComponentTicksMut, ComponentTicksRef, Mut, MutUntyped, Ref, Tick},
component::ComponentId,
query::Access,
resource::Resource,
world::{unsafe_world_cell::UnsafeWorldCell, World},
};
use bevy_ptr::Ptr;
use super::error::ResourceFetchError;
/// Provides read-only access to a set of [`Resource`]s defined by the contained [`Access`].
///
/// Use [`FilteredResourcesMut`] if you need mutable access to some resources.
///
/// To be useful as a [`SystemParam`](crate::system::SystemParam),
/// this must be configured using a [`FilteredResourcesParamBuilder`](crate::system::FilteredResourcesParamBuilder)
/// to build the system using a [`SystemParamBuilder`](crate::prelude::SystemParamBuilder).
///
/// # Examples
///
/// ```
/// # use bevy_ecs::{prelude::*, system::*};
/// #
/// # #[derive(Default, Resource)]
/// # struct A;
/// #
/// # #[derive(Default, Resource)]
/// # struct B;
/// #
/// # #[derive(Default, Resource)]
/// # struct C;
/// #
/// # let mut world = World::new();
/// // Use `FilteredResourcesParamBuilder` to declare access to resources.
/// let system = (FilteredResourcesParamBuilder::new(|builder| {
/// builder.add_read::<B>().add_read::<C>();
/// }),)
/// .build_state(&mut world)
/// .build_system(resource_system);
///
/// world.init_resource::<A>();
/// world.init_resource::<C>();
///
/// fn resource_system(res: FilteredResources) {
/// // The resource exists, but we have no access, so we can't read it.
/// assert!(res.get::<A>().is_err());
/// // The resource doesn't exist, so we can't read it.
/// assert!(res.get::<B>().is_err());
/// // The resource exists and we have access, so we can read it.
/// let c = res.get::<C>().unwrap();
/// // The type parameter can be left out if it can be determined from use.
/// let c: Ref<C> = res.get().unwrap();
/// }
/// #
/// # world.run_system_once(system);
/// ```
///
/// This can be used alongside ordinary [`Res`](crate::system::Res) and [`ResMut`](crate::system::ResMut) parameters if they do not conflict.
///
/// ```
/// # use bevy_ecs::{prelude::*, system::*};
/// #
/// # #[derive(Default, Resource)]
/// # struct A;
/// #
/// # #[derive(Default, Resource)]
/// # struct B;
/// #
/// # let mut world = World::new();
/// # world.init_resource::<A>();
/// # world.init_resource::<B>();
/// #
/// let system = (
/// FilteredResourcesParamBuilder::new(|builder| {
/// builder.add_read::<A>();
/// }),
/// ParamBuilder,
/// ParamBuilder,
/// )
/// .build_state(&mut world)
/// .build_system(resource_system);
///
/// // Read access to A does not conflict with read access to A or write access to B.
/// fn resource_system(filtered: FilteredResources, res_a: Res<A>, res_mut_b: ResMut<B>) {
/// let res_a_2: Ref<A> = filtered.get::<A>().unwrap();
/// }
/// #
/// # world.run_system_once(system);
/// ```
///
/// But it will conflict if it tries to read the same resource that another parameter writes.
///
/// ```should_panic
/// # use bevy_ecs::{prelude::*, system::*};
/// #
/// # #[derive(Default, Resource)]
/// # struct A;
/// #
/// # let mut world = World::new();
/// # world.init_resource::<A>();
/// #
/// let system = (
/// FilteredResourcesParamBuilder::new(|builder| {
/// builder.add_read::<A>();
/// }),
/// ParamBuilder,
/// )
/// .build_state(&mut world)
/// .build_system(invalid_resource_system);
///
/// // Read access to A conflicts with write access to A.
/// fn invalid_resource_system(filtered: FilteredResources, res_mut_a: ResMut<A>) { }
/// #
/// # world.run_system_once(system);
/// ```
#[derive(Clone, Copy)]
pub struct FilteredResources<'w, 's> {
world: UnsafeWorldCell<'w>,
access: &'s Access,
last_run: Tick,
this_run: Tick,
}
impl<'w, 's> FilteredResources<'w, 's> {
/// Creates a new [`FilteredResources`].
/// # Safety
/// It is the callers responsibility to ensure that nothing else may access the any resources in the `world` in a way that conflicts with `access`.
pub(crate) unsafe fn new(
world: UnsafeWorldCell<'w>,
access: &'s Access,
last_run: Tick,
this_run: Tick,
) -> Self {
Self {
world,
access,
last_run,
this_run,
}
}
/// Returns a reference to the underlying [`Access`].
pub fn access(&self) -> &Access {
self.access
}
/// Returns `true` if the `FilteredResources` has access to the given resource.
/// Note that [`Self::get()`] may still return `Err` if the resource does not exist.
pub fn has_read<R: Resource>(&self) -> bool {
let component_id = self.world.components().resource_id::<R>();
component_id.is_some_and(|component_id| self.access.has_resource_read(component_id))
}
/// Gets a reference to the resource of the given type if it exists and the `FilteredResources` has access to it.
pub fn get<R: Resource>(&self) -> Result<Ref<'w, R>, ResourceFetchError> {
let component_id = self
.world
.components()
.valid_resource_id::<R>()
.ok_or(ResourceFetchError::NotRegistered)?;
if !self.access.has_resource_read(component_id) {
return Err(ResourceFetchError::NoResourceAccess(component_id));
}
// SAFETY: We have read access to this resource
let (value, ticks) = unsafe { self.world.get_resource_with_ticks(component_id) }
.ok_or(ResourceFetchError::DoesNotExist(component_id))?;
Ok(Ref {
// SAFETY: `component_id` was obtained from the type ID of `R`.
value: unsafe { value.deref() },
// SAFETY: We have read access to the resource, so no mutable reference can exist.
ticks: unsafe {
ComponentTicksRef::from_tick_cells(ticks, self.last_run, self.this_run)
},
})
}
/// Gets a pointer to the resource with the given [`ComponentId`] if it exists and the `FilteredResources` has access to it.
pub fn get_by_id(&self, component_id: ComponentId) -> Result<Ptr<'w>, ResourceFetchError> {
if !self.access.has_resource_read(component_id) {
return Err(ResourceFetchError::NoResourceAccess(component_id));
}
// SAFETY: We have read access to this resource
unsafe { self.world.get_resource_by_id(component_id) }
.ok_or(ResourceFetchError::DoesNotExist(component_id))
}
}
impl<'w, 's> From<FilteredResourcesMut<'w, 's>> for FilteredResources<'w, 's> {
fn from(resources: FilteredResourcesMut<'w, 's>) -> Self {
// SAFETY:
// - `FilteredResourcesMut` guarantees exclusive access to all resources in the new `FilteredResources`.
unsafe {
FilteredResources::new(
resources.world,
resources.access,
resources.last_run,
resources.this_run,
)
}
}
}
impl<'w, 's> From<&'w FilteredResourcesMut<'_, 's>> for FilteredResources<'w, 's> {
fn from(resources: &'w FilteredResourcesMut<'_, 's>) -> Self {
// SAFETY:
// - `FilteredResourcesMut` guarantees exclusive access to all components in the new `FilteredResources`.
unsafe {
FilteredResources::new(
resources.world,
resources.access,
resources.last_run,
resources.this_run,
)
}
}
}
impl<'w> From<&'w World> for FilteredResources<'w, 'static> {
fn from(value: &'w World) -> Self {
const READ_ALL_RESOURCES: &Access = {
const ACCESS: Access = {
let mut access = Access::new();
access.read_all_resources();
access
};
&ACCESS
};
let last_run = value.last_change_tick();
let this_run = value.read_change_tick();
// SAFETY: We have a reference to the entire world, so nothing else can alias with read access to all resources.
unsafe {
Self::new(
value.as_unsafe_world_cell_readonly(),
READ_ALL_RESOURCES,
last_run,
this_run,
)
}
}
}
impl<'w> From<&'w mut World> for FilteredResources<'w, 'static> {
fn from(value: &'w mut World) -> Self {
Self::from(&*value)
}
}
/// Provides mutable access to a set of [`Resource`]s defined by the contained [`Access`].
///
/// Use [`FilteredResources`] if you only need read-only access to resources.
///
/// To be useful as a [`SystemParam`](crate::system::SystemParam),
/// this must be configured using a [`FilteredResourcesMutParamBuilder`](crate::system::FilteredResourcesMutParamBuilder)
/// to build the system using a [`SystemParamBuilder`](crate::prelude::SystemParamBuilder).
///
/// # Examples
///
/// ```
/// # use bevy_ecs::{prelude::*, system::*};
/// #
/// # #[derive(Default, Resource)]
/// # struct A;
/// #
/// # #[derive(Default, Resource)]
/// # struct B;
/// #
/// # #[derive(Default, Resource)]
/// # struct C;
/// #
/// # #[derive(Default, Resource)]
/// # struct D;
/// #
/// # let mut world = World::new();
/// // Use `FilteredResourcesMutParamBuilder` to declare access to resources.
/// let system = (FilteredResourcesMutParamBuilder::new(|builder| {
/// builder.add_write::<B>().add_read::<C>().add_write::<D>();
/// }),)
/// .build_state(&mut world)
/// .build_system(resource_system);
///
/// world.init_resource::<A>();
/// world.init_resource::<C>();
/// world.init_resource::<D>();
///
/// fn resource_system(mut res: FilteredResourcesMut) {
/// // The resource exists, but we have no access, so we can't read it or write it.
/// assert!(res.get::<A>().is_err());
/// assert!(res.get_mut::<A>().is_err());
/// // The resource doesn't exist, so we can't read it or write it.
/// assert!(res.get::<B>().is_err());
/// assert!(res.get_mut::<B>().is_err());
/// // The resource exists and we have read access, so we can read it but not write it.
/// let c = res.get::<C>().unwrap();
/// assert!(res.get_mut::<C>().is_err());
/// // The resource exists and we have write access, so we can read it or write it.
/// let d = res.get::<D>().unwrap();
/// let d = res.get_mut::<D>().unwrap();
/// // The type parameter can be left out if it can be determined from use.
/// let c: Ref<C> = res.get().unwrap();
/// }
/// #
/// # world.run_system_once(system);
/// ```
///
/// This can be used alongside ordinary [`Res`](crate::system::ResMut) and [`ResMut`](crate::system::ResMut) parameters if they do not conflict.
///
/// ```
/// # use bevy_ecs::{prelude::*, system::*};
/// #
/// # #[derive(Default, Resource)]
/// # struct A;
/// #
/// # #[derive(Default, Resource)]
/// # struct B;
/// #
/// # #[derive(Default, Resource)]
/// # struct C;
/// #
/// # let mut world = World::new();
/// # world.init_resource::<A>();
/// # world.init_resource::<B>();
/// # world.init_resource::<C>();
/// #
/// let system = (
/// FilteredResourcesMutParamBuilder::new(|builder| {
/// builder.add_read::<A>().add_write::<B>();
/// }),
/// ParamBuilder,
/// ParamBuilder,
/// )
/// .build_state(&mut world)
/// .build_system(resource_system);
///
/// // Read access to A does not conflict with read access to A or write access to C.
/// // Write access to B does not conflict with access to A or C.
/// fn resource_system(mut filtered: FilteredResourcesMut, res_a: Res<A>, res_mut_c: ResMut<C>) {
/// let res_a_2: Ref<A> = filtered.get::<A>().unwrap();
/// let res_mut_b: Mut<B> = filtered.get_mut::<B>().unwrap();
/// }
/// #
/// # world.run_system_once(system);
/// ```
///
/// But it will conflict if it tries to read the same resource that another parameter writes,
/// or write the same resource that another parameter reads.
///
/// ```should_panic
/// # use bevy_ecs::{prelude::*, system::*};
/// #
/// # #[derive(Default, Resource)]
/// # struct A;
/// #
/// # let mut world = World::new();
/// # world.init_resource::<A>();
/// #
/// let system = (
/// FilteredResourcesMutParamBuilder::new(|builder| {
/// builder.add_write::<A>();
/// }),
/// ParamBuilder,
/// )
/// .build_state(&mut world)
/// .build_system(invalid_resource_system);
///
/// // Read access to A conflicts with write access to A.
/// fn invalid_resource_system(filtered: FilteredResourcesMut, res_a: Res<A>) { }
/// #
/// # world.run_system_once(system);
/// ```
pub struct FilteredResourcesMut<'w, 's> {
world: UnsafeWorldCell<'w>,
access: &'s Access,
last_run: Tick,
this_run: Tick,
}
impl<'w, 's> FilteredResourcesMut<'w, 's> {
/// Creates a new [`FilteredResources`].
/// # Safety
/// It is the callers responsibility to ensure that nothing else may access the any resources in the `world` in a way that conflicts with `access`.
pub(crate) unsafe fn new(
world: UnsafeWorldCell<'w>,
access: &'s Access,
last_run: Tick,
this_run: Tick,
) -> Self {
Self {
world,
access,
last_run,
this_run,
}
}
/// Gets read-only access to all of the resources this `FilteredResourcesMut` can access.
pub fn as_readonly(&self) -> FilteredResources<'_, 's> {
FilteredResources::from(self)
}
/// Returns a new instance with a shorter lifetime.
/// This is useful if you have `&mut FilteredResourcesMut`, but you need `FilteredResourcesMut`.
pub fn reborrow(&mut self) -> FilteredResourcesMut<'_, 's> {
// SAFETY: We have exclusive access to this access for the duration of `'_`, so there cannot be anything else that conflicts.
unsafe { Self::new(self.world, self.access, self.last_run, self.this_run) }
}
/// Returns a reference to the underlying [`Access`].
pub fn access(&self) -> &Access {
self.access
}
/// Returns `true` if the `FilteredResources` has read access to the given resource.
/// Note that [`Self::get()`] may still return `Err` if the resource does not exist.
pub fn has_read<R: Resource>(&self) -> bool {
let component_id = self.world.components().resource_id::<R>();
component_id.is_some_and(|component_id| self.access.has_resource_read(component_id))
}
/// Returns `true` if the `FilteredResources` has write access to the given resource.
/// Note that [`Self::get_mut()`] may still return `Err` if the resource does not exist.
pub fn has_write<R: Resource>(&self) -> bool {
let component_id = self.world.components().resource_id::<R>();
component_id.is_some_and(|component_id| self.access.has_resource_write(component_id))
}
/// Gets a reference to the resource of the given type if it exists and the `FilteredResources` has access to it.
pub fn get<R: Resource>(&self) -> Result<Ref<'_, R>, ResourceFetchError> {
self.as_readonly().get()
}
/// Gets a pointer to the resource with the given [`ComponentId`] if it exists and the `FilteredResources` has access to it.
pub fn get_by_id(&self, component_id: ComponentId) -> Result<Ptr<'_>, ResourceFetchError> {
self.as_readonly().get_by_id(component_id)
}
/// Gets a mutable reference to the resource of the given type if it exists and the `FilteredResources` has access to it.
pub fn get_mut<R: Resource>(&mut self) -> Result<Mut<'_, R>, ResourceFetchError> {
// SAFETY: We have exclusive access to the resources in `access` for `'_`, and we shorten the returned lifetime to that.
unsafe { self.get_mut_unchecked() }
}
/// Gets a mutable pointer to the resource with the given [`ComponentId`] if it exists and the `FilteredResources` has access to it.
pub fn get_mut_by_id(
&mut self,
component_id: ComponentId,
) -> Result<MutUntyped<'_>, ResourceFetchError> {
// SAFETY: We have exclusive access to the resources in `access` for `'_`, and we shorten the returned lifetime to that.
unsafe { self.get_mut_by_id_unchecked(component_id) }
}
/// Consumes self and gets mutable access to resource of the given type with the world `'w` lifetime if it exists and the `FilteredResources` has access to it.
pub fn into_mut<R: Resource>(mut self) -> Result<Mut<'w, R>, ResourceFetchError> {
// SAFETY: This consumes self, so we have exclusive access to the resources in `access` for the entirety of `'w`.
unsafe { self.get_mut_unchecked() }
}
/// Consumes self and gets mutable access to resource with the given [`ComponentId`] with the world `'w` lifetime if it exists and the `FilteredResources` has access to it.
pub fn into_mut_by_id(
mut self,
component_id: ComponentId,
) -> Result<MutUntyped<'w>, ResourceFetchError> {
// SAFETY: This consumes self, so we have exclusive access to the resources in `access` for the entirety of `'w`.
unsafe { self.get_mut_by_id_unchecked(component_id) }
}
/// Gets a mutable pointer to the resource of the given type if it exists and the `FilteredResources` has access to it.
/// # Safety
/// It is the callers responsibility to ensure that there are no conflicting borrows of anything in `access` for the duration of the returned value.
unsafe fn get_mut_unchecked<R: Resource>(&mut self) -> Result<Mut<'w, R>, ResourceFetchError> {
let component_id = self
.world
.components()
.valid_resource_id::<R>()
.ok_or(ResourceFetchError::NotRegistered)?;
// SAFETY: THe caller ensures that there are no conflicting borrows.
unsafe { self.get_mut_by_id_unchecked(component_id) }
// SAFETY: The underlying type of the resource is `R`.
.map(|ptr| unsafe { ptr.with_type::<R>() })
}
/// Gets a mutable pointer to the resource with the given [`ComponentId`] if it exists and the `FilteredResources` has access to it.
/// # Safety
/// It is the callers responsibility to ensure that there are no conflicting borrows of anything in `access` for the duration of the returned value.
unsafe fn get_mut_by_id_unchecked(
&mut self,
component_id: ComponentId,
) -> Result<MutUntyped<'w>, ResourceFetchError> {
if !self.access.has_resource_write(component_id) {
return Err(ResourceFetchError::NoResourceAccess(component_id));
}
// SAFETY: We have read access to this resource
let (value, ticks) = unsafe { self.world.get_resource_with_ticks(component_id) }
.ok_or(ResourceFetchError::DoesNotExist(component_id))?;
Ok(MutUntyped {
// SAFETY: We have exclusive access to the underlying storage.
value: unsafe { value.assert_unique() },
// SAFETY: We have exclusive access to the underlying storage.
ticks: unsafe {
ComponentTicksMut::from_tick_cells(ticks, self.last_run, self.this_run)
},
})
}
}
impl<'w> From<&'w mut World> for FilteredResourcesMut<'w, 'static> {
fn from(value: &'w mut World) -> Self {
const WRITE_ALL_RESOURCES: &Access = {
const ACCESS: Access = {
let mut access = Access::new();
access.write_all_resources();
access
};
&ACCESS
};
let last_run = value.last_change_tick();
let this_run = value.change_tick();
// SAFETY: We have a mutable reference to the entire world, so nothing else can alias with mutable access to all resources.
unsafe {
Self::new(
value.as_unsafe_world_cell_readonly(),
WRITE_ALL_RESOURCES,
last_run,
this_run,
)
}
}
}
/// Builder struct to define the access for a [`FilteredResources`].
///
/// This is passed to a callback in [`FilteredResourcesParamBuilder`](crate::system::FilteredResourcesParamBuilder).
pub struct FilteredResourcesBuilder<'w> {
world: &'w mut World,
access: Access,
}
impl<'w> FilteredResourcesBuilder<'w> {
/// Creates a new builder with no access.
pub fn new(world: &'w mut World) -> Self {
Self {
world,
access: Access::new(),
}
}
/// Returns a reference to the underlying [`Access`].
pub fn access(&self) -> &Access {
&self.access
}
/// Add accesses required to read all resources.
pub fn add_read_all(&mut self) -> &mut Self {
self.access.read_all_resources();
self
}
/// Add accesses required to read the resource of the given type.
pub fn add_read<R: Resource>(&mut self) -> &mut Self {
let component_id = self.world.components_registrator().register_resource::<R>();
self.add_read_by_id(component_id)
}
/// Add accesses required to read the resource with the given [`ComponentId`].
pub fn add_read_by_id(&mut self, component_id: ComponentId) -> &mut Self {
self.access.add_resource_read(component_id);
self
}
/// Create an [`Access`] that represents the accesses of the builder.
pub fn build(self) -> Access {
self.access
}
}
/// Builder struct to define the access for a [`FilteredResourcesMut`].
///
/// This is passed to a callback in [`FilteredResourcesMutParamBuilder`](crate::system::FilteredResourcesMutParamBuilder).
pub struct FilteredResourcesMutBuilder<'w> {
world: &'w mut World,
access: Access,
}
impl<'w> FilteredResourcesMutBuilder<'w> {
/// Creates a new builder with no access.
pub fn new(world: &'w mut World) -> Self {
Self {
world,
access: Access::new(),
}
}
/// Returns a reference to the underlying [`Access`].
pub fn access(&self) -> &Access {
&self.access
}
/// Add accesses required to read all resources.
pub fn add_read_all(&mut self) -> &mut Self {
self.access.read_all_resources();
self
}
/// Add accesses required to read the resource of the given type.
pub fn add_read<R: Resource>(&mut self) -> &mut Self {
let component_id = self.world.components_registrator().register_resource::<R>();
self.add_read_by_id(component_id)
}
/// Add accesses required to read the resource with the given [`ComponentId`].
pub fn add_read_by_id(&mut self, component_id: ComponentId) -> &mut Self {
self.access.add_resource_read(component_id);
self
}
/// Add accesses required to get mutable access to all resources.
pub fn add_write_all(&mut self) -> &mut Self {
self.access.write_all_resources();
self
}
/// Add accesses required to get mutable access to the resource of the given type.
pub fn add_write<R: Resource>(&mut self) -> &mut Self {
let component_id = self.world.components_registrator().register_resource::<R>();
self.add_write_by_id(component_id)
}
/// Add accesses required to get mutable access to the resource with the given [`ComponentId`].
pub fn add_write_by_id(&mut self, component_id: ComponentId) -> &mut Self {
self.access.add_resource_write(component_id);
self
}
/// Create an [`Access`] that represents the accesses of the builder.
pub fn build(self) -> Access {
self.access
}
}
| 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/world/entity_access/world_mut.rs | crates/bevy_ecs/src/world/entity_access/world_mut.rs | use crate::{
archetype::Archetype,
bundle::{
Bundle, BundleFromComponents, BundleInserter, BundleRemover, DynamicBundle, InsertMode,
},
change_detection::{ComponentTicks, MaybeLocation, MutUntyped, Tick},
component::{Component, ComponentId, Components, Mutable, StorageType},
entity::{Entity, EntityCloner, EntityClonerBuilder, EntityLocation, OptIn, OptOut},
event::{EntityComponentsTrigger, EntityEvent},
lifecycle::{Despawn, Remove, Replace, DESPAWN, REMOVE, REPLACE},
observer::Observer,
query::{
has_conflicts, Access, DebugCheckedUnwrap, QueryAccessError, ReadOnlyQueryData,
ReleaseStateQueryData,
},
relationship::RelationshipHookMode,
resource::Resource,
storage::{SparseSets, Table},
system::IntoObserverSystem,
world::{
error::EntityComponentError, unsafe_world_cell::UnsafeEntityCell, ComponentEntry,
DynamicComponentFetch, EntityMut, EntityRef, FilteredEntityMut, FilteredEntityRef, Mut,
OccupiedComponentEntry, Ref, VacantComponentEntry, World,
},
};
use alloc::vec::Vec;
use bevy_ptr::{move_as_ptr, MovingPtr, OwningPtr};
use core::{any::TypeId, marker::PhantomData, mem::MaybeUninit};
/// A mutable reference to a particular [`Entity`], and the entire world.
///
/// This is essentially a performance-optimized `(Entity, &mut World)` tuple,
/// which caches the [`EntityLocation`] to reduce duplicate lookups.
///
/// Since this type provides mutable access to the entire world, only one
/// [`EntityWorldMut`] can exist at a time for a given world.
///
/// See also [`EntityMut`], which allows disjoint mutable access to multiple
/// entities at once. Unlike `EntityMut`, this type allows adding and
/// removing components, and despawning the entity.
pub struct EntityWorldMut<'w> {
world: &'w mut World,
entity: Entity,
location: Option<EntityLocation>,
}
impl<'w> EntityWorldMut<'w> {
#[track_caller]
#[inline(never)]
#[cold]
fn panic_despawned(&self) -> ! {
panic!(
"Entity {} {}",
self.entity,
self.world.entities().get_spawned(self.entity).unwrap_err()
);
}
#[inline(always)]
#[track_caller]
pub(crate) fn assert_not_despawned(&self) {
if self.location.is_none() {
self.panic_despawned()
}
}
#[inline(always)]
fn as_unsafe_entity_cell_readonly(&self) -> UnsafeEntityCell<'_> {
let location = self.location();
let last_change_tick = self.world.last_change_tick;
let change_tick = self.world.read_change_tick();
UnsafeEntityCell::new(
self.world.as_unsafe_world_cell_readonly(),
self.entity,
location,
last_change_tick,
change_tick,
)
}
#[inline(always)]
fn as_unsafe_entity_cell(&mut self) -> UnsafeEntityCell<'_> {
let location = self.location();
let last_change_tick = self.world.last_change_tick;
let change_tick = self.world.change_tick();
UnsafeEntityCell::new(
self.world.as_unsafe_world_cell(),
self.entity,
location,
last_change_tick,
change_tick,
)
}
#[inline(always)]
fn into_unsafe_entity_cell(self) -> UnsafeEntityCell<'w> {
let location = self.location();
let last_change_tick = self.world.last_change_tick;
let change_tick = self.world.change_tick();
UnsafeEntityCell::new(
self.world.as_unsafe_world_cell(),
self.entity,
location,
last_change_tick,
change_tick,
)
}
/// # Safety
///
/// - `entity` must be valid for `world`: the generation should match that of the entity at the same index.
/// - `location` must be sourced from `world`'s `Entities` and must exactly match the location for `entity`
///
/// The above is trivially satisfied if `location` was sourced from `world.entities().get(entity)`.
#[inline]
pub(crate) unsafe fn new(
world: &'w mut World,
entity: Entity,
location: Option<EntityLocation>,
) -> Self {
debug_assert!(world.entities().contains(entity));
debug_assert_eq!(world.entities().get(entity).unwrap(), location);
EntityWorldMut {
world,
entity,
location,
}
}
/// Consumes `self` and returns read-only access to all of the entity's
/// components, with the world `'w` lifetime.
pub fn into_readonly(self) -> EntityRef<'w> {
EntityRef::from(self)
}
/// Gets read-only access to all of the entity's components.
#[inline]
pub fn as_readonly(&self) -> EntityRef<'_> {
EntityRef::from(self)
}
/// Consumes `self` and returns non-structural mutable access to all of the
/// entity's components, with the world `'w` lifetime.
pub fn into_mutable(self) -> EntityMut<'w> {
EntityMut::from(self)
}
/// Gets non-structural mutable access to all of the entity's components.
#[inline]
pub fn as_mutable(&mut self) -> EntityMut<'_> {
EntityMut::from(self)
}
/// Returns the [ID](Entity) of the current entity.
#[inline]
#[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
pub fn id(&self) -> Entity {
self.entity
}
/// Gets metadata indicating the location where the current entity is stored.
#[inline]
pub fn try_location(&self) -> Option<EntityLocation> {
self.location
}
/// Returns if the entity is spawned or not.
#[inline]
pub fn is_spawned(&self) -> bool {
self.try_location().is_some()
}
/// Returns the archetype that the current entity belongs to.
#[inline]
pub fn try_archetype(&self) -> Option<&Archetype> {
self.try_location()
.map(|location| &self.world.archetypes[location.archetype_id])
}
/// Gets metadata indicating the location where the current entity is stored.
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn location(&self) -> EntityLocation {
match self.try_location() {
Some(a) => a,
None => self.panic_despawned(),
}
}
/// Returns the archetype that the current entity belongs to.
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn archetype(&self) -> &Archetype {
match self.try_archetype() {
Some(a) => a,
None => self.panic_despawned(),
}
}
/// Returns `true` if the current entity has a component of type `T`.
/// Otherwise, this returns `false`.
///
/// ## Notes
///
/// If you do not know the concrete type of a component, consider using
/// [`Self::contains_id`] or [`Self::contains_type_id`].
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn contains<T: Component>(&self) -> bool {
self.contains_type_id(TypeId::of::<T>())
}
/// Returns `true` if the current entity has a component identified by `component_id`.
/// Otherwise, this returns false.
///
/// ## Notes
///
/// - If you know the concrete type of the component, you should prefer [`Self::contains`].
/// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
/// [`Self::contains_type_id`].
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn contains_id(&self, component_id: ComponentId) -> bool {
self.as_unsafe_entity_cell_readonly()
.contains_id(component_id)
}
/// Returns `true` if the current entity has a component with the type identified by `type_id`.
/// Otherwise, this returns false.
///
/// ## Notes
///
/// - If you know the concrete type of the component, you should prefer [`Self::contains`].
/// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn contains_type_id(&self, type_id: TypeId) -> bool {
self.as_unsafe_entity_cell_readonly()
.contains_type_id(type_id)
}
/// Gets access to the component of type `T` for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn get<T: Component>(&self) -> Option<&'_ T> {
self.as_readonly().get()
}
/// Returns read-only components for the current entity that match the query `Q`.
///
/// # Panics
///
/// If the entity does not have the components required by the query `Q` or if the entity
/// has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(&self) -> Q::Item<'_, 'static> {
self.as_readonly().components::<Q>()
}
/// Returns read-only components for the current entity that match the query `Q`,
/// or `None` if the entity does not have the components required by the query `Q`.
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn get_components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(
&self,
) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
self.as_readonly().get_components::<Q>()
}
/// Returns components for the current entity that match the query `Q`,
/// or `None` if the entity does not have the components required by the query `Q`.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// #[derive(Component)]
/// struct X(usize);
/// #[derive(Component)]
/// struct Y(usize);
///
/// # let mut world = World::default();
/// let mut entity = world.spawn((X(0), Y(0)));
/// // Get mutable access to two components at once
/// // SAFETY: X and Y are different components
/// let (mut x, mut y) =
/// unsafe { entity.get_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
/// *x = X(1);
/// *y = Y(1);
/// // This would trigger undefined behavior, as the `&mut X`s would alias:
/// // entity.get_components_mut_unchecked::<(&mut X, &mut X)>();
/// ```
///
/// # Safety
/// It is the caller's responsibility to ensure that
/// the `QueryData` does not provide aliasing mutable references to the same component.
///
/// /// # See also
///
/// - [`Self::get_components_mut`] for the safe version that performs aliasing checks
pub unsafe fn get_components_mut_unchecked<Q: ReleaseStateQueryData>(
&mut self,
) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
// SAFETY: Caller the `QueryData` does not provide aliasing mutable references to the same component
unsafe { self.as_mutable().into_components_mut_unchecked::<Q>() }
}
/// Returns components for the current entity that match the query `Q`.
/// In the case of conflicting [`QueryData`](crate::query::QueryData), unregistered components, or missing components,
/// this will return a [`QueryAccessError`]
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// #[derive(Component)]
/// struct X(usize);
/// #[derive(Component)]
/// struct Y(usize);
///
/// # let mut world = World::default();
/// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
/// // Get mutable access to two components at once
/// // SAFETY: X and Y are different components
/// let (mut x, mut y) = entity.get_components_mut::<(&mut X, &mut Y)>().unwrap();
/// ```
///
/// Note that this does a O(n^2) check that the [`QueryData`](crate::query::QueryData) does not conflict. If performance is a
/// consideration you should use [`Self::get_components_mut_unchecked`] instead.
pub fn get_components_mut<Q: ReleaseStateQueryData>(
&mut self,
) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
self.as_mutable().into_components_mut::<Q>()
}
/// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
/// or `None` if the entity does not have the components required by the query `Q`.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// #[derive(Component)]
/// struct X(usize);
/// #[derive(Component)]
/// struct Y(usize);
///
/// # let mut world = World::default();
/// let mut entity = world.spawn((X(0), Y(0)));
/// // Get mutable access to two components at once
/// // SAFETY: X and Y are different components
/// let (mut x, mut y) =
/// unsafe { entity.into_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
/// *x = X(1);
/// *y = Y(1);
/// // This would trigger undefined behavior, as the `&mut X`s would alias:
/// // entity.into_components_mut_unchecked::<(&mut X, &mut X)>();
/// ```
///
/// # Safety
/// It is the caller's responsibility to ensure that
/// the `QueryData` does not provide aliasing mutable references to the same component.
///
/// # See also
///
/// - [`Self::into_components_mut`] for the safe version that performs aliasing checks
pub unsafe fn into_components_mut_unchecked<Q: ReleaseStateQueryData>(
self,
) -> Result<Q::Item<'w, 'static>, QueryAccessError> {
// SAFETY: Caller the `QueryData` does not provide aliasing mutable references to the same component
unsafe { self.into_mutable().into_components_mut_unchecked::<Q>() }
}
/// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
/// or `None` if the entity does not have the components required by the query `Q`.
///
/// The checks for aliasing mutable references may be expensive.
/// If performance is a concern, consider making multiple calls to [`Self::get_mut`].
/// If that is not possible, consider using [`Self::into_components_mut_unchecked`] to skip the checks.
///
/// # Panics
///
/// - If the `QueryData` provides aliasing mutable references to the same component.
/// - If the entity has been despawned while this `EntityWorldMut` is still alive.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// #[derive(Component)]
/// struct X(usize);
/// #[derive(Component)]
/// struct Y(usize);
///
/// # let mut world = World::default();
/// let mut entity = world.spawn((X(0), Y(0)));
/// // Get mutable access to two components at once
/// let (mut x, mut y) = entity.into_components_mut::<(&mut X, &mut Y)>().unwrap();
/// *x = X(1);
/// *y = Y(1);
/// ```
///
/// ```should_panic
/// # use bevy_ecs::prelude::*;
/// #
/// # #[derive(Component)]
/// # struct X(usize);
/// #
/// # let mut world = World::default();
/// let mut entity = world.spawn((X(0)));
/// // This panics, as the `&mut X`s would alias:
/// entity.into_components_mut::<(&mut X, &mut X)>();
/// ```
pub fn into_components_mut<Q: ReleaseStateQueryData>(
self,
) -> Result<Q::Item<'w, 'static>, QueryAccessError> {
has_conflicts::<Q>(self.world.components())?;
// SAFETY: we checked that there were not conflicting components above
unsafe { self.into_mutable().into_components_mut_unchecked::<Q>() }
}
/// Consumes `self` and gets access to the component of type `T` with
/// the world `'w` lifetime for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn into_borrow<T: Component>(self) -> Option<&'w T> {
self.into_readonly().get()
}
/// Gets access to the component of type `T` for the current entity,
/// including change detection information as a [`Ref`].
///
/// Returns `None` if the entity does not have a component of type `T`.
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
self.as_readonly().get_ref()
}
/// Consumes `self` and gets access to the component of type `T`
/// with the world `'w` lifetime for the current entity,
/// including change detection information as a [`Ref`].
///
/// Returns `None` if the entity does not have a component of type `T`.
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn into_ref<T: Component>(self) -> Option<Ref<'w, T>> {
self.into_readonly().get_ref()
}
/// Gets mutable access to the component of type `T` for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn get_mut<T: Component<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, T>> {
self.as_mutable().into_mut()
}
/// Temporarily removes a [`Component`] `T` from this [`Entity`] and runs the
/// provided closure on it, returning the result if `T` was available.
/// This will trigger the `Remove` and `Replace` component hooks without
/// causing an archetype move.
///
/// This is most useful with immutable components, where removal and reinsertion
/// is the only way to modify a value.
///
/// If you do not need to ensure the above hooks are triggered, and your component
/// is mutable, prefer using [`get_mut`](EntityWorldMut::get_mut).
///
/// # Examples
///
/// ```rust
/// # use bevy_ecs::prelude::*;
/// #
/// #[derive(Component, PartialEq, Eq, Debug)]
/// #[component(immutable)]
/// struct Foo(bool);
///
/// # let mut world = World::default();
/// # world.register_component::<Foo>();
/// #
/// # let entity = world.spawn(Foo(false)).id();
/// #
/// # let mut entity = world.entity_mut(entity);
/// #
/// # assert_eq!(entity.get::<Foo>(), Some(&Foo(false)));
/// #
/// entity.modify_component(|foo: &mut Foo| {
/// foo.0 = true;
/// });
/// #
/// # assert_eq!(entity.get::<Foo>(), Some(&Foo(true)));
/// ```
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn modify_component<T: Component, R>(&mut self, f: impl FnOnce(&mut T) -> R) -> Option<R> {
self.assert_not_despawned();
let result = self
.world
.modify_component(self.entity, f)
.expect("entity access must be valid")?;
self.update_location();
Some(result)
}
/// Temporarily removes a [`Component`] `T` from this [`Entity`] and runs the
/// provided closure on it, returning the result if `T` was available.
/// This will trigger the `Remove` and `Replace` component hooks without
/// causing an archetype move.
///
/// This is most useful with immutable components, where removal and reinsertion
/// is the only way to modify a value.
///
/// If you do not need to ensure the above hooks are triggered, and your component
/// is mutable, prefer using [`get_mut`](EntityWorldMut::get_mut).
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn modify_component_by_id<R>(
&mut self,
component_id: ComponentId,
f: impl for<'a> FnOnce(MutUntyped<'a>) -> R,
) -> Option<R> {
self.assert_not_despawned();
let result = self
.world
.modify_component_by_id(self.entity, component_id, f)
.expect("entity access must be valid")?;
self.update_location();
Some(result)
}
/// Gets mutable access to the component of type `T` for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
///
/// # Safety
///
/// - `T` must be a mutable component
#[inline]
pub unsafe fn get_mut_assume_mutable<T: Component>(&mut self) -> Option<Mut<'_, T>> {
self.as_mutable().into_mut_assume_mutable()
}
/// Consumes `self` and gets mutable access to the component of type `T`
/// with the world `'w` lifetime for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn into_mut<T: Component<Mutability = Mutable>>(self) -> Option<Mut<'w, T>> {
// SAFETY: consuming `self` implies exclusive access
unsafe { self.into_unsafe_entity_cell().get_mut() }
}
/// Consumes `self` and gets mutable access to the component of type `T`
/// with the world `'w` lifetime for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
///
/// # Safety
///
/// - `T` must be a mutable component
#[inline]
pub unsafe fn into_mut_assume_mutable<T: Component>(self) -> Option<Mut<'w, T>> {
// SAFETY: consuming `self` implies exclusive access
unsafe { self.into_unsafe_entity_cell().get_mut_assume_mutable() }
}
/// Gets a reference to the resource of the given type
///
/// # Panics
///
/// Panics if the resource does not exist.
/// Use [`get_resource`](EntityWorldMut::get_resource) instead if you want to handle this case.
#[inline]
#[track_caller]
pub fn resource<R: Resource>(&self) -> &R {
self.world.resource::<R>()
}
/// Gets a mutable reference to the resource of the given type
///
/// # Panics
///
/// Panics if the resource does not exist.
/// Use [`get_resource_mut`](World::get_resource_mut) instead if you want to handle this case.
///
/// If you want to instead insert a value if the resource does not exist,
/// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
#[inline]
#[track_caller]
pub fn resource_mut<R: Resource>(&mut self) -> Mut<'_, R> {
self.world.resource_mut::<R>()
}
/// Gets a reference to the resource of the given type if it exists
#[inline]
pub fn get_resource<R: Resource>(&self) -> Option<&R> {
self.world.get_resource()
}
/// Gets a mutable reference to the resource of the given type if it exists
#[inline]
pub fn get_resource_mut<R: Resource>(&mut self) -> Option<Mut<'_, R>> {
self.world.get_resource_mut()
}
/// Temporarily removes the requested resource from the [`World`], runs custom user code,
/// then re-adds the resource before returning.
///
/// # Panics
///
/// Panics if the resource does not exist.
/// Use [`try_resource_scope`](Self::try_resource_scope) instead if you want to handle this case.
///
/// See [`World::resource_scope`] for further details.
#[track_caller]
pub fn resource_scope<R: Resource, U>(
&mut self,
f: impl FnOnce(&mut EntityWorldMut, Mut<R>) -> U,
) -> U {
let id = self.id();
self.world_scope(|world| {
world.resource_scope(|world, res| {
// Acquiring a new EntityWorldMut here and using that instead of `self` is fine because
// the outer `world_scope` will handle updating our location if it gets changed by the user code
let mut this = world.entity_mut(id);
f(&mut this, res)
})
})
}
/// Temporarily removes the requested resource from the [`World`] if it exists, runs custom user code,
/// then re-adds the resource before returning. Returns `None` if the resource does not exist in the [`World`].
///
/// See [`World::try_resource_scope`] for further details.
pub fn try_resource_scope<R: Resource, U>(
&mut self,
f: impl FnOnce(&mut EntityWorldMut, Mut<R>) -> U,
) -> Option<U> {
let id = self.id();
self.world_scope(|world| {
world.try_resource_scope(|world, res| {
// Acquiring a new EntityWorldMut here and using that instead of `self` is fine because
// the outer `world_scope` will handle updating our location if it gets changed by the user code
let mut this = world.entity_mut(id);
f(&mut this, res)
})
})
}
/// Retrieves the change ticks for the given component. This can be useful for implementing change
/// detection in custom runtimes.
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
self.as_readonly().get_change_ticks::<T>()
}
/// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
/// detection in custom runtimes.
///
/// **You should prefer to use the typed API [`EntityWorldMut::get_change_ticks`] where possible and only
/// use this in cases where the actual component types are not known at
/// compile time.**
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
self.as_readonly().get_change_ticks_by_id(component_id)
}
/// Returns untyped read-only reference(s) to component(s) for the
/// current entity, based on the given [`ComponentId`]s.
///
/// **You should prefer to use the typed API [`EntityWorldMut::get`] where
/// possible and only use this in cases where the actual component types
/// are not known at compile time.**
///
/// Unlike [`EntityWorldMut::get`], this returns untyped reference(s) to
/// component(s), and it's the job of the caller to ensure the correct
/// type(s) are dereferenced (if necessary).
///
/// # Errors
///
/// Returns [`EntityComponentError::MissingComponent`] if the entity does
/// not have a component.
///
/// # Examples
///
/// For examples on how to use this method, see [`EntityRef::get_by_id`].
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn get_by_id<F: DynamicComponentFetch>(
&self,
component_ids: F,
) -> Result<F::Ref<'_>, EntityComponentError> {
self.as_readonly().get_by_id(component_ids)
}
/// Consumes `self` and returns untyped read-only reference(s) to
/// component(s) with lifetime `'w` for the current entity, based on the
/// given [`ComponentId`]s.
///
/// **You should prefer to use the typed API [`EntityWorldMut::into_borrow`]
/// where possible and only use this in cases where the actual component
/// types are not known at compile time.**
///
/// Unlike [`EntityWorldMut::into_borrow`], this returns untyped reference(s) to
/// component(s), and it's the job of the caller to ensure the correct
/// type(s) are dereferenced (if necessary).
///
/// # Errors
///
/// Returns [`EntityComponentError::MissingComponent`] if the entity does
/// not have a component.
///
/// # Examples
///
/// For examples on how to use this method, see [`EntityRef::get_by_id`].
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn into_borrow_by_id<F: DynamicComponentFetch>(
self,
component_ids: F,
) -> Result<F::Ref<'w>, EntityComponentError> {
self.into_readonly().get_by_id(component_ids)
}
/// Returns [untyped mutable reference(s)](MutUntyped) to component(s) for
/// the current entity, based on the given [`ComponentId`]s.
///
/// **You should prefer to use the typed API [`EntityWorldMut::get_mut`] where
/// possible and only use this in cases where the actual component types
/// are not known at compile time.**
///
/// Unlike [`EntityWorldMut::get_mut`], this returns untyped reference(s) to
/// component(s), and it's the job of the caller to ensure the correct
/// type(s) are dereferenced (if necessary).
///
/// # Errors
///
/// - Returns [`EntityComponentError::MissingComponent`] if the entity does
/// not have a component.
/// - Returns [`EntityComponentError::AliasedMutability`] if a component
/// is requested multiple times.
///
/// # Examples
///
/// For examples on how to use this method, see [`EntityMut::get_mut_by_id`].
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
#[inline]
pub fn get_mut_by_id<F: DynamicComponentFetch>(
&mut self,
component_ids: F,
) -> Result<F::Mut<'_>, EntityComponentError> {
self.as_mutable().into_mut_by_id(component_ids)
}
/// Returns [untyped mutable reference(s)](MutUntyped) to component(s) for
/// the current entity, based on the given [`ComponentId`]s.
/// Assumes the given [`ComponentId`]s refer to mutable components.
///
/// **You should prefer to use the typed API [`EntityWorldMut::get_mut_assume_mutable`] where
/// possible and only use this in cases where the actual component types
/// are not known at compile time.**
///
/// Unlike [`EntityWorldMut::get_mut_assume_mutable`], this returns untyped reference(s) to
/// component(s), and it's the job of the caller to ensure the correct
/// type(s) are dereferenced (if necessary).
///
/// # Errors
///
/// - Returns [`EntityComponentError::MissingComponent`] if the entity does
/// not have a component.
/// - Returns [`EntityComponentError::AliasedMutability`] if a component
/// is requested multiple times.
///
/// # Panics
///
/// If the entity has been despawned while this `EntityWorldMut` is still alive.
///
/// # Safety
/// It is the callers responsibility to ensure that
/// - the provided [`ComponentId`]s must refer to mutable components.
#[inline]
pub unsafe fn get_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
&mut self,
component_ids: F,
) -> Result<F::Mut<'_>, EntityComponentError> {
// SAFETY: Upheld by caller
unsafe {
self.as_mutable()
.into_mut_assume_mutable_by_id(component_ids)
}
}
/// Consumes `self` and returns [untyped mutable reference(s)](MutUntyped)
/// to component(s) with lifetime `'w` for the current entity, based on the
/// given [`ComponentId`]s.
///
/// **You should prefer to use the typed API [`EntityWorldMut::into_mut`] where
/// possible and only use this in cases where the actual component types
/// are not known at compile time.**
///
/// Unlike [`EntityWorldMut::into_mut`], this returns untyped reference(s) to
/// component(s), and it's the job of the caller to ensure the correct
/// type(s) are dereferenced (if necessary).
///
/// # Errors
///
/// - Returns [`EntityComponentError::MissingComponent`] if the entity does
/// not have a component.
| 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/world/entity_access/entity_ref.rs | crates/bevy_ecs/src/world/entity_access/entity_ref.rs | use crate::{
archetype::Archetype,
change_detection::{ComponentTicks, MaybeLocation, Tick},
component::{Component, ComponentId},
entity::{ContainsEntity, Entity, EntityEquivalent, EntityLocation},
query::{Access, QueryAccessError, ReadOnlyQueryData, ReleaseStateQueryData},
world::{
error::EntityComponentError, unsafe_world_cell::UnsafeEntityCell, DynamicComponentFetch,
FilteredEntityRef, Ref,
},
};
use core::{
any::TypeId,
cmp::Ordering,
hash::{Hash, Hasher},
};
/// A read-only reference to a particular [`Entity`] and all of its components.
///
/// # Examples
///
/// Read-only access disjoint with mutable access.
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Component)] pub struct A;
/// # #[derive(Component)] pub struct B;
/// fn disjoint_system(
/// query1: Query<&mut A>,
/// query2: Query<EntityRef, Without<A>>,
/// ) {
/// // ...
/// }
/// # bevy_ecs::system::assert_is_system(disjoint_system);
/// ```
#[derive(Copy, Clone)]
pub struct EntityRef<'w> {
cell: UnsafeEntityCell<'w>,
}
impl<'w> EntityRef<'w> {
/// # Safety
/// - `cell` must have permission to read every component of the entity.
/// - No mutable accesses to any of the entity's components may exist
/// at the same time as the returned [`EntityRef`].
#[inline]
pub(crate) unsafe fn new(cell: UnsafeEntityCell<'w>) -> Self {
Self { cell }
}
/// Returns the [ID](Entity) of the current entity.
#[inline]
#[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
pub fn id(&self) -> Entity {
self.cell.id()
}
/// Gets metadata indicating the location where the current entity is stored.
#[inline]
pub fn location(&self) -> EntityLocation {
self.cell.location()
}
/// Returns the archetype that the current entity belongs to.
#[inline]
pub fn archetype(&self) -> &Archetype {
self.cell.archetype()
}
/// Returns `true` if the current entity has a component of type `T`.
/// Otherwise, this returns `false`.
///
/// ## Notes
///
/// If you do not know the concrete type of a component, consider using
/// [`Self::contains_id`] or [`Self::contains_type_id`].
#[inline]
pub fn contains<T: Component>(&self) -> bool {
self.contains_type_id(TypeId::of::<T>())
}
/// Returns `true` if the current entity has a component identified by `component_id`.
/// Otherwise, this returns false.
///
/// ## Notes
///
/// - If you know the concrete type of the component, you should prefer [`Self::contains`].
/// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
/// [`Self::contains_type_id`].
#[inline]
pub fn contains_id(&self, component_id: ComponentId) -> bool {
self.cell.contains_id(component_id)
}
/// Returns `true` if the current entity has a component with the type identified by `type_id`.
/// Otherwise, this returns false.
///
/// ## Notes
///
/// - If you know the concrete type of the component, you should prefer [`Self::contains`].
/// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
#[inline]
pub fn contains_type_id(&self, type_id: TypeId) -> bool {
self.cell.contains_type_id(type_id)
}
/// Gets access to the component of type `T` for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
#[inline]
pub fn get<T: Component>(&self) -> Option<&'w T> {
// SAFETY: We have read-only access to all components of this entity.
unsafe { self.cell.get::<T>() }
}
/// Gets access to the component of type `T` for the current entity,
/// including change detection information as a [`Ref`].
///
/// Returns `None` if the entity does not have a component of type `T`.
#[inline]
pub fn get_ref<T: Component>(&self) -> Option<Ref<'w, T>> {
// SAFETY: We have read-only access to all components of this entity.
unsafe { self.cell.get_ref::<T>() }
}
/// Retrieves the change ticks for the given component. This can be useful for implementing change
/// detection in custom runtimes.
#[inline]
pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
// SAFETY: We have read-only access to all components of this entity.
unsafe { self.cell.get_change_ticks::<T>() }
}
/// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
/// detection in custom runtimes.
///
/// **You should prefer to use the typed API [`EntityRef::get_change_ticks`] where possible and only
/// use this in cases where the actual component types are not known at
/// compile time.**
#[inline]
pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
// SAFETY: We have read-only access to all components of this entity.
unsafe { self.cell.get_change_ticks_by_id(component_id) }
}
/// Returns untyped read-only reference(s) to component(s) for the
/// current entity, based on the given [`ComponentId`]s.
///
/// **You should prefer to use the typed API [`EntityRef::get`] where
/// possible and only use this in cases where the actual component types
/// are not known at compile time.**
///
/// Unlike [`EntityRef::get`], this returns untyped reference(s) to
/// component(s), and it's the job of the caller to ensure the correct
/// type(s) are dereferenced (if necessary).
///
/// # Errors
///
/// Returns [`EntityComponentError::MissingComponent`] if the entity does
/// not have a component.
///
/// # Examples
///
/// ## Single [`ComponentId`]
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// # #[derive(Component, PartialEq, Debug)]
/// # pub struct Foo(i32);
/// # let mut world = World::new();
/// let entity = world.spawn(Foo(42)).id();
///
/// // Grab the component ID for `Foo` in whatever way you like.
/// let component_id = world.register_component::<Foo>();
///
/// // Then, get the component by ID.
/// let ptr = world.entity(entity).get_by_id(component_id);
/// # assert_eq!(unsafe { ptr.unwrap().deref::<Foo>() }, &Foo(42));
/// ```
///
/// ## Array of [`ComponentId`]s
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// # #[derive(Component, PartialEq, Debug)]
/// # pub struct X(i32);
/// # #[derive(Component, PartialEq, Debug)]
/// # pub struct Y(i32);
/// # let mut world = World::new();
/// let entity = world.spawn((X(42), Y(10))).id();
///
/// // Grab the component IDs for `X` and `Y` in whatever way you like.
/// let x_id = world.register_component::<X>();
/// let y_id = world.register_component::<Y>();
///
/// // Then, get the components by ID. You'll receive a same-sized array.
/// let Ok([x_ptr, y_ptr]) = world.entity(entity).get_by_id([x_id, y_id]) else {
/// // Up to you to handle if a component is missing from the entity.
/// # unreachable!();
/// };
/// # assert_eq!((unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() }), (&X(42), &Y(10)));
/// ```
///
/// ## Slice of [`ComponentId`]s
///
/// ```
/// # use bevy_ecs::{prelude::*, component::ComponentId};
/// #
/// # #[derive(Component, PartialEq, Debug)]
/// # pub struct X(i32);
/// # #[derive(Component, PartialEq, Debug)]
/// # pub struct Y(i32);
/// # let mut world = World::new();
/// let entity = world.spawn((X(42), Y(10))).id();
///
/// // Grab the component IDs for `X` and `Y` in whatever way you like.
/// let x_id = world.register_component::<X>();
/// let y_id = world.register_component::<Y>();
///
/// // Then, get the components by ID. You'll receive a vec of ptrs.
/// let ptrs = world.entity(entity).get_by_id(&[x_id, y_id] as &[ComponentId]);
/// # let ptrs = ptrs.unwrap();
/// # assert_eq!((unsafe { ptrs[0].deref::<X>() }, unsafe { ptrs[1].deref::<Y>() }), (&X(42), &Y(10)));
/// ```
///
/// ## `HashSet` of [`ComponentId`]s
///
/// ```
/// # use bevy_platform::collections::HashSet;
/// # use bevy_ecs::{prelude::*, component::ComponentId};
/// #
/// # #[derive(Component, PartialEq, Debug)]
/// # pub struct X(i32);
/// # #[derive(Component, PartialEq, Debug)]
/// # pub struct Y(i32);
/// # let mut world = World::new();
/// let entity = world.spawn((X(42), Y(10))).id();
///
/// // Grab the component IDs for `X` and `Y` in whatever way you like.
/// let x_id = world.register_component::<X>();
/// let y_id = world.register_component::<Y>();
///
/// // Then, get the components by ID. You'll receive a vec of ptrs.
/// let ptrs = world.entity(entity).get_by_id(&HashSet::from_iter([x_id, y_id]));
/// # let ptrs = ptrs.unwrap();
/// # assert_eq!((unsafe { ptrs[&x_id].deref::<X>() }, unsafe { ptrs[&y_id].deref::<Y>() }), (&X(42), &Y(10)));
/// ```
#[inline]
pub fn get_by_id<F: DynamicComponentFetch>(
&self,
component_ids: F,
) -> Result<F::Ref<'w>, EntityComponentError> {
// SAFETY: We have read-only access to all components of this entity.
unsafe { component_ids.fetch_ref(self.cell) }
}
/// Returns read-only components for the current entity that match the query `Q`.
///
/// # Panics
///
/// If the entity does not have the components required by the query `Q`.
pub fn components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(&self) -> Q::Item<'w, 'static> {
self.get_components::<Q>()
.expect("Query does not match the current entity")
}
/// Returns read-only components for the current entity that match the query `Q`,
/// or `None` if the entity does not have the components required by the query `Q`.
pub fn get_components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(
&self,
) -> Result<Q::Item<'w, 'static>, QueryAccessError> {
// SAFETY:
// - We have read-only access to all components of this entity.
// - The query is read-only, and read-only references cannot have conflicts.
unsafe { self.cell.get_components::<Q>() }
}
/// Returns the source code location from which this entity has been spawned.
pub fn spawned_by(&self) -> MaybeLocation {
self.cell.spawned_by()
}
/// Returns the [`Tick`] at which this entity has been spawned.
pub fn spawn_tick(&self) -> Tick {
self.cell.spawn_tick()
}
}
impl<'a> From<EntityRef<'a>> for FilteredEntityRef<'a, 'static> {
fn from(entity: EntityRef<'a>) -> Self {
// SAFETY:
// - `EntityRef` guarantees exclusive access to all components in the new `FilteredEntityRef`.
unsafe { FilteredEntityRef::new(entity.cell, const { &Access::new_read_all() }) }
}
}
impl<'a> From<&'a EntityRef<'_>> for FilteredEntityRef<'a, 'static> {
fn from(entity: &'a EntityRef<'_>) -> Self {
// SAFETY:
// - `EntityRef` guarantees exclusive access to all components in the new `FilteredEntityRef`.
unsafe { FilteredEntityRef::new(entity.cell, const { &Access::new_read_all() }) }
}
}
impl PartialEq for EntityRef<'_> {
fn eq(&self, other: &Self) -> bool {
self.entity() == other.entity()
}
}
impl Eq for EntityRef<'_> {}
impl PartialOrd for EntityRef<'_> {
/// [`EntityRef`]'s comparison trait implementations match the underlying [`Entity`],
/// and cannot discern between different worlds.
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for EntityRef<'_> {
fn cmp(&self, other: &Self) -> Ordering {
self.entity().cmp(&other.entity())
}
}
impl Hash for EntityRef<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.entity().hash(state);
}
}
impl ContainsEntity for EntityRef<'_> {
fn entity(&self) -> Entity {
self.id()
}
}
// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
unsafe impl EntityEquivalent for EntityRef<'_> {}
| 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/world/entity_access/entity_mut.rs | crates/bevy_ecs/src/world/entity_access/entity_mut.rs | use crate::{
archetype::Archetype,
change_detection::{ComponentTicks, MaybeLocation, Tick},
component::{Component, ComponentId, Mutable},
entity::{ContainsEntity, Entity, EntityEquivalent, EntityLocation},
query::{has_conflicts, Access, QueryAccessError, ReadOnlyQueryData, ReleaseStateQueryData},
world::{
error::EntityComponentError, unsafe_world_cell::UnsafeEntityCell, DynamicComponentFetch,
EntityRef, FilteredEntityMut, FilteredEntityRef, Mut, Ref,
},
};
use core::{
any::TypeId,
cmp::Ordering,
hash::{Hash, Hasher},
};
/// Provides mutable access to a single entity and all of its components.
///
/// Contrast with [`EntityWorldMut`], which allows adding and removing components,
/// despawning the entity, and provides mutable access to the entire world.
/// Because of this, `EntityWorldMut` cannot coexist with any other world accesses.
///
/// # Examples
///
/// Disjoint mutable access.
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Component)] pub struct A;
/// fn disjoint_system(
/// query1: Query<EntityMut, With<A>>,
/// query2: Query<EntityMut, Without<A>>,
/// ) {
/// // ...
/// }
/// # bevy_ecs::system::assert_is_system(disjoint_system);
/// ```
///
/// [`EntityWorldMut`]: crate::world::EntityWorldMut
pub struct EntityMut<'w> {
cell: UnsafeEntityCell<'w>,
}
impl<'w> EntityMut<'w> {
/// # Safety
/// - `cell` must have permission to mutate every component of the entity.
/// - No accesses to any of the entity's components may exist
/// at the same time as the returned [`EntityMut`].
#[inline]
pub(crate) unsafe fn new(cell: UnsafeEntityCell<'w>) -> Self {
Self { cell }
}
/// Returns a new instance with a shorter lifetime.
/// This is useful if you have `&mut EntityMut`, but you need `EntityMut`.
pub fn reborrow(&mut self) -> EntityMut<'_> {
// SAFETY: We have exclusive access to the entire entity and its components.
unsafe { Self::new(self.cell) }
}
/// Consumes `self` and returns read-only access to all of the entity's
/// components, with the world `'w` lifetime.
pub fn into_readonly(self) -> EntityRef<'w> {
EntityRef::from(self)
}
/// Gets read-only access to all of the entity's components.
pub fn as_readonly(&self) -> EntityRef<'_> {
EntityRef::from(self)
}
/// Get access to the underlying [`UnsafeEntityCell`]
pub fn as_unsafe_entity_cell(&mut self) -> UnsafeEntityCell<'_> {
self.cell
}
/// Returns the [ID](Entity) of the current entity.
#[inline]
#[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
pub fn id(&self) -> Entity {
self.cell.id()
}
/// Gets metadata indicating the location where the current entity is stored.
#[inline]
pub fn location(&self) -> EntityLocation {
self.cell.location()
}
/// Returns the archetype that the current entity belongs to.
#[inline]
pub fn archetype(&self) -> &Archetype {
self.cell.archetype()
}
/// Returns `true` if the current entity has a component of type `T`.
/// Otherwise, this returns `false`.
///
/// ## Notes
///
/// If you do not know the concrete type of a component, consider using
/// [`Self::contains_id`] or [`Self::contains_type_id`].
#[inline]
pub fn contains<T: Component>(&self) -> bool {
self.contains_type_id(TypeId::of::<T>())
}
/// Returns `true` if the current entity has a component identified by `component_id`.
/// Otherwise, this returns false.
///
/// ## Notes
///
/// - If you know the concrete type of the component, you should prefer [`Self::contains`].
/// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
/// [`Self::contains_type_id`].
#[inline]
pub fn contains_id(&self, component_id: ComponentId) -> bool {
self.cell.contains_id(component_id)
}
/// Returns `true` if the current entity has a component with the type identified by `type_id`.
/// Otherwise, this returns false.
///
/// ## Notes
///
/// - If you know the concrete type of the component, you should prefer [`Self::contains`].
/// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
#[inline]
pub fn contains_type_id(&self, type_id: TypeId) -> bool {
self.cell.contains_type_id(type_id)
}
/// Gets access to the component of type `T` for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
#[inline]
pub fn get<T: Component>(&self) -> Option<&'_ T> {
self.as_readonly().get()
}
/// Returns read-only components for the current entity that match the query `Q`.
///
/// # Panics
///
/// If the entity does not have the components required by the query `Q`.
pub fn components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(&self) -> Q::Item<'_, 'static> {
self.as_readonly().components::<Q>()
}
/// Returns read-only components for the current entity that match the query `Q`,
/// or `None` if the entity does not have the components required by the query `Q`.
pub fn get_components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(
&self,
) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
self.as_readonly().get_components::<Q>()
}
/// Returns components for the current entity that match the query `Q`,
/// or `None` if the entity does not have the components required by the query `Q`.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// #[derive(Component)]
/// struct X(usize);
/// #[derive(Component)]
/// struct Y(usize);
///
/// # let mut world = World::default();
/// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
/// // Get mutable access to two components at once
/// // SAFETY: X and Y are different components
/// let (mut x, mut y) =
/// unsafe { entity.get_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
/// *x = X(1);
/// *y = Y(1);
/// // This would trigger undefined behavior, as the `&mut X`s would alias:
/// // entity.get_components_mut_unchecked::<(&mut X, &mut X)>();
/// ```
///
/// # Safety
/// It is the caller's responsibility to ensure that
/// the `QueryData` does not provide aliasing mutable references to the same component.
///
/// # See also
///
/// - [`Self::get_components_mut`] for the safe version that performs aliasing checks
pub unsafe fn get_components_mut_unchecked<Q: ReleaseStateQueryData>(
&mut self,
) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
// SAFETY: Caller ensures the `QueryData` does not provide aliasing mutable references to the same component
unsafe { self.reborrow().into_components_mut_unchecked::<Q>() }
}
/// Returns components for the current entity that match the query `Q`.
/// In the case of conflicting [`QueryData`](crate::query::QueryData), unregistered components, or missing components,
/// this will return a [`QueryAccessError`]
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// #[derive(Component)]
/// struct X(usize);
/// #[derive(Component)]
/// struct Y(usize);
///
/// # let mut world = World::default();
/// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
/// // Get mutable access to two components at once
/// // SAFETY: X and Y are different components
/// let (mut x, mut y) = entity.get_components_mut::<(&mut X, &mut Y)>().unwrap();
/// ```
///
/// Note that this does a O(n^2) check that the [`QueryData`](crate::query::QueryData) does not conflict. If performance is a
/// consideration you should use [`Self::get_components_mut_unchecked`] instead.
pub fn get_components_mut<Q: ReleaseStateQueryData>(
&mut self,
) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
self.reborrow().into_components_mut::<Q>()
}
/// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
/// or `None` if the entity does not have the components required by the query `Q`.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// #[derive(Component)]
/// struct X(usize);
/// #[derive(Component)]
/// struct Y(usize);
///
/// # let mut world = World::default();
/// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
/// // Get mutable access to two components at once
/// // SAFETY: X and Y are different components
/// let (mut x, mut y) =
/// unsafe { entity.into_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
/// *x = X(1);
/// *y = Y(1);
/// // This would trigger undefined behavior, as the `&mut X`s would alias:
/// // entity.into_components_mut_unchecked::<(&mut X, &mut X)>();
/// ```
///
/// # Safety
/// It is the caller's responsibility to ensure that
/// the `QueryData` does not provide aliasing mutable references to the same component.
///
/// # See also
///
/// - [`Self::into_components_mut`] for the safe version that performs aliasing checks
pub unsafe fn into_components_mut_unchecked<Q: ReleaseStateQueryData>(
self,
) -> Result<Q::Item<'w, 'static>, QueryAccessError> {
// SAFETY:
// - We have mutable access to all components of this entity.
// - Caller asserts the `QueryData` does not provide aliasing mutable references to the same component
unsafe { self.cell.get_components::<Q>() }
}
/// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
/// or `None` if the entity does not have the components required by the query `Q`.
///
/// The checks for aliasing mutable references may be expensive.
/// If performance is a concern, consider making multiple calls to [`Self::get_mut`].
/// If that is not possible, consider using [`Self::into_components_mut_unchecked`] to skip the checks.
///
/// # Panics
///
/// If the `QueryData` provides aliasing mutable references to the same component.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// #[derive(Component)]
/// struct X(usize);
/// #[derive(Component)]
/// struct Y(usize);
///
/// # let mut world = World::default();
/// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
/// // Get mutable access to two components at once
/// let (mut x, mut y) = entity.into_components_mut::<(&mut X, &mut Y)>().unwrap();
/// *x = X(1);
/// *y = Y(1);
/// ```
///
/// ```should_panic
/// # use bevy_ecs::prelude::*;
/// #
/// # #[derive(Component)]
/// # struct X(usize);
/// #
/// # let mut world = World::default();
/// let mut entity = world.spawn((X(0))).into_mutable();
/// // This panics, as the `&mut X`s would alias:
/// entity.into_components_mut::<(&mut X, &mut X)>();
/// ```
pub fn into_components_mut<Q: ReleaseStateQueryData>(
self,
) -> Result<Q::Item<'w, 'static>, QueryAccessError> {
has_conflicts::<Q>(self.cell.world().components())?;
// SAFETY: we checked that there were not conflicting components above
unsafe { self.into_components_mut_unchecked::<Q>() }
}
/// Consumes `self` and gets access to the component of type `T` with the
/// world `'w` lifetime for the current entity.
///
/// Returns `None` if the entity does not have a component of type `T`.
#[inline]
pub fn into_borrow<T: Component>(self) -> Option<&'w T> {
self.into_readonly().get()
}
/// Gets access to the component of type `T` for the current entity,
/// including change detection information as a [`Ref`].
///
/// Returns `None` if the entity does not have a component of type `T`.
#[inline]
pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
self.as_readonly().get_ref()
}
/// Consumes `self` and gets access to the component of type `T` with world
/// `'w` lifetime for the current entity, including change detection information
/// as a [`Ref<'w>`].
///
/// Returns `None` if the entity does not have a component of type `T`.
#[inline]
pub fn into_ref<T: Component>(self) -> Option<Ref<'w, T>> {
self.into_readonly().get_ref()
}
/// Gets mutable access to the component of type `T` for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
#[inline]
pub fn get_mut<T: Component<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, T>> {
// SAFETY: &mut self implies exclusive access for duration of returned value
unsafe { self.cell.get_mut() }
}
/// Gets mutable access to the component of type `T` for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
///
/// # Safety
///
/// - `T` must be a mutable component
#[inline]
pub unsafe fn get_mut_assume_mutable<T: Component>(&mut self) -> Option<Mut<'_, T>> {
// SAFETY:
// - &mut self implies exclusive access for duration of returned value
// - Caller ensures `T` is a mutable component
unsafe { self.cell.get_mut_assume_mutable() }
}
/// Consumes self and gets mutable access to the component of type `T`
/// with the world `'w` lifetime for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
#[inline]
pub fn into_mut<T: Component<Mutability = Mutable>>(self) -> Option<Mut<'w, T>> {
// SAFETY: consuming `self` implies exclusive access
unsafe { self.cell.get_mut() }
}
/// Gets mutable access to the component of type `T` for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
///
/// # Safety
///
/// - `T` must be a mutable component
#[inline]
pub unsafe fn into_mut_assume_mutable<T: Component>(self) -> Option<Mut<'w, T>> {
// SAFETY:
// - Consuming `self` implies exclusive access
// - Caller ensures `T` is a mutable component
unsafe { self.cell.get_mut_assume_mutable() }
}
/// Retrieves the change ticks for the given component. This can be useful for implementing change
/// detection in custom runtimes.
#[inline]
pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
self.as_readonly().get_change_ticks::<T>()
}
/// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
/// detection in custom runtimes.
///
/// **You should prefer to use the typed API [`EntityWorldMut::get_change_ticks`] where possible and only
/// use this in cases where the actual component types are not known at
/// compile time.**
///
/// [`EntityWorldMut::get_change_ticks`]: crate::world::EntityWorldMut::get_change_ticks
#[inline]
pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
self.as_readonly().get_change_ticks_by_id(component_id)
}
/// Returns untyped read-only reference(s) to component(s) for the
/// current entity, based on the given [`ComponentId`]s.
///
/// **You should prefer to use the typed API [`EntityMut::get`] where
/// possible and only use this in cases where the actual component types
/// are not known at compile time.**
///
/// Unlike [`EntityMut::get`], this returns untyped reference(s) to
/// component(s), and it's the job of the caller to ensure the correct
/// type(s) are dereferenced (if necessary).
///
/// # Errors
///
/// Returns [`EntityComponentError::MissingComponent`] if the entity does
/// not have a component.
///
/// # Examples
///
/// For examples on how to use this method, see [`EntityRef::get_by_id`].
#[inline]
pub fn get_by_id<F: DynamicComponentFetch>(
&self,
component_ids: F,
) -> Result<F::Ref<'_>, EntityComponentError> {
self.as_readonly().get_by_id(component_ids)
}
/// Consumes `self` and returns untyped read-only reference(s) to
/// component(s) with lifetime `'w` for the current entity, based on the
/// given [`ComponentId`]s.
///
/// **You should prefer to use the typed API [`EntityMut::into_borrow`]
/// where possible and only use this in cases where the actual component
/// types are not known at compile time.**
///
/// Unlike [`EntityMut::into_borrow`], this returns untyped reference(s) to
/// component(s), and it's the job of the caller to ensure the correct
/// type(s) are dereferenced (if necessary).
///
/// # Errors
///
/// Returns [`EntityComponentError::MissingComponent`] if the entity does
/// not have a component.
///
/// # Examples
///
/// For examples on how to use this method, see [`EntityRef::get_by_id`].
#[inline]
pub fn into_borrow_by_id<F: DynamicComponentFetch>(
self,
component_ids: F,
) -> Result<F::Ref<'w>, EntityComponentError> {
self.into_readonly().get_by_id(component_ids)
}
/// Returns untyped mutable reference(s) to component(s) for
/// the current entity, based on the given [`ComponentId`]s.
///
/// **You should prefer to use the typed API [`EntityMut::get_mut`] where
/// possible and only use this in cases where the actual component types
/// are not known at compile time.**
///
/// Unlike [`EntityMut::get_mut`], this returns untyped reference(s) to
/// component(s), and it's the job of the caller to ensure the correct
/// type(s) are dereferenced (if necessary).
///
/// # Errors
///
/// - Returns [`EntityComponentError::MissingComponent`] if the entity does
/// not have a component.
/// - Returns [`EntityComponentError::AliasedMutability`] if a component
/// is requested multiple times.
///
/// # Examples
///
/// ## Single [`ComponentId`]
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// # #[derive(Component, PartialEq, Debug)]
/// # pub struct Foo(i32);
/// # let mut world = World::new();
/// let entity = world.spawn(Foo(42)).id();
///
/// // Grab the component ID for `Foo` in whatever way you like.
/// let component_id = world.register_component::<Foo>();
///
/// // Then, get the component by ID.
/// let mut entity_mut = world.entity_mut(entity);
/// let mut ptr = entity_mut.get_mut_by_id(component_id)
/// # .unwrap();
/// # assert_eq!(unsafe { ptr.as_mut().deref_mut::<Foo>() }, &mut Foo(42));
/// ```
///
/// ## Array of [`ComponentId`]s
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// # #[derive(Component, PartialEq, Debug)]
/// # pub struct X(i32);
/// # #[derive(Component, PartialEq, Debug)]
/// # pub struct Y(i32);
/// # let mut world = World::new();
/// let entity = world.spawn((X(42), Y(10))).id();
///
/// // Grab the component IDs for `X` and `Y` in whatever way you like.
/// let x_id = world.register_component::<X>();
/// let y_id = world.register_component::<Y>();
///
/// // Then, get the components by ID. You'll receive a same-sized array.
/// let mut entity_mut = world.entity_mut(entity);
/// let Ok([mut x_ptr, mut y_ptr]) = entity_mut.get_mut_by_id([x_id, y_id]) else {
/// // Up to you to handle if a component is missing from the entity.
/// # unreachable!();
/// };
/// # assert_eq!((unsafe { x_ptr.as_mut().deref_mut::<X>() }, unsafe { y_ptr.as_mut().deref_mut::<Y>() }), (&mut X(42), &mut Y(10)));
/// ```
///
/// ## Slice of [`ComponentId`]s
///
/// ```
/// # use bevy_ecs::{prelude::*, component::ComponentId, change_detection::MutUntyped};
/// #
/// # #[derive(Component, PartialEq, Debug)]
/// # pub struct X(i32);
/// # #[derive(Component, PartialEq, Debug)]
/// # pub struct Y(i32);
/// # let mut world = World::new();
/// let entity = world.spawn((X(42), Y(10))).id();
///
/// // Grab the component IDs for `X` and `Y` in whatever way you like.
/// let x_id = world.register_component::<X>();
/// let y_id = world.register_component::<Y>();
///
/// // Then, get the components by ID. You'll receive a vec of ptrs.
/// let mut entity_mut = world.entity_mut(entity);
/// let ptrs = entity_mut.get_mut_by_id(&[x_id, y_id] as &[ComponentId])
/// # .unwrap();
/// # let [mut x_ptr, mut y_ptr]: [MutUntyped; 2] = ptrs.try_into().unwrap();
/// # assert_eq!((unsafe { x_ptr.as_mut().deref_mut::<X>() }, unsafe { y_ptr.as_mut().deref_mut::<Y>() }), (&mut X(42), &mut Y(10)));
/// ```
///
/// ## `HashSet` of [`ComponentId`]s
///
/// ```
/// # use bevy_platform::collections::HashSet;
/// # use bevy_ecs::{prelude::*, component::ComponentId};
/// #
/// # #[derive(Component, PartialEq, Debug)]
/// # pub struct X(i32);
/// # #[derive(Component, PartialEq, Debug)]
/// # pub struct Y(i32);
/// # let mut world = World::new();
/// let entity = world.spawn((X(42), Y(10))).id();
///
/// // Grab the component IDs for `X` and `Y` in whatever way you like.
/// let x_id = world.register_component::<X>();
/// let y_id = world.register_component::<Y>();
///
/// // Then, get the components by ID. You'll receive a `HashMap` of ptrs.
/// let mut entity_mut = world.entity_mut(entity);
/// let mut ptrs = entity_mut.get_mut_by_id(&HashSet::from_iter([x_id, y_id]))
/// # .unwrap();
/// # let [Some(mut x_ptr), Some(mut y_ptr)] = ptrs.get_many_mut([&x_id, &y_id]) else { unreachable!() };
/// # assert_eq!((unsafe { x_ptr.as_mut().deref_mut::<X>() }, unsafe { y_ptr.as_mut().deref_mut::<Y>() }), (&mut X(42), &mut Y(10)));
/// ```
#[inline]
pub fn get_mut_by_id<F: DynamicComponentFetch>(
&mut self,
component_ids: F,
) -> Result<F::Mut<'_>, EntityComponentError> {
// SAFETY:
// - `&mut self` ensures that no references exist to this entity's components.
// - We have exclusive access to all components of this entity.
unsafe { component_ids.fetch_mut(self.cell) }
}
/// Returns untyped mutable reference(s) to component(s) for
/// the current entity, based on the given [`ComponentId`]s.
/// Assumes the given [`ComponentId`]s refer to mutable components.
///
/// **You should prefer to use the typed API [`EntityMut::get_mut_assume_mutable`] where
/// possible and only use this in cases where the actual component types
/// are not known at compile time.**
///
/// Unlike [`EntityMut::get_mut_assume_mutable`], this returns untyped reference(s) to
/// component(s), and it's the job of the caller to ensure the correct
/// type(s) are dereferenced (if necessary).
///
/// # Errors
///
/// - Returns [`EntityComponentError::MissingComponent`] if the entity does
/// not have a component.
/// - Returns [`EntityComponentError::AliasedMutability`] if a component
/// is requested multiple times.
///
/// # Safety
/// It is the callers responsibility to ensure that
/// - the provided [`ComponentId`]s must refer to mutable components.
#[inline]
pub unsafe fn get_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
&mut self,
component_ids: F,
) -> Result<F::Mut<'_>, EntityComponentError> {
// SAFETY:
// - `&mut self` ensures that no references exist to this entity's components.
// - We have exclusive access to all components of this entity.
unsafe { component_ids.fetch_mut_assume_mutable(self.cell) }
}
/// Returns untyped mutable reference to component for
/// the current entity, based on the given [`ComponentId`].
///
/// Unlike [`EntityMut::get_mut_by_id`], this method borrows &self instead of
/// &mut self, allowing the caller to access multiple components simultaneously.
///
/// # Errors
///
/// - Returns [`EntityComponentError::MissingComponent`] if the entity does
/// not have a component.
/// - Returns [`EntityComponentError::AliasedMutability`] if a component
/// is requested multiple times.
///
/// # Safety
/// It is the callers responsibility to ensure that
/// - the [`UnsafeEntityCell`] has permission to access the component mutably
/// - no other references to the component exist at the same time
#[inline]
pub unsafe fn get_mut_by_id_unchecked<F: DynamicComponentFetch>(
&self,
component_ids: F,
) -> Result<F::Mut<'_>, EntityComponentError> {
// SAFETY:
// - The caller must ensure simultaneous access is limited
// - to components that are mutually independent.
unsafe { component_ids.fetch_mut(self.cell) }
}
/// Returns untyped mutable reference to component for
/// the current entity, based on the given [`ComponentId`].
/// Assumes the given [`ComponentId`]s refer to mutable components.
///
/// Unlike [`EntityMut::get_mut_assume_mutable_by_id`], this method borrows &self instead of
/// &mut self, allowing the caller to access multiple components simultaneously.
///
/// # Errors
///
/// - Returns [`EntityComponentError::MissingComponent`] if the entity does
/// not have a component.
/// - Returns [`EntityComponentError::AliasedMutability`] if a component
/// is requested multiple times.
///
/// # Safety
/// It is the callers responsibility to ensure that
/// - the [`UnsafeEntityCell`] has permission to access the component mutably
/// - no other references to the component exist at the same time
/// - the provided [`ComponentId`]s must refer to mutable components.
#[inline]
pub unsafe fn get_mut_assume_mutable_by_id_unchecked<F: DynamicComponentFetch>(
&self,
component_ids: F,
) -> Result<F::Mut<'_>, EntityComponentError> {
// SAFETY:
// - The caller must ensure simultaneous access is limited
// - to components that are mutually independent.
unsafe { component_ids.fetch_mut_assume_mutable(self.cell) }
}
/// Consumes `self` and returns untyped mutable reference(s)
/// to component(s) with lifetime `'w` for the current entity, based on the
/// given [`ComponentId`]s.
///
/// **You should prefer to use the typed API [`EntityMut::into_mut`] where
/// possible and only use this in cases where the actual component types
/// are not known at compile time.**
///
/// Unlike [`EntityMut::into_mut`], this returns untyped reference(s) to
/// component(s), and it's the job of the caller to ensure the correct
/// type(s) are dereferenced (if necessary).
///
/// # Errors
///
/// - Returns [`EntityComponentError::MissingComponent`] if the entity does
/// not have a component.
/// - Returns [`EntityComponentError::AliasedMutability`] if a component
/// is requested multiple times.
///
/// # Examples
///
/// For examples on how to use this method, see [`EntityMut::get_mut_by_id`].
#[inline]
pub fn into_mut_by_id<F: DynamicComponentFetch>(
self,
component_ids: F,
) -> Result<F::Mut<'w>, EntityComponentError> {
// SAFETY:
// - consuming `self` ensures that no references exist to this entity's components.
// - We have exclusive access to all components of this entity.
unsafe { component_ids.fetch_mut(self.cell) }
}
/// Consumes `self` and returns untyped mutable reference(s)
/// to component(s) with lifetime `'w` for the current entity, based on the
/// given [`ComponentId`]s.
/// Assumes the given [`ComponentId`]s refer to mutable components.
///
/// **You should prefer to use the typed API [`EntityMut::into_mut_assume_mutable`] where
/// possible and only use this in cases where the actual component types
/// are not known at compile time.**
///
/// Unlike [`EntityMut::into_mut_assume_mutable`], this returns untyped reference(s) to
/// component(s), and it's the job of the caller to ensure the correct
/// type(s) are dereferenced (if necessary).
///
/// # Errors
///
/// - Returns [`EntityComponentError::MissingComponent`] if the entity does
/// not have a component.
/// - Returns [`EntityComponentError::AliasedMutability`] if a component
/// is requested multiple times.
///
/// # Safety
/// It is the callers responsibility to ensure that
/// - the provided [`ComponentId`]s must refer to mutable components.
#[inline]
pub unsafe fn into_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
self,
component_ids: F,
) -> Result<F::Mut<'w>, EntityComponentError> {
// SAFETY:
// - consuming `self` ensures that no references exist to this entity's components.
// - We have exclusive access to all components of this entity.
unsafe { component_ids.fetch_mut_assume_mutable(self.cell) }
}
/// Returns the source code location from which this entity has been spawned.
pub fn spawned_by(&self) -> MaybeLocation {
self.cell.spawned_by()
}
/// Returns the [`Tick`] at which this entity has been spawned.
pub fn spawn_tick(&self) -> Tick {
self.cell.spawn_tick()
}
}
impl<'w> From<EntityMut<'w>> for EntityRef<'w> {
fn from(entity: EntityMut<'w>) -> Self {
// SAFETY:
// - `EntityMut` guarantees exclusive access to all of the entity's components.
unsafe { EntityRef::new(entity.cell) }
}
}
impl<'a> From<&'a EntityMut<'_>> for EntityRef<'a> {
fn from(entity: &'a EntityMut<'_>) -> Self {
// SAFETY:
// - `EntityMut` guarantees exclusive access to all of the entity's components.
// - `&entity` ensures there are no mutable accesses.
unsafe { EntityRef::new(entity.cell) }
}
}
impl<'w> From<&'w mut EntityMut<'_>> for EntityMut<'w> {
fn from(entity: &'w mut EntityMut<'_>) -> Self {
entity.reborrow()
}
}
impl<'a> From<EntityMut<'a>> for FilteredEntityRef<'a, 'static> {
fn from(entity: EntityMut<'a>) -> Self {
// SAFETY:
// - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
unsafe { FilteredEntityRef::new(entity.cell, const { &Access::new_read_all() }) }
}
}
impl<'a> From<&'a EntityMut<'_>> for FilteredEntityRef<'a, 'static> {
fn from(entity: &'a EntityMut<'_>) -> Self {
// SAFETY:
// - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
unsafe { FilteredEntityRef::new(entity.cell, const { &Access::new_read_all() }) }
}
}
impl<'a> From<EntityMut<'a>> for FilteredEntityMut<'a, 'static> {
fn from(entity: EntityMut<'a>) -> Self {
// SAFETY:
// - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityMut`.
unsafe { FilteredEntityMut::new(entity.cell, const { &Access::new_write_all() }) }
}
}
impl<'a> From<&'a mut EntityMut<'_>> for FilteredEntityMut<'a, 'static> {
fn from(entity: &'a mut EntityMut<'_>) -> Self {
// SAFETY:
// - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityMut`.
unsafe { FilteredEntityMut::new(entity.cell, const { &Access::new_write_all() }) }
}
}
impl PartialEq for EntityMut<'_> {
fn eq(&self, other: &Self) -> bool {
self.entity() == other.entity()
}
}
impl Eq for EntityMut<'_> {}
impl PartialOrd for EntityMut<'_> {
/// [`EntityMut`]'s comparison trait implementations match the underlying [`Entity`],
/// and cannot discern between different worlds.
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for EntityMut<'_> {
| 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/world/entity_access/except.rs | crates/bevy_ecs/src/world/entity_access/except.rs | use crate::{
bundle::Bundle,
change_detection::{ComponentTicks, MaybeLocation, MutUntyped, Tick},
component::{Component, ComponentId, Components, Mutable},
entity::{ContainsEntity, Entity, EntityEquivalent},
query::Access,
world::{
unsafe_world_cell::UnsafeEntityCell, DynamicComponentFetch, FilteredEntityMut,
FilteredEntityRef, Mut, Ref,
},
};
use bevy_ptr::Ptr;
use core::{
any::TypeId,
cmp::Ordering,
hash::{Hash, Hasher},
marker::PhantomData,
};
/// Provides read-only access to a single entity and all its components, save
/// for an explicitly-enumerated set.
pub struct EntityRefExcept<'w, 's, B>
where
B: Bundle,
{
entity: UnsafeEntityCell<'w>,
access: &'s Access,
phantom: PhantomData<B>,
}
impl<'w, 's, B> EntityRefExcept<'w, 's, B>
where
B: Bundle,
{
/// # Safety
/// Other users of `UnsafeEntityCell` must only have mutable access to the components in `B`.
pub(crate) unsafe fn new(entity: UnsafeEntityCell<'w>, access: &'s Access) -> Self {
Self {
entity,
access,
phantom: PhantomData,
}
}
/// Returns the [ID](Entity) of the current entity.
#[inline]
#[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
pub fn id(&self) -> Entity {
self.entity.id()
}
/// Gets access to the component of type `C` for the current entity. Returns
/// `None` if the component doesn't have a component of that type or if the
/// type is one of the excluded components.
#[inline]
pub fn get<C>(&self) -> Option<&'w C>
where
C: Component,
{
let components = self.entity.world().components();
let id = components.valid_component_id::<C>()?;
if bundle_contains_component::<B>(components, id) {
None
} else {
// SAFETY: We have read access for all components that weren't
// covered by the `contains` check above.
unsafe { self.entity.get() }
}
}
/// Gets access to the component of type `C` for the current entity,
/// including change detection information. Returns `None` if the component
/// doesn't have a component of that type or if the type is one of the
/// excluded components.
#[inline]
pub fn get_ref<C>(&self) -> Option<Ref<'w, C>>
where
C: Component,
{
let components = self.entity.world().components();
let id = components.valid_component_id::<C>()?;
if bundle_contains_component::<B>(components, id) {
None
} else {
// SAFETY: We have read access for all components that weren't
// covered by the `contains` check above.
unsafe { self.entity.get_ref() }
}
}
/// Returns the source code location from which this entity has been spawned.
pub fn spawned_by(&self) -> MaybeLocation {
self.entity.spawned_by()
}
/// Returns the [`Tick`] at which this entity has been spawned.
pub fn spawn_tick(&self) -> Tick {
self.entity.spawn_tick()
}
/// Gets the component of the given [`ComponentId`] from the entity.
///
/// **You should prefer to use the typed API [`Self::get`] where possible and only
/// use this in cases where the actual component types are not known at
/// compile time.**
///
/// Unlike [`EntityRefExcept::get`], this returns a raw pointer to the component,
/// which is only valid while the [`EntityRefExcept`] is alive.
#[inline]
pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'w>> {
let components = self.entity.world().components();
(!bundle_contains_component::<B>(components, component_id))
.then(|| {
// SAFETY: We have read access for this component
unsafe { self.entity.get_by_id(component_id) }
})
.flatten()
}
/// Returns `true` if the current entity has a component of type `T`.
/// Otherwise, this returns `false`.
///
/// ## Notes
///
/// If you do not know the concrete type of a component, consider using
/// [`Self::contains_id`] or [`Self::contains_type_id`].
#[inline]
pub fn contains<T: Component>(&self) -> bool {
self.contains_type_id(TypeId::of::<T>())
}
/// Returns `true` if the current entity has a component identified by `component_id`.
/// Otherwise, this returns false.
///
/// ## Notes
///
/// - If you know the concrete type of the component, you should prefer [`Self::contains`].
/// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
/// [`Self::contains_type_id`].
#[inline]
pub fn contains_id(&self, component_id: ComponentId) -> bool {
self.entity.contains_id(component_id)
}
/// Returns `true` if the current entity has a component with the type identified by `type_id`.
/// Otherwise, this returns false.
///
/// ## Notes
///
/// - If you know the concrete type of the component, you should prefer [`Self::contains`].
/// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
#[inline]
pub fn contains_type_id(&self, type_id: TypeId) -> bool {
self.entity.contains_type_id(type_id)
}
/// Retrieves the change ticks for the given component. This can be useful for implementing change
/// detection in custom runtimes.
#[inline]
pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
let component_id = self
.entity
.world()
.components()
.get_valid_id(TypeId::of::<T>())?;
let components = self.entity.world().components();
(!bundle_contains_component::<B>(components, component_id))
.then(|| {
// SAFETY: We have read access
unsafe { self.entity.get_change_ticks::<T>() }
})
.flatten()
}
/// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
/// detection in custom runtimes.
///
/// **You should prefer to use the typed API [`Self::get_change_ticks`] where possible and only
/// use this in cases where the actual component types are not known at
/// compile time.**
#[inline]
pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
let components = self.entity.world().components();
(!bundle_contains_component::<B>(components, component_id))
.then(|| {
// SAFETY: We have read access
unsafe { self.entity.get_change_ticks_by_id(component_id) }
})
.flatten()
}
}
impl<'w, 's, B: Bundle> From<&'w EntityRefExcept<'_, 's, B>> for FilteredEntityRef<'w, 's> {
fn from(value: &'w EntityRefExcept<'_, 's, B>) -> Self {
// SAFETY:
// - The FilteredEntityRef has the same component access as the given EntityRefExcept.
unsafe { FilteredEntityRef::new(value.entity, value.access) }
}
}
impl<B: Bundle> Clone for EntityRefExcept<'_, '_, B> {
fn clone(&self) -> Self {
*self
}
}
impl<B: Bundle> Copy for EntityRefExcept<'_, '_, B> {}
impl<B: Bundle> PartialEq for EntityRefExcept<'_, '_, B> {
fn eq(&self, other: &Self) -> bool {
self.entity() == other.entity()
}
}
impl<B: Bundle> Eq for EntityRefExcept<'_, '_, B> {}
impl<B: Bundle> PartialOrd for EntityRefExcept<'_, '_, B> {
/// [`EntityRefExcept`]'s comparison trait implementations match the underlying [`Entity`],
/// and cannot discern between different worlds.
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<B: Bundle> Ord for EntityRefExcept<'_, '_, B> {
fn cmp(&self, other: &Self) -> Ordering {
self.entity().cmp(&other.entity())
}
}
impl<B: Bundle> Hash for EntityRefExcept<'_, '_, B> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.entity().hash(state);
}
}
impl<B: Bundle> ContainsEntity for EntityRefExcept<'_, '_, B> {
fn entity(&self) -> Entity {
self.id()
}
}
// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
unsafe impl<B: Bundle> EntityEquivalent for EntityRefExcept<'_, '_, B> {}
/// Provides mutable access to all components of an entity, with the exception
/// of an explicit set.
///
/// This is a rather niche type that should only be used if you need access to
/// *all* components of an entity, while still allowing you to consult other
/// queries that might match entities that this query also matches. If you don't
/// need access to all components, prefer a standard query with a
/// [`Without`](`crate::query::Without`) filter.
pub struct EntityMutExcept<'w, 's, B>
where
B: Bundle,
{
entity: UnsafeEntityCell<'w>,
access: &'s Access,
phantom: PhantomData<B>,
}
impl<'w, 's, B> EntityMutExcept<'w, 's, B>
where
B: Bundle,
{
/// # Safety
/// Other users of `UnsafeEntityCell` must not have access to any components not in `B`.
pub(crate) unsafe fn new(entity: UnsafeEntityCell<'w>, access: &'s Access) -> Self {
Self {
entity,
access,
phantom: PhantomData,
}
}
/// Returns the [ID](Entity) of the current entity.
#[inline]
#[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
pub fn id(&self) -> Entity {
self.entity.id()
}
/// Returns a new instance with a shorter lifetime.
///
/// This is useful if you have `&mut EntityMutExcept`, but you need
/// `EntityMutExcept`.
pub fn reborrow(&mut self) -> EntityMutExcept<'_, 's, B> {
// SAFETY: We have exclusive access to the entire entity and the
// applicable components.
unsafe { Self::new(self.entity, self.access) }
}
/// Gets read-only access to all of the entity's components, except for the
/// ones in `CL`.
#[inline]
pub fn as_readonly(&self) -> EntityRefExcept<'_, 's, B> {
EntityRefExcept::from(self)
}
/// Get access to the underlying [`UnsafeEntityCell`]
pub fn as_unsafe_entity_cell(&mut self) -> UnsafeEntityCell<'_> {
self.entity
}
/// Gets access to the component of type `C` for the current entity. Returns
/// `None` if the component doesn't have a component of that type or if the
/// type is one of the excluded components.
#[inline]
pub fn get<C>(&self) -> Option<&'_ C>
where
C: Component,
{
self.as_readonly().get()
}
/// Gets access to the component of type `C` for the current entity,
/// including change detection information. Returns `None` if the component
/// doesn't have a component of that type or if the type is one of the
/// excluded components.
#[inline]
pub fn get_ref<C>(&self) -> Option<Ref<'_, C>>
where
C: Component,
{
self.as_readonly().get_ref()
}
/// Gets mutable access to the component of type `C` for the current entity.
/// Returns `None` if the component doesn't have a component of that type or
/// if the type is one of the excluded components.
#[inline]
pub fn get_mut<C>(&mut self) -> Option<Mut<'_, C>>
where
C: Component<Mutability = Mutable>,
{
let components = self.entity.world().components();
let id = components.valid_component_id::<C>()?;
if bundle_contains_component::<B>(components, id) {
None
} else {
// SAFETY: We have write access for all components that weren't
// covered by the `contains` check above.
unsafe { self.entity.get_mut() }
}
}
/// Returns the source code location from which this entity has been spawned.
pub fn spawned_by(&self) -> MaybeLocation {
self.entity.spawned_by()
}
/// Returns the [`Tick`] at which this entity has been spawned.
pub fn spawn_tick(&self) -> Tick {
self.entity.spawn_tick()
}
/// Returns `true` if the current entity has a component of type `T`.
/// Otherwise, this returns `false`.
///
/// ## Notes
///
/// If you do not know the concrete type of a component, consider using
/// [`Self::contains_id`] or [`Self::contains_type_id`].
#[inline]
pub fn contains<T: Component>(&self) -> bool {
self.contains_type_id(TypeId::of::<T>())
}
/// Returns `true` if the current entity has a component identified by `component_id`.
/// Otherwise, this returns false.
///
/// ## Notes
///
/// - If you know the concrete type of the component, you should prefer [`Self::contains`].
/// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
/// [`Self::contains_type_id`].
#[inline]
pub fn contains_id(&self, component_id: ComponentId) -> bool {
self.entity.contains_id(component_id)
}
/// Returns `true` if the current entity has a component with the type identified by `type_id`.
/// Otherwise, this returns false.
///
/// ## Notes
///
/// - If you know the concrete type of the component, you should prefer [`Self::contains`].
/// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
#[inline]
pub fn contains_type_id(&self, type_id: TypeId) -> bool {
self.entity.contains_type_id(type_id)
}
/// Gets the component of the given [`ComponentId`] from the entity.
///
/// **You should prefer to use the typed API [`Self::get`] where possible and only
/// use this in cases where the actual component types are not known at
/// compile time.**
///
/// Unlike [`EntityMutExcept::get`], this returns a raw pointer to the component,
/// which is only valid while the [`EntityMutExcept`] is alive.
#[inline]
pub fn get_by_id(&'w self, component_id: ComponentId) -> Option<Ptr<'w>> {
self.as_readonly().get_by_id(component_id)
}
/// Gets a [`MutUntyped`] of the component of the given [`ComponentId`] from the entity.
///
/// **You should prefer to use the typed API [`Self::get_mut`] where possible and only
/// use this in cases where the actual component types are not known at
/// compile time.**
///
/// Unlike [`EntityMutExcept::get_mut`], this returns a raw pointer to the component,
/// which is only valid while the [`EntityMutExcept`] is alive.
#[inline]
pub fn get_mut_by_id<F: DynamicComponentFetch>(
&mut self,
component_id: ComponentId,
) -> Option<MutUntyped<'_>> {
let components = self.entity.world().components();
(!bundle_contains_component::<B>(components, component_id))
.then(|| {
// SAFETY: We have write access
unsafe { self.entity.get_mut_by_id(component_id).ok() }
})
.flatten()
}
}
impl<'w, 's, B: Bundle> From<&'w mut EntityMutExcept<'_, 's, B>> for FilteredEntityMut<'w, 's> {
fn from(value: &'w mut EntityMutExcept<'_, 's, B>) -> Self {
// SAFETY:
// - The FilteredEntityMut has the same component access as the given EntityMutExcept.
unsafe { FilteredEntityMut::new(value.entity, value.access) }
}
}
impl<'w, 's, B> From<&'w EntityMutExcept<'_, 's, B>> for EntityRefExcept<'w, 's, B>
where
B: Bundle,
{
fn from(entity: &'w EntityMutExcept<'_, 's, B>) -> Self {
// SAFETY: All accesses that `EntityRefExcept` provides are also
// accesses that `EntityMutExcept` provides.
unsafe { EntityRefExcept::new(entity.entity, entity.access) }
}
}
impl<B: Bundle> PartialEq for EntityMutExcept<'_, '_, B> {
fn eq(&self, other: &Self) -> bool {
self.entity() == other.entity()
}
}
impl<B: Bundle> Eq for EntityMutExcept<'_, '_, B> {}
impl<B: Bundle> PartialOrd for EntityMutExcept<'_, '_, B> {
/// [`EntityMutExcept`]'s comparison trait implementations match the underlying [`Entity`],
/// and cannot discern between different worlds.
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<B: Bundle> Ord for EntityMutExcept<'_, '_, B> {
fn cmp(&self, other: &Self) -> Ordering {
self.entity().cmp(&other.entity())
}
}
impl<B: Bundle> Hash for EntityMutExcept<'_, '_, B> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.entity().hash(state);
}
}
impl<B: Bundle> ContainsEntity for EntityMutExcept<'_, '_, B> {
fn entity(&self) -> Entity {
self.id()
}
}
// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
unsafe impl<B: Bundle> EntityEquivalent for EntityMutExcept<'_, '_, B> {}
fn bundle_contains_component<B>(components: &Components, query_id: ComponentId) -> bool
where
B: Bundle,
{
let mut found = false;
for id in B::get_component_ids(components).flatten() {
found = found || id == query_id;
}
found
}
| 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/world/entity_access/filtered.rs | crates/bevy_ecs/src/world/entity_access/filtered.rs | use crate::{
archetype::Archetype,
change_detection::{ComponentTicks, MaybeLocation, MutUntyped, Tick},
component::{Component, ComponentId, Mutable},
entity::{ContainsEntity, Entity, EntityEquivalent, EntityLocation},
query::Access,
world::{unsafe_world_cell::UnsafeEntityCell, EntityMut, EntityRef, Mut, Ref},
};
use bevy_ptr::Ptr;
use core::{
any::TypeId,
cmp::Ordering,
hash::{Hash, Hasher},
};
use thiserror::Error;
/// Provides read-only access to a single entity and some of its components defined by the contained [`Access`].
///
/// To define the access when used as a [`QueryData`](crate::query::QueryData),
/// use a [`QueryBuilder`](crate::query::QueryBuilder) or [`QueryParamBuilder`](crate::system::QueryParamBuilder).
/// The [`FilteredEntityRef`] must be the entire [`QueryData`](crate::query::QueryData), and not nested inside a tuple with other data.
///
/// ```
/// # use bevy_ecs::{prelude::*, world::FilteredEntityRef};
/// #
/// # #[derive(Component)]
/// # struct A;
/// #
/// # let mut world = World::new();
/// # world.spawn(A);
/// #
/// // This gives the `FilteredEntityRef` access to `&A`.
/// let mut query = QueryBuilder::<FilteredEntityRef>::new(&mut world)
/// .data::<&A>()
/// .build();
///
/// let filtered_entity: FilteredEntityRef = query.single(&mut world).unwrap();
/// let component: &A = filtered_entity.get().unwrap();
/// ```
#[derive(Clone, Copy)]
pub struct FilteredEntityRef<'w, 's> {
entity: UnsafeEntityCell<'w>,
access: &'s Access,
}
impl<'w, 's> FilteredEntityRef<'w, 's> {
/// # Safety
/// - No `&mut World` can exist from the underlying `UnsafeWorldCell`
/// - If `access` takes read access to a component no mutable reference to that
/// component can exist at the same time as the returned [`FilteredEntityMut`]
/// - If `access` takes any access for a component `entity` must have that component.
#[inline]
pub(crate) unsafe fn new(entity: UnsafeEntityCell<'w>, access: &'s Access) -> Self {
Self { entity, access }
}
/// Returns the [ID](Entity) of the current entity.
#[inline]
#[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
pub fn id(&self) -> Entity {
self.entity.id()
}
/// Gets metadata indicating the location where the current entity is stored.
#[inline]
pub fn location(&self) -> EntityLocation {
self.entity.location()
}
/// Returns the archetype that the current entity belongs to.
#[inline]
pub fn archetype(&self) -> &Archetype {
self.entity.archetype()
}
/// Returns a reference to the underlying [`Access`].
#[inline]
pub fn access(&self) -> &Access {
self.access
}
/// Returns `true` if the current entity has a component of type `T`.
/// Otherwise, this returns `false`.
///
/// ## Notes
///
/// If you do not know the concrete type of a component, consider using
/// [`Self::contains_id`] or [`Self::contains_type_id`].
#[inline]
pub fn contains<T: Component>(&self) -> bool {
self.contains_type_id(TypeId::of::<T>())
}
/// Returns `true` if the current entity has a component identified by `component_id`.
/// Otherwise, this returns false.
///
/// ## Notes
///
/// - If you know the concrete type of the component, you should prefer [`Self::contains`].
/// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
/// [`Self::contains_type_id`].
#[inline]
pub fn contains_id(&self, component_id: ComponentId) -> bool {
self.entity.contains_id(component_id)
}
/// Returns `true` if the current entity has a component with the type identified by `type_id`.
/// Otherwise, this returns false.
///
/// ## Notes
///
/// - If you know the concrete type of the component, you should prefer [`Self::contains`].
/// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
#[inline]
pub fn contains_type_id(&self, type_id: TypeId) -> bool {
self.entity.contains_type_id(type_id)
}
/// Gets access to the component of type `T` for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
#[inline]
pub fn get<T: Component>(&self) -> Option<&'w T> {
let id = self
.entity
.world()
.components()
.get_valid_id(TypeId::of::<T>())?;
self.access
.has_component_read(id)
// SAFETY: We have read access
.then(|| unsafe { self.entity.get() })
.flatten()
}
/// Gets access to the component of type `T` for the current entity,
/// including change detection information as a [`Ref`].
///
/// Returns `None` if the entity does not have a component of type `T`.
#[inline]
pub fn get_ref<T: Component>(&self) -> Option<Ref<'w, T>> {
let id = self
.entity
.world()
.components()
.get_valid_id(TypeId::of::<T>())?;
self.access
.has_component_read(id)
// SAFETY: We have read access
.then(|| unsafe { self.entity.get_ref() })
.flatten()
}
/// Retrieves the change ticks for the given component. This can be useful for implementing change
/// detection in custom runtimes.
#[inline]
pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
let id = self
.entity
.world()
.components()
.get_valid_id(TypeId::of::<T>())?;
self.access
.has_component_read(id)
// SAFETY: We have read access
.then(|| unsafe { self.entity.get_change_ticks::<T>() })
.flatten()
}
/// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
/// detection in custom runtimes.
///
/// **You should prefer to use the typed API [`Self::get_change_ticks`] where possible and only
/// use this in cases where the actual component types are not known at
/// compile time.**
#[inline]
pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
self.access
.has_component_read(component_id)
// SAFETY: We have read access
.then(|| unsafe { self.entity.get_change_ticks_by_id(component_id) })
.flatten()
}
/// Gets the component of the given [`ComponentId`] from the entity.
///
/// **You should prefer to use the typed API [`Self::get`] where possible and only
/// use this in cases where the actual component types are not known at
/// compile time.**
///
/// Unlike [`FilteredEntityRef::get`], this returns a raw pointer to the component,
/// which is only valid while the [`FilteredEntityRef`] is alive.
#[inline]
pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'w>> {
self.access
.has_component_read(component_id)
// SAFETY: We have read access
.then(|| unsafe { self.entity.get_by_id(component_id) })
.flatten()
}
/// Returns the source code location from which this entity has been spawned.
pub fn spawned_by(&self) -> MaybeLocation {
self.entity.spawned_by()
}
/// Returns the [`Tick`] at which this entity has been spawned.
pub fn spawn_tick(&self) -> Tick {
self.entity.spawn_tick()
}
}
impl<'a> TryFrom<FilteredEntityRef<'a, '_>> for EntityRef<'a> {
type Error = TryFromFilteredError;
fn try_from(entity: FilteredEntityRef<'a, '_>) -> Result<Self, Self::Error> {
if !entity.access.has_read_all() {
Err(TryFromFilteredError::MissingReadAllAccess)
} else {
// SAFETY: check above guarantees read-only access to all components of the entity.
Ok(unsafe { EntityRef::new(entity.entity) })
}
}
}
impl<'a> TryFrom<&'a FilteredEntityRef<'_, '_>> for EntityRef<'a> {
type Error = TryFromFilteredError;
fn try_from(entity: &'a FilteredEntityRef<'_, '_>) -> Result<Self, Self::Error> {
if !entity.access.has_read_all() {
Err(TryFromFilteredError::MissingReadAllAccess)
} else {
// SAFETY: check above guarantees read-only access to all components of the entity.
Ok(unsafe { EntityRef::new(entity.entity) })
}
}
}
impl PartialEq for FilteredEntityRef<'_, '_> {
fn eq(&self, other: &Self) -> bool {
self.entity() == other.entity()
}
}
impl Eq for FilteredEntityRef<'_, '_> {}
impl PartialOrd for FilteredEntityRef<'_, '_> {
/// [`FilteredEntityRef`]'s comparison trait implementations match the underlying [`Entity`],
/// and cannot discern between different worlds.
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for FilteredEntityRef<'_, '_> {
fn cmp(&self, other: &Self) -> Ordering {
self.entity().cmp(&other.entity())
}
}
impl Hash for FilteredEntityRef<'_, '_> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.entity().hash(state);
}
}
impl ContainsEntity for FilteredEntityRef<'_, '_> {
fn entity(&self) -> Entity {
self.id()
}
}
// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
unsafe impl EntityEquivalent for FilteredEntityRef<'_, '_> {}
/// Variant of [`FilteredEntityMut`] that can be used to create copies of a [`FilteredEntityMut`], as long
/// as the user ensures that these won't cause aliasing violations.
///
/// This can be useful to mutably query multiple components from a single `FilteredEntityMut`.
///
/// ### Example Usage
///
/// ```
/// # use bevy_ecs::{prelude::*, world::{FilteredEntityMut, UnsafeFilteredEntityMut}};
/// #
/// # #[derive(Component)]
/// # struct A;
/// # #[derive(Component)]
/// # struct B;
/// #
/// # let mut world = World::new();
/// # world.spawn((A, B));
/// #
/// // This gives the `FilteredEntityMut` access to `&mut A` and `&mut B`.
/// let mut query = QueryBuilder::<FilteredEntityMut>::new(&mut world)
/// .data::<(&mut A, &mut B)>()
/// .build();
///
/// let mut filtered_entity: FilteredEntityMut = query.single_mut(&mut world).unwrap();
/// let unsafe_filtered_entity = UnsafeFilteredEntityMut::new_readonly(&filtered_entity);
/// // SAFETY: the original FilteredEntityMut accesses `&mut A` and the clone accesses `&mut B`, so no aliasing violations occur.
/// let mut filtered_entity_clone: FilteredEntityMut = unsafe { unsafe_filtered_entity.into_mut() };
/// let a: Mut<A> = filtered_entity.get_mut().unwrap();
/// let b: Mut<B> = filtered_entity_clone.get_mut().unwrap();
/// ```
#[derive(Copy, Clone)]
pub struct UnsafeFilteredEntityMut<'w, 's> {
entity: UnsafeEntityCell<'w>,
access: &'s Access,
}
impl<'w, 's> UnsafeFilteredEntityMut<'w, 's> {
/// Creates a [`UnsafeFilteredEntityMut`] that can be used to have multiple concurrent [`FilteredEntityMut`]s.
#[inline]
pub fn new_readonly(filtered_entity_mut: &FilteredEntityMut<'w, 's>) -> Self {
Self {
entity: filtered_entity_mut.entity,
access: filtered_entity_mut.access,
}
}
/// Returns a new instance of [`FilteredEntityMut`].
///
/// # Safety
/// - The user must ensure that no aliasing violations occur when using the returned `FilteredEntityMut`.
#[inline]
pub unsafe fn into_mut(self) -> FilteredEntityMut<'w, 's> {
// SAFETY: Upheld by caller.
unsafe { FilteredEntityMut::new(self.entity, self.access) }
}
}
/// Provides mutable access to a single entity and some of its components defined by the contained [`Access`].
///
/// To define the access when used as a [`QueryData`](crate::query::QueryData),
/// use a [`QueryBuilder`](crate::query::QueryBuilder) or [`QueryParamBuilder`](crate::system::QueryParamBuilder).
/// The `FilteredEntityMut` must be the entire `QueryData`, and not nested inside a tuple with other data.
///
/// ```
/// # use bevy_ecs::{prelude::*, world::FilteredEntityMut};
/// #
/// # #[derive(Component)]
/// # struct A;
/// #
/// # let mut world = World::new();
/// # world.spawn(A);
/// #
/// // This gives the `FilteredEntityMut` access to `&mut A`.
/// let mut query = QueryBuilder::<FilteredEntityMut>::new(&mut world)
/// .data::<&mut A>()
/// .build();
///
/// let mut filtered_entity: FilteredEntityMut = query.single_mut(&mut world).unwrap();
/// let component: Mut<A> = filtered_entity.get_mut().unwrap();
/// ```
///
/// Also see [`UnsafeFilteredEntityMut`] for a way to bypass borrow-checker restrictions.
pub struct FilteredEntityMut<'w, 's> {
entity: UnsafeEntityCell<'w>,
access: &'s Access,
}
impl<'w, 's> FilteredEntityMut<'w, 's> {
/// # Safety
/// - No `&mut World` can exist from the underlying `UnsafeWorldCell`
/// - If `access` takes read access to a component no mutable reference to that
/// component can exist at the same time as the returned [`FilteredEntityMut`]
/// - If `access` takes write access to a component, no reference to that component
/// may exist at the same time as the returned [`FilteredEntityMut`]
/// - If `access` takes any access for a component `entity` must have that component.
#[inline]
pub(crate) unsafe fn new(entity: UnsafeEntityCell<'w>, access: &'s Access) -> Self {
Self { entity, access }
}
/// Returns a new instance with a shorter lifetime.
/// This is useful if you have `&mut FilteredEntityMut`, but you need `FilteredEntityMut`.
pub fn reborrow(&mut self) -> FilteredEntityMut<'_, 's> {
// SAFETY: We have exclusive access to the entire entity and its components.
unsafe { Self::new(self.entity, self.access) }
}
/// Gets read-only access to all of the entity's components.
#[inline]
pub fn as_readonly(&self) -> FilteredEntityRef<'_, 's> {
FilteredEntityRef::from(self)
}
/// Get access to the underlying [`UnsafeEntityCell`]
pub fn as_unsafe_entity_cell(&mut self) -> UnsafeEntityCell<'_> {
self.entity
}
/// Returns the [ID](Entity) of the current entity.
#[inline]
#[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
pub fn id(&self) -> Entity {
self.entity.id()
}
/// Gets metadata indicating the location where the current entity is stored.
#[inline]
pub fn location(&self) -> EntityLocation {
self.entity.location()
}
/// Returns the archetype that the current entity belongs to.
#[inline]
pub fn archetype(&self) -> &Archetype {
self.entity.archetype()
}
/// Returns a reference to the underlying [`Access`].
#[inline]
pub fn access(&self) -> &Access {
self.access
}
/// Returns `true` if the current entity has a component of type `T`.
/// Otherwise, this returns `false`.
///
/// ## Notes
///
/// If you do not know the concrete type of a component, consider using
/// [`Self::contains_id`] or [`Self::contains_type_id`].
#[inline]
pub fn contains<T: Component>(&self) -> bool {
self.contains_type_id(TypeId::of::<T>())
}
/// Returns `true` if the current entity has a component identified by `component_id`.
/// Otherwise, this returns false.
///
/// ## Notes
///
/// - If you know the concrete type of the component, you should prefer [`Self::contains`].
/// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
/// [`Self::contains_type_id`].
#[inline]
pub fn contains_id(&self, component_id: ComponentId) -> bool {
self.entity.contains_id(component_id)
}
/// Returns `true` if the current entity has a component with the type identified by `type_id`.
/// Otherwise, this returns false.
///
/// ## Notes
///
/// - If you know the concrete type of the component, you should prefer [`Self::contains`].
/// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
#[inline]
pub fn contains_type_id(&self, type_id: TypeId) -> bool {
self.entity.contains_type_id(type_id)
}
/// Gets access to the component of type `T` for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
#[inline]
pub fn get<T: Component>(&self) -> Option<&'_ T> {
self.as_readonly().get()
}
/// Gets access to the component of type `T` for the current entity,
/// including change detection information as a [`Ref`].
///
/// Returns `None` if the entity does not have a component of type `T`.
#[inline]
pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
self.as_readonly().get_ref()
}
/// Gets mutable access to the component of type `T` for the current entity.
/// Returns `None` if the entity does not have a component of type `T` or if
/// the access does not include write access to `T`.
#[inline]
pub fn get_mut<T: Component<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, T>> {
// SAFETY: we use a mutable reference to self, so we cannot use the `FilteredEntityMut` to access
// another component
unsafe { self.get_mut_unchecked() }
}
/// Gets mutable access to the component of type `T` for the current entity.
/// Returns `None` if the entity does not have a component of type `T` or if
/// the access does not include write access to `T`.
///
/// This only requires `&self`, and so may be used to get mutable access to multiple components.
///
/// # Example
///
/// ```
/// # use bevy_ecs::{prelude::*, world::FilteredEntityMut};
/// #
/// #[derive(Component)]
/// struct X(usize);
/// #[derive(Component)]
/// struct Y(usize);
///
/// # let mut world = World::default();
/// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
///
/// // This gives the `FilteredEntityMut` access to `&mut X` and `&mut Y`.
/// let mut query = QueryBuilder::<FilteredEntityMut>::new(&mut world)
/// .data::<(&mut X, &mut Y)>()
/// .build();
///
/// let mut filtered_entity: FilteredEntityMut = query.single_mut(&mut world).unwrap();
///
/// // Get mutable access to two components at once
/// // SAFETY: We don't take any other references to `X` from this entity
/// let mut x = unsafe { filtered_entity.get_mut_unchecked::<X>() }.unwrap();
/// // SAFETY: We don't take any other references to `Y` from this entity
/// let mut y = unsafe { filtered_entity.get_mut_unchecked::<Y>() }.unwrap();
/// *x = X(1);
/// *y = Y(1);
/// ```
///
/// # Safety
///
/// No other references to the same component may exist at the same time as the returned reference.
///
/// # See also
///
/// - [`get_mut`](Self::get_mut) for the safe version.
#[inline]
pub unsafe fn get_mut_unchecked<T: Component<Mutability = Mutable>>(
&self,
) -> Option<Mut<'_, T>> {
let id = self
.entity
.world()
.components()
.get_valid_id(TypeId::of::<T>())?;
self.access
.has_component_write(id)
// SAFETY: We have permission to access the component mutable
// and we promise to not create other references to the same component
.then(|| unsafe { self.entity.get_mut() })
.flatten()
}
/// Consumes self and gets mutable access to the component of type `T`
/// with the world `'w` lifetime for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
#[inline]
pub fn into_mut<T: Component<Mutability = Mutable>>(self) -> Option<Mut<'w, T>> {
// SAFETY:
// - We have write access
// - The bound `T: Component<Mutability = Mutable>` ensures the component is mutable
unsafe { self.into_mut_assume_mutable() }
}
/// Consumes self and gets mutable access to the component of type `T`
/// with the world `'w` lifetime for the current entity.
/// Returns `None` if the entity does not have a component of type `T`.
///
/// # Safety
///
/// - `T` must be a mutable component
#[inline]
pub unsafe fn into_mut_assume_mutable<T: Component>(self) -> Option<Mut<'w, T>> {
let id = self
.entity
.world()
.components()
.get_valid_id(TypeId::of::<T>())?;
self.access
.has_component_write(id)
// SAFETY:
// - We have write access
// - Caller ensures `T` is a mutable component
.then(|| unsafe { self.entity.get_mut_assume_mutable() })
.flatten()
}
/// Retrieves the change ticks for the given component. This can be useful for implementing change
/// detection in custom runtimes.
#[inline]
pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
self.as_readonly().get_change_ticks::<T>()
}
/// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
/// detection in custom runtimes.
///
/// **You should prefer to use the typed API [`Self::get_change_ticks`] where possible and only
/// use this in cases where the actual component types are not known at
/// compile time.**
#[inline]
pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
self.as_readonly().get_change_ticks_by_id(component_id)
}
/// Gets the component of the given [`ComponentId`] from the entity.
///
/// **You should prefer to use the typed API [`Self::get`] where possible and only
/// use this in cases where the actual component types are not known at
/// compile time.**
///
/// Unlike [`FilteredEntityMut::get`], this returns a raw pointer to the component,
/// which is only valid while the [`FilteredEntityMut`] is alive.
#[inline]
pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
self.as_readonly().get_by_id(component_id)
}
/// Gets a [`MutUntyped`] of the component of the given [`ComponentId`] from the entity.
///
/// **You should prefer to use the typed API [`Self::get_mut`] where possible and only
/// use this in cases where the actual component types are not known at
/// compile time.**
///
/// Unlike [`FilteredEntityMut::get_mut`], this returns a raw pointer to the component,
/// which is only valid while the [`FilteredEntityMut`] is alive.
#[inline]
pub fn get_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
// SAFETY: we use a mutable reference to self, so we cannot use the `FilteredEntityMut` to access
// another component
unsafe { self.get_mut_by_id_unchecked(component_id) }
}
/// Gets a [`MutUntyped`] of the component of the given [`ComponentId`] from the entity.
///
/// **You should prefer to use the typed API [`Self::get_mut`] where possible and only
/// use this in cases where the actual component types are not known at
/// compile time.**
///
/// Unlike [`FilteredEntityMut::get_mut`], this returns a raw pointer to the component,
/// which is only valid while the [`FilteredEntityMut`] is alive.
///
/// This only requires `&self`, and so may be used to get mutable access to multiple components.
///
/// # Safety
///
/// No other references to the same component may exist at the same time as the returned reference.
///
/// # See also
///
/// - [`get_mut_by_id`](Self::get_mut_by_id) for the safe version.
#[inline]
pub unsafe fn get_mut_by_id_unchecked(
&self,
component_id: ComponentId,
) -> Option<MutUntyped<'_>> {
self.access
.has_component_write(component_id)
// SAFETY: We have permission to access the component mutable
// and we promise to not create other references to the same component
.then(|| unsafe { self.entity.get_mut_by_id(component_id).ok() })
.flatten()
}
/// Returns the source code location from which this entity has last been spawned.
pub fn spawned_by(&self) -> MaybeLocation {
self.entity.spawned_by()
}
/// Returns the [`Tick`] at which this entity has been spawned.
pub fn spawn_tick(&self) -> Tick {
self.entity.spawn_tick()
}
}
impl<'a> TryFrom<FilteredEntityMut<'a, '_>> for EntityRef<'a> {
type Error = TryFromFilteredError;
fn try_from(entity: FilteredEntityMut<'a, '_>) -> Result<Self, Self::Error> {
if !entity.access.has_read_all() {
Err(TryFromFilteredError::MissingReadAllAccess)
} else {
// SAFETY: check above guarantees read-only access to all components of the entity.
Ok(unsafe { EntityRef::new(entity.entity) })
}
}
}
impl<'a> TryFrom<&'a FilteredEntityMut<'_, '_>> for EntityRef<'a> {
type Error = TryFromFilteredError;
fn try_from(entity: &'a FilteredEntityMut<'_, '_>) -> Result<Self, Self::Error> {
if !entity.access.has_read_all() {
Err(TryFromFilteredError::MissingReadAllAccess)
} else {
// SAFETY: check above guarantees read-only access to all components of the entity.
Ok(unsafe { EntityRef::new(entity.entity) })
}
}
}
impl<'a> TryFrom<FilteredEntityMut<'a, '_>> for EntityMut<'a> {
type Error = TryFromFilteredError;
fn try_from(entity: FilteredEntityMut<'a, '_>) -> Result<Self, Self::Error> {
if !entity.access.has_read_all() {
Err(TryFromFilteredError::MissingReadAllAccess)
} else if !entity.access.has_write_all() {
Err(TryFromFilteredError::MissingWriteAllAccess)
} else {
// SAFETY: check above guarantees exclusive access to all components of the entity.
Ok(unsafe { EntityMut::new(entity.entity) })
}
}
}
impl<'a> TryFrom<&'a mut FilteredEntityMut<'_, '_>> for EntityMut<'a> {
type Error = TryFromFilteredError;
fn try_from(entity: &'a mut FilteredEntityMut<'_, '_>) -> Result<Self, Self::Error> {
if !entity.access.has_read_all() {
Err(TryFromFilteredError::MissingReadAllAccess)
} else if !entity.access.has_write_all() {
Err(TryFromFilteredError::MissingWriteAllAccess)
} else {
// SAFETY: check above guarantees exclusive access to all components of the entity.
Ok(unsafe { EntityMut::new(entity.entity) })
}
}
}
impl<'w, 's> From<FilteredEntityMut<'w, 's>> for FilteredEntityRef<'w, 's> {
#[inline]
fn from(entity: FilteredEntityMut<'w, 's>) -> Self {
// SAFETY:
// - `FilteredEntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
unsafe { FilteredEntityRef::new(entity.entity, entity.access) }
}
}
impl<'w, 's> From<&'w FilteredEntityMut<'_, 's>> for FilteredEntityRef<'w, 's> {
#[inline]
fn from(entity: &'w FilteredEntityMut<'_, 's>) -> Self {
// SAFETY:
// - `FilteredEntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
unsafe { FilteredEntityRef::new(entity.entity, entity.access) }
}
}
impl PartialEq for FilteredEntityMut<'_, '_> {
fn eq(&self, other: &Self) -> bool {
self.entity() == other.entity()
}
}
impl Eq for FilteredEntityMut<'_, '_> {}
impl PartialOrd for FilteredEntityMut<'_, '_> {
/// [`FilteredEntityMut`]'s comparison trait implementations match the underlying [`Entity`],
/// and cannot discern between different worlds.
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for FilteredEntityMut<'_, '_> {
fn cmp(&self, other: &Self) -> Ordering {
self.entity().cmp(&other.entity())
}
}
impl Hash for FilteredEntityMut<'_, '_> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.entity().hash(state);
}
}
impl ContainsEntity for FilteredEntityMut<'_, '_> {
fn entity(&self) -> Entity {
self.id()
}
}
// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
unsafe impl EntityEquivalent for FilteredEntityMut<'_, '_> {}
/// Error type returned by [`TryFrom`] conversions from filtered entity types
/// ([`FilteredEntityRef`]/[`FilteredEntityMut`]) to full-access entity types
/// ([`EntityRef`]/[`EntityMut`]).
#[derive(Error, Debug)]
pub enum TryFromFilteredError {
/// Error indicating that the filtered entity does not have read access to
/// all components.
#[error("Conversion failed, filtered entity ref does not have read access to all components")]
MissingReadAllAccess,
/// Error indicating that the filtered entity does not have write access to
/// all components.
#[error("Conversion failed, filtered entity ref does not have write access to all components")]
MissingWriteAllAccess,
}
| 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/world/entity_access/mod.rs | crates/bevy_ecs/src/world/entity_access/mod.rs | mod component_fetch;
mod entity_mut;
mod entity_ref;
mod entry;
mod except;
mod filtered;
mod world_mut;
pub use component_fetch::*;
pub use entity_mut::*;
pub use entity_ref::*;
pub use entry::*;
pub use except::*;
pub use filtered::*;
pub use world_mut::*;
#[cfg(test)]
mod tests {
use alloc::{vec, vec::Vec};
use bevy_ptr::{OwningPtr, Ptr};
use core::panic::AssertUnwindSafe;
use std::sync::OnceLock;
use crate::change_detection::Tick;
use crate::lifecycle::HookContext;
use crate::query::QueryAccessError;
use crate::{
change_detection::{MaybeLocation, MutUntyped},
component::ComponentId,
prelude::*,
system::{assert_is_system, RunSystemOnce as _},
world::{error::EntityComponentError, DeferredWorld, FilteredEntityMut, FilteredEntityRef},
};
use super::{EntityMutExcept, EntityRefExcept};
#[derive(Component, Clone, Copy, Debug, PartialEq)]
struct TestComponent(u32);
#[derive(Component, Clone, Copy, Debug, PartialEq)]
#[component(storage = "SparseSet")]
struct TestComponent2(u32);
#[derive(Component)]
struct Marker;
#[test]
fn entity_ref_get_by_id() {
let mut world = World::new();
let entity = world.spawn(TestComponent(42)).id();
let component_id = world
.components()
.get_valid_id(core::any::TypeId::of::<TestComponent>())
.unwrap();
let entity = world.entity(entity);
let test_component = entity.get_by_id(component_id).unwrap();
// SAFETY: points to a valid `TestComponent`
let test_component = unsafe { test_component.deref::<TestComponent>() };
assert_eq!(test_component.0, 42);
}
#[test]
fn entity_mut_get_by_id() {
let mut world = World::new();
let entity = world.spawn(TestComponent(42)).id();
let component_id = world
.components()
.get_valid_id(core::any::TypeId::of::<TestComponent>())
.unwrap();
let mut entity_mut = world.entity_mut(entity);
let mut test_component = entity_mut.get_mut_by_id(component_id).unwrap();
{
test_component.set_changed();
let test_component =
// SAFETY: `test_component` has unique access of the `EntityWorldMut` and is not used afterwards
unsafe { test_component.into_inner().deref_mut::<TestComponent>() };
test_component.0 = 43;
}
let entity = world.entity(entity);
let test_component = entity.get_by_id(component_id).unwrap();
// SAFETY: `TestComponent` is the correct component type
let test_component = unsafe { test_component.deref::<TestComponent>() };
assert_eq!(test_component.0, 43);
}
#[test]
fn entity_ref_get_by_id_invalid_component_id() {
let invalid_component_id = ComponentId::new(usize::MAX);
let mut world = World::new();
let entity = world.spawn_empty().id();
let entity = world.entity(entity);
assert!(entity.get_by_id(invalid_component_id).is_err());
}
#[test]
fn entity_mut_get_by_id_invalid_component_id() {
let invalid_component_id = ComponentId::new(usize::MAX);
let mut world = World::new();
let mut entity = world.spawn_empty();
assert!(entity.get_by_id(invalid_component_id).is_err());
assert!(entity.get_mut_by_id(invalid_component_id).is_err());
}
#[derive(Resource)]
struct R(usize);
#[test]
fn entity_mut_resource_scope() {
// Keep in sync with the `resource_scope` test in lib.rs
let mut world = World::new();
let mut entity = world.spawn_empty();
assert!(entity.try_resource_scope::<R, _>(|_, _| {}).is_none());
entity.world_scope(|world| world.insert_resource(R(0)));
entity.resource_scope(|entity: &mut EntityWorldMut, mut value: Mut<R>| {
value.0 += 1;
assert!(!entity.world().contains_resource::<R>());
});
assert_eq!(entity.resource::<R>().0, 1);
}
#[test]
fn entity_mut_resource_scope_panic() {
let mut world = World::new();
world.insert_resource(R(0));
let mut entity = world.spawn_empty();
let old_location = entity.location();
let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
entity.resource_scope(|entity: &mut EntityWorldMut, _: Mut<R>| {
// Change the entity's `EntityLocation`.
entity.insert(TestComponent(0));
// Ensure that the entity location still gets updated even in case of a panic.
panic!("this should get caught by the outer scope")
});
}));
assert!(result.is_err());
// Ensure that the location has been properly updated.
assert_ne!(entity.location(), old_location);
}
// regression test for https://github.com/bevyengine/bevy/pull/7387
#[test]
fn entity_mut_world_scope_panic() {
let mut world = World::new();
let mut entity = world.spawn_empty();
let old_location = entity.location();
let id = entity.id();
let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
entity.world_scope(|w| {
// Change the entity's `EntityLocation`, which invalidates the original `EntityWorldMut`.
// This will get updated at the end of the scope.
w.entity_mut(id).insert(TestComponent(0));
// Ensure that the entity location still gets updated even in case of a panic.
panic!("this should get caught by the outer scope")
});
}));
assert!(res.is_err());
// Ensure that the location has been properly updated.
assert_ne!(entity.location(), old_location);
}
#[test]
fn entity_mut_reborrow_scope_panic() {
let mut world = World::new();
let mut entity = world.spawn_empty();
let old_location = entity.location();
let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
entity.reborrow_scope(|mut entity| {
// Change the entity's `EntityLocation`, which invalidates the original `EntityWorldMut`.
// This will get updated at the end of the scope.
entity.insert(TestComponent(0));
// Ensure that the entity location still gets updated even in case of a panic.
panic!("this should get caught by the outer scope")
});
}));
assert!(res.is_err());
// Ensure that the location has been properly updated.
assert_ne!(entity.location(), old_location);
}
// regression test for https://github.com/bevyengine/bevy/pull/7805
#[test]
fn removing_sparse_updates_archetype_row() {
#[derive(Component, PartialEq, Debug)]
struct Dense(u8);
#[derive(Component)]
#[component(storage = "SparseSet")]
struct Sparse;
let mut world = World::new();
let e1 = world.spawn((Dense(0), Sparse)).id();
let e2 = world.spawn((Dense(1), Sparse)).id();
world.entity_mut(e1).remove::<Sparse>();
assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
}
// regression test for https://github.com/bevyengine/bevy/pull/7805
#[test]
fn removing_dense_updates_table_row() {
#[derive(Component, PartialEq, Debug)]
struct Dense(u8);
#[derive(Component)]
#[component(storage = "SparseSet")]
struct Sparse;
let mut world = World::new();
let e1 = world.spawn((Dense(0), Sparse)).id();
let e2 = world.spawn((Dense(1), Sparse)).id();
world.entity_mut(e1).remove::<Dense>();
assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
}
// Test that calling retain with `()` removes all components.
#[test]
fn retain_nothing() {
#[derive(Component)]
struct Marker<const N: usize>;
let mut world = World::new();
let ent = world.spawn((Marker::<1>, Marker::<2>, Marker::<3>)).id();
world.entity_mut(ent).retain::<()>();
assert_eq!(world.entity(ent).archetype().components().len(), 0);
}
// Test removing some components with `retain`, including components not on the entity.
#[test]
fn retain_some_components() {
#[derive(Component)]
struct Marker<const N: usize>;
let mut world = World::new();
let ent = world.spawn((Marker::<1>, Marker::<2>, Marker::<3>)).id();
world.entity_mut(ent).retain::<(Marker<2>, Marker<4>)>();
// Check that marker 2 was retained.
assert!(world.entity(ent).get::<Marker<2>>().is_some());
// Check that only marker 2 was retained.
assert_eq!(world.entity(ent).archetype().components().len(), 1);
}
// regression test for https://github.com/bevyengine/bevy/pull/7805
#[test]
fn inserting_sparse_updates_archetype_row() {
#[derive(Component, PartialEq, Debug)]
struct Dense(u8);
#[derive(Component)]
#[component(storage = "SparseSet")]
struct Sparse;
let mut world = World::new();
let e1 = world.spawn(Dense(0)).id();
let e2 = world.spawn(Dense(1)).id();
world.entity_mut(e1).insert(Sparse);
assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
}
// regression test for https://github.com/bevyengine/bevy/pull/7805
#[test]
fn inserting_dense_updates_archetype_row() {
#[derive(Component, PartialEq, Debug)]
struct Dense(u8);
#[derive(Component)]
struct Dense2;
#[derive(Component)]
#[component(storage = "SparseSet")]
struct Sparse;
let mut world = World::new();
let e1 = world.spawn(Dense(0)).id();
let e2 = world.spawn(Dense(1)).id();
world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
// archetype with [e2, e1]
// table with [e1, e2]
world.entity_mut(e2).insert(Dense2);
assert_eq!(world.entity(e1).get::<Dense>().unwrap(), &Dense(0));
}
#[test]
fn inserting_dense_updates_table_row() {
#[derive(Component, PartialEq, Debug)]
struct Dense(u8);
#[derive(Component)]
struct Dense2;
#[derive(Component)]
#[component(storage = "SparseSet")]
struct Sparse;
let mut world = World::new();
let e1 = world.spawn(Dense(0)).id();
let e2 = world.spawn(Dense(1)).id();
world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
// archetype with [e2, e1]
// table with [e1, e2]
world.entity_mut(e1).insert(Dense2);
assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
}
// regression test for https://github.com/bevyengine/bevy/pull/7805
#[test]
fn despawning_entity_updates_archetype_row() {
#[derive(Component, PartialEq, Debug)]
struct Dense(u8);
#[derive(Component)]
#[component(storage = "SparseSet")]
struct Sparse;
let mut world = World::new();
let e1 = world.spawn(Dense(0)).id();
let e2 = world.spawn(Dense(1)).id();
world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
// archetype with [e2, e1]
// table with [e1, e2]
world.entity_mut(e2).despawn();
assert_eq!(world.entity(e1).get::<Dense>().unwrap(), &Dense(0));
}
// regression test for https://github.com/bevyengine/bevy/pull/7805
#[test]
fn despawning_entity_updates_table_row() {
#[derive(Component, PartialEq, Debug)]
struct Dense(u8);
#[derive(Component)]
#[component(storage = "SparseSet")]
struct Sparse;
let mut world = World::new();
let e1 = world.spawn(Dense(0)).id();
let e2 = world.spawn(Dense(1)).id();
world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
// archetype with [e2, e1]
// table with [e1, e2]
world.entity_mut(e1).despawn();
assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
}
#[test]
fn entity_mut_insert_by_id() {
let mut world = World::new();
let test_component_id = world.register_component::<TestComponent>();
let mut entity = world.spawn_empty();
OwningPtr::make(TestComponent(42), |ptr| {
// SAFETY: `ptr` matches the component id
unsafe { entity.insert_by_id(test_component_id, ptr) };
});
let components: Vec<_> = world.query::<&TestComponent>().iter(&world).collect();
assert_eq!(components, vec![&TestComponent(42)]);
// Compare with `insert_bundle_by_id`
let mut entity = world.spawn_empty();
OwningPtr::make(TestComponent(84), |ptr| {
// SAFETY: `ptr` matches the component id
unsafe { entity.insert_by_ids(&[test_component_id], vec![ptr].into_iter()) };
});
let components: Vec<_> = world.query::<&TestComponent>().iter(&world).collect();
assert_eq!(components, vec![&TestComponent(42), &TestComponent(84)]);
}
#[test]
fn entity_mut_insert_bundle_by_id() {
let mut world = World::new();
let test_component_id = world.register_component::<TestComponent>();
let test_component_2_id = world.register_component::<TestComponent2>();
let component_ids = [test_component_id, test_component_2_id];
let test_component_value = TestComponent(42);
let test_component_2_value = TestComponent2(84);
let mut entity = world.spawn_empty();
OwningPtr::make(test_component_value, |ptr1| {
OwningPtr::make(test_component_2_value, |ptr2| {
// SAFETY: `ptr1` and `ptr2` match the component ids
unsafe { entity.insert_by_ids(&component_ids, vec![ptr1, ptr2].into_iter()) };
});
});
let dynamic_components: Vec<_> = world
.query::<(&TestComponent, &TestComponent2)>()
.iter(&world)
.collect();
assert_eq!(
dynamic_components,
vec![(&TestComponent(42), &TestComponent2(84))]
);
// Compare with `World` generated using static type equivalents
let mut static_world = World::new();
static_world.spawn((test_component_value, test_component_2_value));
let static_components: Vec<_> = static_world
.query::<(&TestComponent, &TestComponent2)>()
.iter(&static_world)
.collect();
assert_eq!(dynamic_components, static_components);
}
#[test]
fn entity_mut_remove_by_id() {
let mut world = World::new();
let test_component_id = world.register_component::<TestComponent>();
let mut entity = world.spawn(TestComponent(42));
entity.remove_by_id(test_component_id);
let components: Vec<_> = world.query::<&TestComponent>().iter(&world).collect();
assert_eq!(components, vec![] as Vec<&TestComponent>);
// remove non-existent component does not panic
world.spawn_empty().remove_by_id(test_component_id);
}
/// Tests that components can be accessed through an `EntityRefExcept`.
#[test]
fn entity_ref_except() {
let mut world = World::new();
world.register_component::<TestComponent>();
world.register_component::<TestComponent2>();
world.spawn((TestComponent(0), TestComponent2(0), Marker));
let mut query = world.query_filtered::<EntityRefExcept<TestComponent>, With<Marker>>();
let mut found = false;
for entity_ref in query.iter_mut(&mut world) {
found = true;
assert!(entity_ref.get::<TestComponent>().is_none());
assert!(entity_ref.get_ref::<TestComponent>().is_none());
assert!(matches!(
entity_ref.get::<TestComponent2>(),
Some(TestComponent2(0))
));
}
assert!(found);
}
// Test that a single query can't both contain a mutable reference to a
// component C and an `EntityRefExcept` that doesn't include C among its
// exclusions.
#[test]
#[should_panic]
fn entity_ref_except_conflicts_with_self() {
let mut world = World::new();
world.spawn(TestComponent(0)).insert(TestComponent2(0));
// This should panic, because we have a mutable borrow on
// `TestComponent` but have a simultaneous indirect immutable borrow on
// that component via `EntityRefExcept`.
world.run_system_once(system).unwrap();
fn system(_: Query<(&mut TestComponent, EntityRefExcept<TestComponent2>)>) {}
}
// Test that an `EntityRefExcept` that doesn't include a component C among
// its exclusions can't coexist with a mutable query for that component.
#[test]
#[should_panic]
fn entity_ref_except_conflicts_with_other() {
let mut world = World::new();
world.spawn(TestComponent(0)).insert(TestComponent2(0));
// This should panic, because we have a mutable borrow on
// `TestComponent` but have a simultaneous indirect immutable borrow on
// that component via `EntityRefExcept`.
world.run_system_once(system).unwrap();
fn system(_: Query<&mut TestComponent>, _: Query<EntityRefExcept<TestComponent2>>) {}
}
// Test that an `EntityRefExcept` with an exception for some component C can
// coexist with a query for that component C.
#[test]
fn entity_ref_except_doesnt_conflict() {
let mut world = World::new();
world.spawn((TestComponent(0), TestComponent2(0), Marker));
world.run_system_once(system).unwrap();
fn system(
_: Query<&mut TestComponent, With<Marker>>,
query: Query<EntityRefExcept<TestComponent>, With<Marker>>,
) {
for entity_ref in query.iter() {
assert!(matches!(
entity_ref.get::<TestComponent2>(),
Some(TestComponent2(0))
));
}
}
}
/// Tests that components can be mutably accessed through an
/// `EntityMutExcept`.
#[test]
fn entity_mut_except() {
let mut world = World::new();
world.spawn((TestComponent(0), TestComponent2(0), Marker));
let mut query = world.query_filtered::<EntityMutExcept<TestComponent>, With<Marker>>();
let mut found = false;
for mut entity_mut in query.iter_mut(&mut world) {
found = true;
assert!(entity_mut.get::<TestComponent>().is_none());
assert!(entity_mut.get_ref::<TestComponent>().is_none());
assert!(entity_mut.get_mut::<TestComponent>().is_none());
assert!(matches!(
entity_mut.get::<TestComponent2>(),
Some(TestComponent2(0))
));
}
assert!(found);
}
// Test that a single query can't both contain a mutable reference to a
// component C and an `EntityMutExcept` that doesn't include C among its
// exclusions.
#[test]
#[should_panic]
fn entity_mut_except_conflicts_with_self() {
let mut world = World::new();
world.spawn(TestComponent(0)).insert(TestComponent2(0));
// This should panic, because we have a mutable borrow on
// `TestComponent` but have a simultaneous indirect immutable borrow on
// that component via `EntityRefExcept`.
world.run_system_once(system).unwrap();
fn system(_: Query<(&mut TestComponent, EntityMutExcept<TestComponent2>)>) {}
}
// Test that an `EntityMutExcept` that doesn't include a component C among
// its exclusions can't coexist with a query for that component.
#[test]
#[should_panic]
fn entity_mut_except_conflicts_with_other() {
let mut world = World::new();
world.spawn(TestComponent(0)).insert(TestComponent2(0));
// This should panic, because we have a mutable borrow on
// `TestComponent` but have a simultaneous indirect immutable borrow on
// that component via `EntityRefExcept`.
world.run_system_once(system).unwrap();
fn system(_: Query<&mut TestComponent>, mut query: Query<EntityMutExcept<TestComponent2>>) {
for mut entity_mut in query.iter_mut() {
assert!(entity_mut
.get_mut::<TestComponent2>()
.is_some_and(|component| component.0 == 0));
}
}
}
// Test that an `EntityMutExcept` with an exception for some component C can
// coexist with a query for that component C.
#[test]
fn entity_mut_except_doesnt_conflict() {
let mut world = World::new();
world.spawn((TestComponent(0), TestComponent2(0), Marker));
world.run_system_once(system).unwrap();
fn system(
_: Query<&mut TestComponent, With<Marker>>,
mut query: Query<EntityMutExcept<TestComponent>, With<Marker>>,
) {
for mut entity_mut in query.iter_mut() {
assert!(entity_mut
.get_mut::<TestComponent2>()
.is_some_and(|component| component.0 == 0));
}
}
}
#[test]
fn entity_mut_except_registers_components() {
// Checks for a bug where `EntityMutExcept` would not register the component and
// would therefore not include an exception, causing it to conflict with the later query.
fn system1(_query: Query<EntityMutExcept<TestComponent>>, _: Query<&mut TestComponent>) {}
let mut world = World::new();
world.run_system_once(system1).unwrap();
fn system2(_: Query<&mut TestComponent>, _query: Query<EntityMutExcept<TestComponent>>) {}
let mut world = World::new();
world.run_system_once(system2).unwrap();
}
#[derive(Component)]
struct A;
#[test]
fn disjoint_access() {
fn disjoint_readonly(_: Query<EntityMut, With<A>>, _: Query<EntityRef, Without<A>>) {}
fn disjoint_mutable(_: Query<EntityMut, With<A>>, _: Query<EntityMut, Without<A>>) {}
assert_is_system(disjoint_readonly);
assert_is_system(disjoint_mutable);
}
#[test]
fn ref_compatible() {
fn borrow_system(_: Query<(EntityRef, &A)>, _: Query<&A>) {}
assert_is_system(borrow_system);
}
#[test]
fn ref_compatible_with_resource() {
fn borrow_system(_: Query<EntityRef>, _: Res<R>) {}
assert_is_system(borrow_system);
}
#[test]
fn ref_compatible_with_resource_mut() {
fn borrow_system(_: Query<EntityRef>, _: ResMut<R>) {}
assert_is_system(borrow_system);
}
#[test]
#[should_panic]
fn ref_incompatible_with_mutable_component() {
fn incompatible_system(_: Query<(EntityRef, &mut A)>) {}
assert_is_system(incompatible_system);
}
#[test]
#[should_panic]
fn ref_incompatible_with_mutable_query() {
fn incompatible_system(_: Query<EntityRef>, _: Query<&mut A>) {}
assert_is_system(incompatible_system);
}
#[test]
fn mut_compatible_with_entity() {
fn borrow_mut_system(_: Query<(Entity, EntityMut)>) {}
assert_is_system(borrow_mut_system);
}
#[test]
fn mut_compatible_with_resource() {
fn borrow_mut_system(_: Res<R>, _: Query<EntityMut>) {}
assert_is_system(borrow_mut_system);
}
#[test]
fn mut_compatible_with_resource_mut() {
fn borrow_mut_system(_: ResMut<R>, _: Query<EntityMut>) {}
assert_is_system(borrow_mut_system);
}
#[test]
#[should_panic]
fn mut_incompatible_with_read_only_component() {
fn incompatible_system(_: Query<(EntityMut, &A)>) {}
assert_is_system(incompatible_system);
}
#[test]
#[should_panic]
fn mut_incompatible_with_mutable_component() {
fn incompatible_system(_: Query<(EntityMut, &mut A)>) {}
assert_is_system(incompatible_system);
}
#[test]
#[should_panic]
fn mut_incompatible_with_read_only_query() {
fn incompatible_system(_: Query<EntityMut>, _: Query<&A>) {}
assert_is_system(incompatible_system);
}
#[test]
#[should_panic]
fn mut_incompatible_with_mutable_query() {
fn incompatible_system(_: Query<EntityMut>, _: Query<&mut A>) {}
assert_is_system(incompatible_system);
}
#[test]
fn filtered_entity_ref_normal() {
let mut world = World::new();
let a_id = world.register_component::<A>();
let e: FilteredEntityRef = world.spawn(A).into();
assert!(e.get::<A>().is_some());
assert!(e.get_ref::<A>().is_some());
assert!(e.get_change_ticks::<A>().is_some());
assert!(e.get_by_id(a_id).is_some());
assert!(e.get_change_ticks_by_id(a_id).is_some());
}
#[test]
fn filtered_entity_ref_missing() {
let mut world = World::new();
let a_id = world.register_component::<A>();
let e: FilteredEntityRef = world.spawn(()).into();
assert!(e.get::<A>().is_none());
assert!(e.get_ref::<A>().is_none());
assert!(e.get_change_ticks::<A>().is_none());
assert!(e.get_by_id(a_id).is_none());
assert!(e.get_change_ticks_by_id(a_id).is_none());
}
#[test]
fn filtered_entity_mut_normal() {
let mut world = World::new();
let a_id = world.register_component::<A>();
let mut e: FilteredEntityMut = world.spawn(A).into();
assert!(e.get::<A>().is_some());
assert!(e.get_ref::<A>().is_some());
assert!(e.get_mut::<A>().is_some());
assert!(e.get_change_ticks::<A>().is_some());
assert!(e.get_by_id(a_id).is_some());
assert!(e.get_mut_by_id(a_id).is_some());
assert!(e.get_change_ticks_by_id(a_id).is_some());
}
#[test]
fn filtered_entity_mut_missing() {
let mut world = World::new();
let a_id = world.register_component::<A>();
let mut e: FilteredEntityMut = world.spawn(()).into();
assert!(e.get::<A>().is_none());
assert!(e.get_ref::<A>().is_none());
assert!(e.get_mut::<A>().is_none());
assert!(e.get_change_ticks::<A>().is_none());
assert!(e.get_by_id(a_id).is_none());
assert!(e.get_mut_by_id(a_id).is_none());
assert!(e.get_change_ticks_by_id(a_id).is_none());
}
#[derive(Component, PartialEq, Eq, Debug)]
struct X(usize);
#[derive(Component, PartialEq, Eq, Debug)]
struct Y(usize);
#[test]
fn get_components() {
let mut world = World::default();
let e1 = world.spawn((X(7), Y(10))).id();
let e2 = world.spawn(X(8)).id();
let e3 = world.spawn_empty().id();
assert_eq!(
Ok((&X(7), &Y(10))),
world.entity(e1).get_components::<(&X, &Y)>()
);
assert_eq!(
Err(QueryAccessError::EntityDoesNotMatch),
world.entity(e2).get_components::<(&X, &Y)>()
);
assert_eq!(
Err(QueryAccessError::EntityDoesNotMatch),
world.entity(e3).get_components::<(&X, &Y)>()
);
}
#[test]
fn get_components_mut() {
let mut world = World::default();
let e1 = world.spawn((X(7), Y(10))).id();
let mut entity_mut_1 = world.entity_mut(e1);
let Ok((mut x, mut y)) = entity_mut_1.get_components_mut::<(&mut X, &mut Y)>() else {
panic!("could not get components");
};
x.0 += 1;
y.0 += 1;
assert_eq!(
Ok((&X(8), &Y(11))),
world.entity(e1).get_components::<(&X, &Y)>()
);
}
#[test]
fn get_by_id_array() {
let mut world = World::default();
let e1 = world.spawn((X(7), Y(10))).id();
let e2 = world.spawn(X(8)).id();
let e3 = world.spawn_empty().id();
let x_id = world.register_component::<X>();
let y_id = world.register_component::<Y>();
assert_eq!(
Ok((&X(7), &Y(10))),
world
.entity(e1)
.get_by_id([x_id, y_id])
.map(|[x_ptr, y_ptr]| {
// SAFETY: components match the id they were fetched with
(unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
})
);
assert_eq!(
Err(EntityComponentError::MissingComponent(y_id)),
world
.entity(e2)
.get_by_id([x_id, y_id])
.map(|[x_ptr, y_ptr]| {
// SAFETY: components match the id they were fetched with
(unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
})
);
assert_eq!(
Err(EntityComponentError::MissingComponent(x_id)),
world
.entity(e3)
.get_by_id([x_id, y_id])
.map(|[x_ptr, y_ptr]| {
// SAFETY: components match the id they were fetched with
(unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
})
);
}
#[test]
fn get_by_id_vec() {
let mut world = World::default();
let e1 = world.spawn((X(7), Y(10))).id();
let e2 = world.spawn(X(8)).id();
let e3 = world.spawn_empty().id();
let x_id = world.register_component::<X>();
let y_id = world.register_component::<Y>();
assert_eq!(
Ok((&X(7), &Y(10))),
world
.entity(e1)
.get_by_id(&[x_id, y_id] as &[ComponentId])
.map(|ptrs| {
let Ok([x_ptr, y_ptr]): Result<[Ptr; 2], _> = ptrs.try_into() else {
panic!("get_by_id(slice) didn't return 2 elements")
};
// SAFETY: components match the id they were fetched with
(unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
})
);
assert_eq!(
Err(EntityComponentError::MissingComponent(y_id)),
world
.entity(e2)
.get_by_id(&[x_id, y_id] as &[ComponentId])
.map(|ptrs| {
let Ok([x_ptr, y_ptr]): Result<[Ptr; 2], _> = ptrs.try_into() else {
panic!("get_by_id(slice) didn't return 2 elements")
};
// SAFETY: components match the id they were fetched with
(unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
})
);
assert_eq!(
Err(EntityComponentError::MissingComponent(x_id)),
world
.entity(e3)
.get_by_id(&[x_id, y_id] as &[ComponentId])
.map(|ptrs| {
let Ok([x_ptr, y_ptr]): Result<[Ptr; 2], _> = ptrs.try_into() else {
panic!("get_by_id(slice) didn't return 2 elements")
};
// SAFETY: components match the id they were fetched with
(unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
})
);
}
#[test]
fn get_mut_by_id_array() {
let mut world = World::default();
let e1 = world.spawn((X(7), Y(10))).id();
let e2 = world.spawn(X(8)).id();
let e3 = world.spawn_empty().id();
let x_id = world.register_component::<X>();
let y_id = world.register_component::<Y>();
assert_eq!(
Ok((&mut X(7), &mut Y(10))),
world
.entity_mut(e1)
.get_mut_by_id([x_id, y_id])
.map(|[x_ptr, y_ptr]| {
// SAFETY: components match the id they were fetched with
(unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
y_ptr.into_inner().deref_mut::<Y>()
})
})
);
assert_eq!(
Err(EntityComponentError::MissingComponent(y_id)),
world
.entity_mut(e2)
.get_mut_by_id([x_id, y_id])
.map(|[x_ptr, y_ptr]| {
// SAFETY: components match the id they were fetched with
| 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/world/entity_access/component_fetch.rs | crates/bevy_ecs/src/world/entity_access/component_fetch.rs | use crate::{
change_detection::MutUntyped,
component::ComponentId,
world::{error::EntityComponentError, unsafe_world_cell::UnsafeEntityCell},
};
use alloc::vec::Vec;
use bevy_platform::collections::{HashMap, HashSet};
use bevy_ptr::Ptr;
use core::mem::MaybeUninit;
/// Types that can be used to fetch components from an entity dynamically by
/// [`ComponentId`]s.
///
/// Provided implementations are:
/// - [`ComponentId`]: Returns a single untyped reference.
/// - `[ComponentId; N]` and `&[ComponentId; N]`: Returns a same-sized array of untyped references.
/// - `&[ComponentId]`: Returns a [`Vec`] of untyped references.
/// - [`&HashSet<ComponentId>`](HashSet): Returns a [`HashMap`] of IDs to untyped references.
///
/// # Performance
///
/// - The slice and array implementations perform an aliased mutability check in
/// [`DynamicComponentFetch::fetch_mut`] that is `O(N^2)`.
/// - The [`HashSet`] implementation performs no such check as the type itself
/// guarantees unique IDs.
/// - The single [`ComponentId`] implementation performs no such check as only
/// one reference is returned.
///
/// # Safety
///
/// Implementor must ensure that:
/// - No aliased mutability is caused by the returned references.
/// - [`DynamicComponentFetch::fetch_ref`] returns only read-only references.
pub unsafe trait DynamicComponentFetch {
/// The read-only reference type returned by [`DynamicComponentFetch::fetch_ref`].
type Ref<'w>;
/// The mutable reference type returned by [`DynamicComponentFetch::fetch_mut`].
type Mut<'w>;
/// Returns untyped read-only reference(s) to the component(s) with the
/// given [`ComponentId`]s, as determined by `self`.
///
/// # Safety
///
/// It is the caller's responsibility to ensure that:
/// - The given [`UnsafeEntityCell`] has read-only access to the fetched components.
/// - No other mutable references to the fetched components exist at the same time.
///
/// # Errors
///
/// - Returns [`EntityComponentError::MissingComponent`] if a component is missing from the entity.
unsafe fn fetch_ref(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Ref<'_>, EntityComponentError>;
/// Returns untyped mutable reference(s) to the component(s) with the
/// given [`ComponentId`]s, as determined by `self`.
///
/// # Safety
///
/// It is the caller's responsibility to ensure that:
/// - The given [`UnsafeEntityCell`] has mutable access to the fetched components.
/// - No other references to the fetched components exist at the same time.
///
/// # Errors
///
/// - Returns [`EntityComponentError::MissingComponent`] if a component is missing from the entity.
/// - Returns [`EntityComponentError::AliasedMutability`] if a component is requested multiple times.
unsafe fn fetch_mut(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Mut<'_>, EntityComponentError>;
/// Returns untyped mutable reference(s) to the component(s) with the
/// given [`ComponentId`]s, as determined by `self`.
/// Assumes all [`ComponentId`]s refer to mutable components.
///
/// # Safety
///
/// It is the caller's responsibility to ensure that:
/// - The given [`UnsafeEntityCell`] has mutable access to the fetched components.
/// - No other references to the fetched components exist at the same time.
/// - The requested components are all mutable.
///
/// # Errors
///
/// - Returns [`EntityComponentError::MissingComponent`] if a component is missing from the entity.
/// - Returns [`EntityComponentError::AliasedMutability`] if a component is requested multiple times.
unsafe fn fetch_mut_assume_mutable(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Mut<'_>, EntityComponentError>;
}
// SAFETY:
// - No aliased mutability is caused because a single reference is returned.
// - No mutable references are returned by `fetch_ref`.
unsafe impl DynamicComponentFetch for ComponentId {
type Ref<'w> = Ptr<'w>;
type Mut<'w> = MutUntyped<'w>;
unsafe fn fetch_ref(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Ref<'_>, EntityComponentError> {
// SAFETY: caller ensures that the cell has read access to the component.
unsafe { cell.get_by_id(self) }.ok_or(EntityComponentError::MissingComponent(self))
}
unsafe fn fetch_mut(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Mut<'_>, EntityComponentError> {
// SAFETY: caller ensures that the cell has mutable access to the component.
unsafe { cell.get_mut_by_id(self) }
.map_err(|_| EntityComponentError::MissingComponent(self))
}
unsafe fn fetch_mut_assume_mutable(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Mut<'_>, EntityComponentError> {
// SAFETY: caller ensures that the cell has mutable access to the component.
unsafe { cell.get_mut_assume_mutable_by_id(self) }
.map_err(|_| EntityComponentError::MissingComponent(self))
}
}
// SAFETY:
// - No aliased mutability is caused because the array is checked for duplicates.
// - No mutable references are returned by `fetch_ref`.
unsafe impl<const N: usize> DynamicComponentFetch for [ComponentId; N] {
type Ref<'w> = [Ptr<'w>; N];
type Mut<'w> = [MutUntyped<'w>; N];
unsafe fn fetch_ref(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Ref<'_>, EntityComponentError> {
// SAFETY: Uphelp by caller.
unsafe { <&Self>::fetch_ref(&self, cell) }
}
unsafe fn fetch_mut(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Mut<'_>, EntityComponentError> {
// SAFETY: Uphelp by caller.
unsafe { <&Self>::fetch_mut(&self, cell) }
}
unsafe fn fetch_mut_assume_mutable(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Mut<'_>, EntityComponentError> {
// SAFETY: Uphelp by caller.
unsafe { <&Self>::fetch_mut_assume_mutable(&self, cell) }
}
}
// SAFETY:
// - No aliased mutability is caused because the array is checked for duplicates.
// - No mutable references are returned by `fetch_ref`.
unsafe impl<const N: usize> DynamicComponentFetch for &'_ [ComponentId; N] {
type Ref<'w> = [Ptr<'w>; N];
type Mut<'w> = [MutUntyped<'w>; N];
unsafe fn fetch_ref(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Ref<'_>, EntityComponentError> {
let mut ptrs = [const { MaybeUninit::uninit() }; N];
for (ptr, &id) in core::iter::zip(&mut ptrs, self) {
*ptr = MaybeUninit::new(
// SAFETY: caller ensures that the cell has read access to the component.
unsafe { cell.get_by_id(id) }.ok_or(EntityComponentError::MissingComponent(id))?,
);
}
// SAFETY: Each ptr was initialized in the loop above.
let ptrs = ptrs.map(|ptr| unsafe { MaybeUninit::assume_init(ptr) });
Ok(ptrs)
}
unsafe fn fetch_mut(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Mut<'_>, EntityComponentError> {
// Check for duplicate component IDs.
for i in 0..self.len() {
for j in 0..i {
if self[i] == self[j] {
return Err(EntityComponentError::AliasedMutability(self[i]));
}
}
}
let mut ptrs = [const { MaybeUninit::uninit() }; N];
for (ptr, &id) in core::iter::zip(&mut ptrs, self) {
*ptr = MaybeUninit::new(
// SAFETY: caller ensures that the cell has mutable access to the component.
unsafe { cell.get_mut_by_id(id) }
.map_err(|_| EntityComponentError::MissingComponent(id))?,
);
}
// SAFETY: Each ptr was initialized in the loop above.
let ptrs = ptrs.map(|ptr| unsafe { MaybeUninit::assume_init(ptr) });
Ok(ptrs)
}
unsafe fn fetch_mut_assume_mutable(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Mut<'_>, EntityComponentError> {
// Check for duplicate component IDs.
for i in 0..self.len() {
for j in 0..i {
if self[i] == self[j] {
return Err(EntityComponentError::AliasedMutability(self[i]));
}
}
}
let mut ptrs = [const { MaybeUninit::uninit() }; N];
for (ptr, &id) in core::iter::zip(&mut ptrs, self) {
*ptr = MaybeUninit::new(
// SAFETY: caller ensures that the cell has mutable access to the component.
unsafe { cell.get_mut_assume_mutable_by_id(id) }
.map_err(|_| EntityComponentError::MissingComponent(id))?,
);
}
// SAFETY: Each ptr was initialized in the loop above.
let ptrs = ptrs.map(|ptr| unsafe { MaybeUninit::assume_init(ptr) });
Ok(ptrs)
}
}
// SAFETY:
// - No aliased mutability is caused because the slice is checked for duplicates.
// - No mutable references are returned by `fetch_ref`.
unsafe impl DynamicComponentFetch for &'_ [ComponentId] {
type Ref<'w> = Vec<Ptr<'w>>;
type Mut<'w> = Vec<MutUntyped<'w>>;
unsafe fn fetch_ref(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Ref<'_>, EntityComponentError> {
let mut ptrs = Vec::with_capacity(self.len());
for &id in self {
ptrs.push(
// SAFETY: caller ensures that the cell has read access to the component.
unsafe { cell.get_by_id(id) }.ok_or(EntityComponentError::MissingComponent(id))?,
);
}
Ok(ptrs)
}
unsafe fn fetch_mut(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Mut<'_>, EntityComponentError> {
// Check for duplicate component IDs.
for i in 0..self.len() {
for j in 0..i {
if self[i] == self[j] {
return Err(EntityComponentError::AliasedMutability(self[i]));
}
}
}
let mut ptrs = Vec::with_capacity(self.len());
for &id in self {
ptrs.push(
// SAFETY: caller ensures that the cell has mutable access to the component.
unsafe { cell.get_mut_by_id(id) }
.map_err(|_| EntityComponentError::MissingComponent(id))?,
);
}
Ok(ptrs)
}
unsafe fn fetch_mut_assume_mutable(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Mut<'_>, EntityComponentError> {
// Check for duplicate component IDs.
for i in 0..self.len() {
for j in 0..i {
if self[i] == self[j] {
return Err(EntityComponentError::AliasedMutability(self[i]));
}
}
}
let mut ptrs = Vec::with_capacity(self.len());
for &id in self {
ptrs.push(
// SAFETY: caller ensures that the cell has mutable access to the component.
unsafe { cell.get_mut_assume_mutable_by_id(id) }
.map_err(|_| EntityComponentError::MissingComponent(id))?,
);
}
Ok(ptrs)
}
}
// SAFETY:
// - No aliased mutability is caused because `HashSet` guarantees unique elements.
// - No mutable references are returned by `fetch_ref`.
unsafe impl DynamicComponentFetch for &'_ HashSet<ComponentId> {
type Ref<'w> = HashMap<ComponentId, Ptr<'w>>;
type Mut<'w> = HashMap<ComponentId, MutUntyped<'w>>;
unsafe fn fetch_ref(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Ref<'_>, EntityComponentError> {
let mut ptrs = HashMap::with_capacity_and_hasher(self.len(), Default::default());
for &id in self {
ptrs.insert(
id,
// SAFETY: caller ensures that the cell has read access to the component.
unsafe { cell.get_by_id(id) }.ok_or(EntityComponentError::MissingComponent(id))?,
);
}
Ok(ptrs)
}
unsafe fn fetch_mut(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Mut<'_>, EntityComponentError> {
let mut ptrs = HashMap::with_capacity_and_hasher(self.len(), Default::default());
for &id in self {
ptrs.insert(
id,
// SAFETY: caller ensures that the cell has mutable access to the component.
unsafe { cell.get_mut_by_id(id) }
.map_err(|_| EntityComponentError::MissingComponent(id))?,
);
}
Ok(ptrs)
}
unsafe fn fetch_mut_assume_mutable(
self,
cell: UnsafeEntityCell<'_>,
) -> Result<Self::Mut<'_>, EntityComponentError> {
let mut ptrs = HashMap::with_capacity_and_hasher(self.len(), Default::default());
for &id in self {
ptrs.insert(
id,
// SAFETY: caller ensures that the cell has mutable access to the component.
unsafe { cell.get_mut_assume_mutable_by_id(id) }
.map_err(|_| EntityComponentError::MissingComponent(id))?,
);
}
Ok(ptrs)
}
}
| 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/world/entity_access/entry.rs | crates/bevy_ecs/src/world/entity_access/entry.rs | use crate::{
component::{Component, Mutable},
world::{EntityWorldMut, Mut},
};
use core::marker::PhantomData;
/// A view into a single entity and component in a world, which may either be vacant or occupied.
///
/// This `enum` can only be constructed from the [`entry`] method on [`EntityWorldMut`].
///
/// [`entry`]: EntityWorldMut::entry
pub enum ComponentEntry<'w, 'a, T: Component> {
/// An occupied entry.
Occupied(OccupiedComponentEntry<'w, 'a, T>),
/// A vacant entry.
Vacant(VacantComponentEntry<'w, 'a, T>),
}
impl<'w, 'a, T: Component<Mutability = Mutable>> ComponentEntry<'w, 'a, T> {
/// Provides in-place mutable access to an occupied entry.
///
/// # Examples
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
/// struct Comp(u32);
///
/// # let mut world = World::new();
/// let mut entity = world.spawn(Comp(0));
///
/// entity.entry::<Comp>().and_modify(|mut c| c.0 += 1);
/// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 1);
/// ```
#[inline]
pub fn and_modify<F: FnOnce(Mut<'_, T>)>(self, f: F) -> Self {
match self {
ComponentEntry::Occupied(mut entry) => {
f(entry.get_mut());
ComponentEntry::Occupied(entry)
}
ComponentEntry::Vacant(entry) => ComponentEntry::Vacant(entry),
}
}
}
impl<'w, 'a, T: Component> ComponentEntry<'w, 'a, T> {
/// Replaces the component of the entry, and returns an [`OccupiedComponentEntry`].
///
/// # Examples
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
/// struct Comp(u32);
///
/// # let mut world = World::new();
/// let mut entity = world.spawn_empty();
///
/// let entry = entity.entry().insert_entry(Comp(4));
/// assert_eq!(entry.get(), &Comp(4));
///
/// let entry = entity.entry().insert_entry(Comp(2));
/// assert_eq!(entry.get(), &Comp(2));
/// ```
#[inline]
pub fn insert_entry(self, component: T) -> OccupiedComponentEntry<'w, 'a, T> {
match self {
ComponentEntry::Occupied(mut entry) => {
entry.insert(component);
entry
}
ComponentEntry::Vacant(entry) => entry.insert(component),
}
}
/// Ensures the entry has this component by inserting the given default if empty, and
/// returns a mutable reference to this component in the entry.
///
/// # Examples
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
/// struct Comp(u32);
///
/// # let mut world = World::new();
/// let mut entity = world.spawn_empty();
///
/// entity.entry().or_insert(Comp(4));
/// # let entity_id = entity.id();
/// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 4);
///
/// # let mut entity = world.get_entity_mut(entity_id).unwrap();
/// entity.entry().or_insert(Comp(15)).into_mut().0 *= 2;
/// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 8);
/// ```
#[inline]
pub fn or_insert(self, default: T) -> OccupiedComponentEntry<'w, 'a, T> {
match self {
ComponentEntry::Occupied(entry) => entry,
ComponentEntry::Vacant(entry) => entry.insert(default),
}
}
/// Ensures the entry has this component by inserting the result of the default function if
/// empty, and returns a mutable reference to this component in the entry.
///
/// # Examples
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
/// struct Comp(u32);
///
/// # let mut world = World::new();
/// let mut entity = world.spawn_empty();
///
/// entity.entry().or_insert_with(|| Comp(4));
/// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 4);
/// ```
#[inline]
pub fn or_insert_with<F: FnOnce() -> T>(self, default: F) -> OccupiedComponentEntry<'w, 'a, T> {
match self {
ComponentEntry::Occupied(entry) => entry,
ComponentEntry::Vacant(entry) => entry.insert(default()),
}
}
}
impl<'w, 'a, T: Component + Default> ComponentEntry<'w, 'a, T> {
/// Ensures the entry has this component by inserting the default value if empty, and
/// returns a mutable reference to this component in the entry.
///
/// # Examples
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
/// struct Comp(u32);
///
/// # let mut world = World::new();
/// let mut entity = world.spawn_empty();
///
/// entity.entry::<Comp>().or_default();
/// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 0);
/// ```
#[inline]
pub fn or_default(self) -> OccupiedComponentEntry<'w, 'a, T> {
match self {
ComponentEntry::Occupied(entry) => entry,
ComponentEntry::Vacant(entry) => entry.insert(Default::default()),
}
}
}
/// A view into an occupied entry in a [`EntityWorldMut`]. It is part of the [`OccupiedComponentEntry`] enum.
///
/// The contained entity must have the component type parameter if we have this struct.
pub struct OccupiedComponentEntry<'w, 'a, T: Component> {
pub(crate) entity_world: &'a mut EntityWorldMut<'w>,
pub(crate) _marker: PhantomData<T>,
}
impl<'w, 'a, T: Component> OccupiedComponentEntry<'w, 'a, T> {
/// Gets a reference to the component in the entry.
///
/// # Examples
///
/// ```
/// # use bevy_ecs::{prelude::*, world::ComponentEntry};
/// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
/// struct Comp(u32);
///
/// # let mut world = World::new();
/// let mut entity = world.spawn(Comp(5));
///
/// if let ComponentEntry::Occupied(o) = entity.entry::<Comp>() {
/// assert_eq!(o.get().0, 5);
/// }
/// ```
#[inline]
pub fn get(&self) -> &T {
// This shouldn't panic because if we have an OccupiedComponentEntry the component must exist.
self.entity_world.get::<T>().unwrap()
}
/// Replaces the component of the entry.
///
/// # Examples
///
/// ```
/// # use bevy_ecs::{prelude::*, world::ComponentEntry};
/// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
/// struct Comp(u32);
///
/// # let mut world = World::new();
/// let mut entity = world.spawn(Comp(5));
///
/// if let ComponentEntry::Occupied(mut o) = entity.entry::<Comp>() {
/// o.insert(Comp(10));
/// }
///
/// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 10);
/// ```
#[inline]
pub fn insert(&mut self, component: T) {
self.entity_world.insert(component);
}
/// Removes the component from the entry and returns it.
///
/// # Examples
///
/// ```
/// # use bevy_ecs::{prelude::*, world::ComponentEntry};
/// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
/// struct Comp(u32);
///
/// # let mut world = World::new();
/// let mut entity = world.spawn(Comp(5));
///
/// if let ComponentEntry::Occupied(o) = entity.entry::<Comp>() {
/// assert_eq!(o.take(), Comp(5));
/// }
///
/// assert_eq!(world.query::<&Comp>().iter(&world).len(), 0);
/// ```
#[inline]
pub fn take(self) -> T {
// This shouldn't panic because if we have an OccupiedComponentEntry the component must exist.
self.entity_world.take().unwrap()
}
}
impl<'w, 'a, T: Component<Mutability = Mutable>> OccupiedComponentEntry<'w, 'a, T> {
/// Gets a mutable reference to the component in the entry.
///
/// If you need a reference to the [`OccupiedComponentEntry`] which may outlive the destruction of
/// the [`OccupiedComponentEntry`] value, see [`into_mut`].
///
/// [`into_mut`]: Self::into_mut
///
/// # Examples
///
/// ```
/// # use bevy_ecs::{prelude::*, world::ComponentEntry};
/// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
/// struct Comp(u32);
///
/// # let mut world = World::new();
/// let mut entity = world.spawn(Comp(5));
///
/// if let ComponentEntry::Occupied(mut o) = entity.entry::<Comp>() {
/// o.get_mut().0 += 10;
/// assert_eq!(o.get().0, 15);
///
/// // We can use the same Entry multiple times.
/// o.get_mut().0 += 2
/// }
///
/// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 17);
/// ```
#[inline]
pub fn get_mut(&mut self) -> Mut<'_, T> {
// This shouldn't panic because if we have an OccupiedComponentEntry the component must exist.
self.entity_world.get_mut::<T>().unwrap()
}
/// Converts the [`OccupiedComponentEntry`] into a mutable reference to the value in the entry with
/// a lifetime bound to the `EntityWorldMut`.
///
/// If you need multiple references to the [`OccupiedComponentEntry`], see [`get_mut`].
///
/// [`get_mut`]: Self::get_mut
///
/// # Examples
///
/// ```
/// # use bevy_ecs::{prelude::*, world::ComponentEntry};
/// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
/// struct Comp(u32);
///
/// # let mut world = World::new();
/// let mut entity = world.spawn(Comp(5));
///
/// if let ComponentEntry::Occupied(o) = entity.entry::<Comp>() {
/// o.into_mut().0 += 10;
/// }
///
/// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 15);
/// ```
#[inline]
pub fn into_mut(self) -> Mut<'a, T> {
// This shouldn't panic because if we have an OccupiedComponentEntry the component must exist.
self.entity_world.get_mut().unwrap()
}
}
/// A view into a vacant entry in a [`EntityWorldMut`]. It is part of the [`ComponentEntry`] enum.
pub struct VacantComponentEntry<'w, 'a, T: Component> {
pub(crate) entity_world: &'a mut EntityWorldMut<'w>,
pub(crate) _marker: PhantomData<T>,
}
impl<'w, 'a, T: Component> VacantComponentEntry<'w, 'a, T> {
/// Inserts the component into the [`VacantComponentEntry`] and returns an [`OccupiedComponentEntry`].
///
/// # Examples
///
/// ```
/// # use bevy_ecs::{prelude::*, world::ComponentEntry};
/// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
/// struct Comp(u32);
///
/// # let mut world = World::new();
/// let mut entity = world.spawn_empty();
///
/// if let ComponentEntry::Vacant(v) = entity.entry::<Comp>() {
/// v.insert(Comp(10));
/// }
///
/// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 10);
/// ```
#[inline]
pub fn insert(self, component: T) -> OccupiedComponentEntry<'w, 'a, T> {
self.entity_world.insert(component);
OccupiedComponentEntry {
entity_world: self.entity_world,
_marker: PhantomData,
}
}
}
| 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/schedule/config.rs | crates/bevy_ecs/src/schedule/config.rs | use alloc::{boxed::Box, vec, vec::Vec};
use variadics_please::all_tuples;
use crate::{
schedule::{
auto_insert_apply_deferred::IgnoreDeferred,
condition::{BoxedCondition, SystemCondition},
graph::{Ambiguity, Dependency, DependencyKind, GraphInfo},
set::{InternedSystemSet, IntoSystemSet, SystemSet},
Chain,
},
system::{BoxedSystem, IntoSystem, ScheduleSystem, System},
};
fn new_condition<M>(condition: impl SystemCondition<M>) -> BoxedCondition {
let condition_system = IntoSystem::into_system(condition);
assert!(
condition_system.is_send(),
"SystemCondition `{}` accesses `NonSend` resources. This is not currently supported.",
condition_system.name()
);
Box::new(condition_system)
}
fn ambiguous_with(graph_info: &mut GraphInfo, set: InternedSystemSet) {
match &mut graph_info.ambiguous_with {
detection @ Ambiguity::Check => {
*detection = Ambiguity::IgnoreWithSet(vec![set]);
}
Ambiguity::IgnoreWithSet(ambiguous_with) => {
ambiguous_with.push(set);
}
Ambiguity::IgnoreAll => (),
}
}
/// Stores data to differentiate different schedulable structs.
pub trait Schedulable {
/// Additional data used to configure independent scheduling. Stored in [`ScheduleConfig`].
type Metadata;
/// Additional data used to configure a schedulable group. Stored in [`ScheduleConfigs`].
type GroupMetadata;
/// Initializes a configuration from this node.
fn into_config(self) -> ScheduleConfig<Self>
where
Self: Sized;
}
impl Schedulable for ScheduleSystem {
type Metadata = GraphInfo;
type GroupMetadata = Chain;
fn into_config(self) -> ScheduleConfig<Self> {
let sets = self.default_system_sets().clone();
ScheduleConfig {
node: self,
metadata: GraphInfo {
hierarchy: sets,
..Default::default()
},
conditions: Vec::new(),
}
}
}
impl Schedulable for InternedSystemSet {
type Metadata = GraphInfo;
type GroupMetadata = Chain;
fn into_config(self) -> ScheduleConfig<Self> {
assert!(
self.system_type().is_none(),
"configuring system type sets is not allowed"
);
ScheduleConfig {
node: self,
metadata: GraphInfo::default(),
conditions: Vec::new(),
}
}
}
/// Stores configuration for a single generic node (a system or a system set)
///
/// The configuration includes the node itself, scheduling metadata
/// (hierarchy: in which sets is the node contained,
/// dependencies: before/after which other nodes should this node run)
/// and the run conditions associated with this node.
pub struct ScheduleConfig<T: Schedulable> {
pub(crate) node: T,
pub(crate) metadata: T::Metadata,
pub(crate) conditions: Vec<BoxedCondition>,
}
/// Single or nested configurations for [`Schedulable`]s.
pub enum ScheduleConfigs<T: Schedulable> {
/// Configuration for a single [`Schedulable`].
ScheduleConfig(ScheduleConfig<T>),
/// Configuration for a tuple of nested `Configs` instances.
Configs {
/// Configuration for each element of the tuple.
configs: Vec<ScheduleConfigs<T>>,
/// Run conditions applied to everything in the tuple.
collective_conditions: Vec<BoxedCondition>,
/// Metadata to be applied to all elements in the tuple.
metadata: T::GroupMetadata,
},
}
impl<T: Schedulable<Metadata = GraphInfo, GroupMetadata = Chain>> ScheduleConfigs<T> {
/// Adds a new boxed system set to the systems.
pub fn in_set_inner(&mut self, set: InternedSystemSet) {
match self {
Self::ScheduleConfig(config) => {
config.metadata.hierarchy.push(set);
}
Self::Configs { configs, .. } => {
for config in configs {
config.in_set_inner(set);
}
}
}
}
fn before_inner(&mut self, set: InternedSystemSet) {
match self {
Self::ScheduleConfig(config) => {
config
.metadata
.dependencies
.push(Dependency::new(DependencyKind::Before, set));
}
Self::Configs { configs, .. } => {
for config in configs {
config.before_inner(set);
}
}
}
}
fn after_inner(&mut self, set: InternedSystemSet) {
match self {
Self::ScheduleConfig(config) => {
config
.metadata
.dependencies
.push(Dependency::new(DependencyKind::After, set));
}
Self::Configs { configs, .. } => {
for config in configs {
config.after_inner(set);
}
}
}
}
fn before_ignore_deferred_inner(&mut self, set: InternedSystemSet) {
match self {
Self::ScheduleConfig(config) => {
config
.metadata
.dependencies
.push(Dependency::new(DependencyKind::Before, set).add_config(IgnoreDeferred));
}
Self::Configs { configs, .. } => {
for config in configs {
config.before_ignore_deferred_inner(set.intern());
}
}
}
}
fn after_ignore_deferred_inner(&mut self, set: InternedSystemSet) {
match self {
Self::ScheduleConfig(config) => {
config
.metadata
.dependencies
.push(Dependency::new(DependencyKind::After, set).add_config(IgnoreDeferred));
}
Self::Configs { configs, .. } => {
for config in configs {
config.after_ignore_deferred_inner(set.intern());
}
}
}
}
fn distributive_run_if_inner<M>(&mut self, condition: impl SystemCondition<M> + Clone) {
match self {
Self::ScheduleConfig(config) => {
config.conditions.push(new_condition(condition));
}
Self::Configs { configs, .. } => {
for config in configs {
config.distributive_run_if_inner(condition.clone());
}
}
}
}
fn ambiguous_with_inner(&mut self, set: InternedSystemSet) {
match self {
Self::ScheduleConfig(config) => {
ambiguous_with(&mut config.metadata, set);
}
Self::Configs { configs, .. } => {
for config in configs {
config.ambiguous_with_inner(set);
}
}
}
}
fn ambiguous_with_all_inner(&mut self) {
match self {
Self::ScheduleConfig(config) => {
config.metadata.ambiguous_with = Ambiguity::IgnoreAll;
}
Self::Configs { configs, .. } => {
for config in configs {
config.ambiguous_with_all_inner();
}
}
}
}
/// Adds a new boxed run condition to the systems.
///
/// This is useful if you have a run condition whose concrete type is unknown.
/// Prefer `run_if` for run conditions whose type is known at compile time.
pub fn run_if_dyn(&mut self, condition: BoxedCondition) {
match self {
Self::ScheduleConfig(config) => {
config.conditions.push(condition);
}
Self::Configs {
collective_conditions,
..
} => {
collective_conditions.push(condition);
}
}
}
fn chain_inner(mut self) -> Self {
match &mut self {
Self::ScheduleConfig(_) => { /* no op */ }
Self::Configs { metadata, .. } => {
metadata.set_chained();
}
};
self
}
fn chain_ignore_deferred_inner(mut self) -> Self {
match &mut self {
Self::ScheduleConfig(_) => { /* no op */ }
Self::Configs { metadata, .. } => {
metadata.set_chained_with_config(IgnoreDeferred);
}
}
self
}
}
/// Types that can convert into a [`ScheduleConfigs`].
///
/// This trait is implemented for "systems" (functions whose arguments all implement
/// [`SystemParam`](crate::system::SystemParam)), or tuples thereof.
/// It is a common entry point for system configurations.
///
/// # Usage notes
///
/// This trait should only be used as a bound for trait implementations or as an
/// argument to a function. If system configs need to be returned from a
/// function or stored somewhere, use [`ScheduleConfigs`] instead of this trait.
///
/// # Examples
///
/// ```
/// # use bevy_ecs::{schedule::IntoScheduleConfigs, system::ScheduleSystem};
/// # struct AppMock;
/// # struct Update;
/// # impl AppMock {
/// # pub fn add_systems<M>(
/// # &mut self,
/// # schedule: Update,
/// # systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
/// # ) -> &mut Self { self }
/// # }
/// # let mut app = AppMock;
///
/// fn handle_input() {}
///
/// fn update_camera() {}
/// fn update_character() {}
///
/// app.add_systems(
/// Update,
/// (
/// handle_input,
/// (update_camera, update_character).after(handle_input)
/// )
/// );
/// ```
#[diagnostic::on_unimplemented(
message = "`{Self}` does not describe a valid system configuration",
label = "invalid system configuration"
)]
pub trait IntoScheduleConfigs<T: Schedulable<Metadata = GraphInfo, GroupMetadata = Chain>, Marker>:
Sized
{
/// Convert into a [`ScheduleConfigs`].
fn into_configs(self) -> ScheduleConfigs<T>;
/// Add these systems to the provided `set`.
#[track_caller]
fn in_set(self, set: impl SystemSet) -> ScheduleConfigs<T> {
self.into_configs().in_set(set)
}
/// Runs before all systems in `set`. If `self` has any systems that produce [`Commands`](crate::system::Commands)
/// or other [`Deferred`](crate::system::Deferred) operations, all systems in `set` will see their effect.
///
/// If automatically inserting [`ApplyDeferred`](crate::schedule::ApplyDeferred) like
/// this isn't desired, use [`before_ignore_deferred`](Self::before_ignore_deferred) instead.
///
/// Calling [`.chain`](Self::chain) is often more convenient and ensures that all systems are added to the schedule.
/// Please check the [caveats section of `.after`](Self::after) for details.
fn before<M>(self, set: impl IntoSystemSet<M>) -> ScheduleConfigs<T> {
self.into_configs().before(set)
}
/// Run after all systems in `set`. If `set` has any systems that produce [`Commands`](crate::system::Commands)
/// or other [`Deferred`](crate::system::Deferred) operations, all systems in `self` will see their effect.
///
/// If automatically inserting [`ApplyDeferred`](crate::schedule::ApplyDeferred) like
/// this isn't desired, use [`after_ignore_deferred`](Self::after_ignore_deferred) instead.
///
/// Calling [`.chain`](Self::chain) is often more convenient and ensures that all systems are added to the schedule.
///
/// # Caveats
///
/// If you configure two [`System`]s like `(GameSystem::A).after(GameSystem::B)` or `(GameSystem::A).before(GameSystem::B)`, the `GameSystem::B` will not be automatically scheduled.
///
/// This means that the system `GameSystem::A` and the system or systems in `GameSystem::B` will run independently of each other if `GameSystem::B` was never explicitly scheduled with [`configure_sets`]
/// If that is the case, `.after`/`.before` will not provide the desired behavior
/// and the systems can run in parallel or in any order determined by the scheduler.
/// Only use `after(GameSystem::B)` and `before(GameSystem::B)` when you know that `B` has already been scheduled for you,
/// e.g. when it was provided by Bevy or a third-party dependency,
/// or you manually scheduled it somewhere else in your app.
///
/// Another caveat is that if `GameSystem::B` is placed in a different schedule than `GameSystem::A`,
/// any ordering calls between themβwhether using `.before`, `.after`, or `.chain`βwill be silently ignored.
///
/// [`configure_sets`]: https://docs.rs/bevy/latest/bevy/app/struct.App.html#method.configure_sets
fn after<M>(self, set: impl IntoSystemSet<M>) -> ScheduleConfigs<T> {
self.into_configs().after(set)
}
/// Run before all systems in `set`.
///
/// Unlike [`before`](Self::before), this will not cause the systems in
/// `set` to wait for the deferred effects of `self` to be applied.
fn before_ignore_deferred<M>(self, set: impl IntoSystemSet<M>) -> ScheduleConfigs<T> {
self.into_configs().before_ignore_deferred(set)
}
/// Run after all systems in `set`.
///
/// Unlike [`after`](Self::after), this will not wait for the deferred
/// effects of systems in `set` to be applied.
fn after_ignore_deferred<M>(self, set: impl IntoSystemSet<M>) -> ScheduleConfigs<T> {
self.into_configs().after_ignore_deferred(set)
}
/// Add a run condition to each contained system.
///
/// Each system will receive its own clone of the [`SystemCondition`] and will only run
/// if the `SystemCondition` is true.
///
/// Each individual condition will be evaluated at most once (per schedule run),
/// right before the corresponding system prepares to run.
///
/// This is equivalent to calling [`run_if`](IntoScheduleConfigs::run_if) on each individual
/// system, as shown below:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut schedule = Schedule::default();
/// # fn a() {}
/// # fn b() {}
/// # fn condition() -> bool { true }
/// schedule.add_systems((a, b).distributive_run_if(condition));
/// schedule.add_systems((a.run_if(condition), b.run_if(condition)));
/// ```
///
/// # Note
///
/// Because the conditions are evaluated separately for each system, there is no guarantee
/// that all evaluations in a single schedule run will yield the same result. If another
/// system is run inbetween two evaluations it could cause the result of the condition to change.
///
/// Use [`run_if`](ScheduleConfigs::run_if) on a [`SystemSet`] if you want to make sure
/// that either all or none of the systems are run, or you don't want to evaluate the run
/// condition for each contained system separately.
fn distributive_run_if<M>(
self,
condition: impl SystemCondition<M> + Clone,
) -> ScheduleConfigs<T> {
self.into_configs().distributive_run_if(condition)
}
/// Run the systems only if the [`SystemCondition`] is `true`.
///
/// The `SystemCondition` will be evaluated at most once (per schedule run),
/// the first time a system in this set prepares to run.
///
/// If this set contains more than one system, calling `run_if` is equivalent to adding each
/// system to a common set and configuring the run condition on that set, as shown below:
///
/// # Examples
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut schedule = Schedule::default();
/// # fn a() {}
/// # fn b() {}
/// # fn condition() -> bool { true }
/// # #[derive(SystemSet, Debug, Eq, PartialEq, Hash, Clone, Copy)]
/// # struct C;
/// schedule.add_systems((a, b).run_if(condition));
/// schedule.add_systems((a, b).in_set(C)).configure_sets(C.run_if(condition));
/// ```
///
/// # Note
///
/// Because the condition will only be evaluated once, there is no guarantee that the condition
/// is upheld after the first system has run. You need to make sure that no other systems that
/// could invalidate the condition are scheduled inbetween the first and last run system.
///
/// Use [`distributive_run_if`](IntoScheduleConfigs::distributive_run_if) if you want the
/// condition to be evaluated for each individual system, right before one is run.
fn run_if<M>(self, condition: impl SystemCondition<M>) -> ScheduleConfigs<T> {
self.into_configs().run_if(condition)
}
/// Suppress warnings and errors that would result from these systems having ambiguities
/// (conflicting access but indeterminate order) with systems in `set`.
fn ambiguous_with<M>(self, set: impl IntoSystemSet<M>) -> ScheduleConfigs<T> {
self.into_configs().ambiguous_with(set)
}
/// Suppress warnings and errors that would result from these systems having ambiguities
/// (conflicting access but indeterminate order) with any other system.
fn ambiguous_with_all(self) -> ScheduleConfigs<T> {
self.into_configs().ambiguous_with_all()
}
/// Treat this collection as a sequence of systems.
///
/// Ordering constraints will be applied between the successive elements.
///
/// If the preceding node on an edge has deferred parameters, an [`ApplyDeferred`](crate::schedule::ApplyDeferred)
/// will be inserted on the edge. If this behavior is not desired consider using
/// [`chain_ignore_deferred`](Self::chain_ignore_deferred) instead.
fn chain(self) -> ScheduleConfigs<T> {
self.into_configs().chain()
}
/// Treat this collection as a sequence of systems.
///
/// Ordering constraints will be applied between the successive elements.
///
/// Unlike [`chain`](Self::chain) this will **not** add [`ApplyDeferred`](crate::schedule::ApplyDeferred) on the edges.
fn chain_ignore_deferred(self) -> ScheduleConfigs<T> {
self.into_configs().chain_ignore_deferred()
}
}
impl<T: Schedulable<Metadata = GraphInfo, GroupMetadata = Chain>> IntoScheduleConfigs<T, ()>
for ScheduleConfigs<T>
{
fn into_configs(self) -> Self {
self
}
#[track_caller]
fn in_set(mut self, set: impl SystemSet) -> Self {
assert!(
set.system_type().is_none(),
"adding arbitrary systems to a system type set is not allowed"
);
self.in_set_inner(set.intern());
self
}
fn before<M>(mut self, set: impl IntoSystemSet<M>) -> Self {
let set = set.into_system_set();
self.before_inner(set.intern());
self
}
fn after<M>(mut self, set: impl IntoSystemSet<M>) -> Self {
let set = set.into_system_set();
self.after_inner(set.intern());
self
}
fn before_ignore_deferred<M>(mut self, set: impl IntoSystemSet<M>) -> Self {
let set = set.into_system_set();
self.before_ignore_deferred_inner(set.intern());
self
}
fn after_ignore_deferred<M>(mut self, set: impl IntoSystemSet<M>) -> Self {
let set = set.into_system_set();
self.after_ignore_deferred_inner(set.intern());
self
}
fn distributive_run_if<M>(
mut self,
condition: impl SystemCondition<M> + Clone,
) -> ScheduleConfigs<T> {
self.distributive_run_if_inner(condition);
self
}
fn run_if<M>(mut self, condition: impl SystemCondition<M>) -> ScheduleConfigs<T> {
self.run_if_dyn(new_condition(condition));
self
}
fn ambiguous_with<M>(mut self, set: impl IntoSystemSet<M>) -> Self {
let set = set.into_system_set();
self.ambiguous_with_inner(set.intern());
self
}
fn ambiguous_with_all(mut self) -> Self {
self.ambiguous_with_all_inner();
self
}
fn chain(self) -> Self {
self.chain_inner()
}
fn chain_ignore_deferred(self) -> Self {
self.chain_ignore_deferred_inner()
}
}
impl<F, Marker> IntoScheduleConfigs<ScheduleSystem, Marker> for F
where
F: IntoSystem<(), (), Marker>,
{
fn into_configs(self) -> ScheduleConfigs<ScheduleSystem> {
let boxed_system = Box::new(IntoSystem::into_system(self));
ScheduleConfigs::ScheduleConfig(ScheduleSystem::into_config(boxed_system))
}
}
impl IntoScheduleConfigs<ScheduleSystem, ()> for BoxedSystem<(), ()> {
fn into_configs(self) -> ScheduleConfigs<ScheduleSystem> {
ScheduleConfigs::ScheduleConfig(ScheduleSystem::into_config(self))
}
}
impl<S: SystemSet> IntoScheduleConfigs<InternedSystemSet, ()> for S {
fn into_configs(self) -> ScheduleConfigs<InternedSystemSet> {
ScheduleConfigs::ScheduleConfig(InternedSystemSet::into_config(self.intern()))
}
}
#[doc(hidden)]
pub struct ScheduleConfigTupleMarker;
macro_rules! impl_node_type_collection {
($(#[$meta:meta])* $(($param: ident, $sys: ident)),*) => {
$(#[$meta])*
impl<$($param, $sys),*, T: Schedulable<Metadata = GraphInfo, GroupMetadata = Chain>> IntoScheduleConfigs<T, (ScheduleConfigTupleMarker, $($param,)*)> for ($($sys,)*)
where
$($sys: IntoScheduleConfigs<T, $param>),*
{
#[expect(
clippy::allow_attributes,
reason = "We are inside a macro, and as such, `non_snake_case` is not guaranteed to apply."
)]
#[allow(
non_snake_case,
reason = "Variable names are provided by the macro caller, not by us."
)]
fn into_configs(self) -> ScheduleConfigs<T> {
let ($($sys,)*) = self;
ScheduleConfigs::Configs {
metadata: Default::default(),
configs: vec![$($sys.into_configs(),)*],
collective_conditions: Vec::new(),
}
}
}
}
}
all_tuples!(
#[doc(fake_variadic)]
impl_node_type_collection,
1,
20,
P,
S
);
| 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/schedule/node.rs | crates/bevy_ecs/src/schedule/node.rs | use alloc::{boxed::Box, collections::BTreeSet, string::String, vec::Vec};
use core::{
any::TypeId,
fmt::{self, Debug},
ops::{Deref, Index, IndexMut, Range},
};
use bevy_platform::collections::{HashMap, HashSet};
use bevy_utils::prelude::DebugName;
use slotmap::{new_key_type, Key, KeyData, SecondaryMap, SlotMap};
use thiserror::Error;
use crate::{
change_detection::{CheckChangeTicks, Tick},
component::{ComponentId, Components},
prelude::{SystemIn, SystemSet},
query::{AccessConflicts, FilteredAccessSet},
schedule::{
graph::{
DagAnalysis, DagGroups, DiGraph,
Direction::{self, Incoming, Outgoing},
GraphNodeId, UnGraph,
},
BoxedCondition, InternedSystemSet, ScheduleGraph,
},
storage::SparseSetIndex,
system::{
ReadOnlySystem, RunSystemError, ScheduleSystem, System, SystemParamValidationError,
SystemStateFlags,
},
world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, World},
};
/// A [`SystemWithAccess`] stored in a [`ScheduleGraph`].
pub(crate) struct SystemNode {
pub(crate) inner: Option<SystemWithAccess>,
}
/// A [`ScheduleSystem`] stored alongside the access returned from [`System::initialize`].
pub struct SystemWithAccess {
/// The system itself.
pub system: ScheduleSystem,
/// The access returned by [`System::initialize`].
/// This will be empty if the system has not been initialized yet.
pub access: FilteredAccessSet,
}
impl SystemWithAccess {
/// Constructs a new [`SystemWithAccess`] from a [`ScheduleSystem`].
/// The `access` will initially be empty.
pub fn new(system: ScheduleSystem) -> Self {
Self {
system,
access: FilteredAccessSet::new(),
}
}
}
impl System for SystemWithAccess {
type In = ();
type Out = ();
#[inline]
fn name(&self) -> DebugName {
self.system.name()
}
#[inline]
fn type_id(&self) -> TypeId {
self.system.type_id()
}
#[inline]
fn flags(&self) -> SystemStateFlags {
self.system.flags()
}
#[inline]
unsafe fn run_unsafe(
&mut self,
input: SystemIn<'_, Self>,
world: UnsafeWorldCell,
) -> Result<Self::Out, RunSystemError> {
// SAFETY: Caller ensures the same safety requirements.
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 World) {
self.system.apply_deferred(world);
}
#[inline]
fn queue_deferred(&mut self, world: DeferredWorld) {
self.system.queue_deferred(world);
}
#[inline]
unsafe fn validate_param_unsafe(
&mut self,
world: UnsafeWorldCell,
) -> Result<(), SystemParamValidationError> {
// SAFETY: Caller ensures the same safety requirements.
unsafe { self.system.validate_param_unsafe(world) }
}
#[inline]
fn initialize(&mut self, world: &mut World) -> FilteredAccessSet {
self.system.initialize(world)
}
#[inline]
fn check_change_tick(&mut self, check: CheckChangeTicks) {
self.system.check_change_tick(check);
}
#[inline]
fn default_system_sets(&self) -> Vec<InternedSystemSet> {
self.system.default_system_sets()
}
#[inline]
fn get_last_run(&self) -> Tick {
self.system.get_last_run()
}
#[inline]
fn set_last_run(&mut self, last_run: Tick) {
self.system.set_last_run(last_run);
}
}
/// A [`BoxedCondition`] stored alongside the access returned from [`System::initialize`].
pub struct ConditionWithAccess {
/// The condition itself.
pub condition: BoxedCondition,
/// The access returned by [`System::initialize`].
/// This will be empty if the system has not been initialized yet.
pub access: FilteredAccessSet,
}
impl ConditionWithAccess {
/// Constructs a new [`ConditionWithAccess`] from a [`BoxedCondition`].
/// The `access` will initially be empty.
pub const fn new(condition: BoxedCondition) -> Self {
Self {
condition,
access: FilteredAccessSet::new(),
}
}
}
impl System for ConditionWithAccess {
type In = ();
type Out = bool;
#[inline]
fn name(&self) -> DebugName {
self.condition.name()
}
#[inline]
fn type_id(&self) -> TypeId {
self.condition.type_id()
}
#[inline]
fn flags(&self) -> SystemStateFlags {
self.condition.flags()
}
#[inline]
unsafe fn run_unsafe(
&mut self,
input: SystemIn<'_, Self>,
world: UnsafeWorldCell,
) -> Result<Self::Out, RunSystemError> {
// SAFETY: Caller ensures the same safety requirements.
unsafe { self.condition.run_unsafe(input, world) }
}
#[cfg(feature = "hotpatching")]
#[inline]
fn refresh_hotpatch(&mut self) {
self.condition.refresh_hotpatch();
}
#[inline]
fn apply_deferred(&mut self, world: &mut World) {
self.condition.apply_deferred(world);
}
#[inline]
fn queue_deferred(&mut self, world: DeferredWorld) {
self.condition.queue_deferred(world);
}
#[inline]
unsafe fn validate_param_unsafe(
&mut self,
world: UnsafeWorldCell,
) -> Result<(), SystemParamValidationError> {
// SAFETY: Caller ensures the same safety requirements.
unsafe { self.condition.validate_param_unsafe(world) }
}
#[inline]
fn initialize(&mut self, world: &mut World) -> FilteredAccessSet {
self.condition.initialize(world)
}
#[inline]
fn check_change_tick(&mut self, check: CheckChangeTicks) {
self.condition.check_change_tick(check);
}
#[inline]
fn default_system_sets(&self) -> Vec<InternedSystemSet> {
self.condition.default_system_sets()
}
#[inline]
fn get_last_run(&self) -> Tick {
self.condition.get_last_run()
}
#[inline]
fn set_last_run(&mut self, last_run: Tick) {
self.condition.set_last_run(last_run);
}
}
impl SystemNode {
/// Create a new [`SystemNode`]
pub fn new(system: ScheduleSystem) -> Self {
Self {
inner: Some(SystemWithAccess::new(system)),
}
}
/// Obtain a reference to the [`SystemWithAccess`] represented by this node.
pub fn get(&self) -> Option<&SystemWithAccess> {
self.inner.as_ref()
}
/// Obtain a mutable reference to the [`SystemWithAccess`] represented by this node.
pub fn get_mut(&mut self) -> Option<&mut SystemWithAccess> {
self.inner.as_mut()
}
}
new_key_type! {
/// A unique identifier for a system in a [`ScheduleGraph`].
pub struct SystemKey;
/// A unique identifier for a system set in a [`ScheduleGraph`].
pub struct SystemSetKey;
}
impl GraphNodeId for SystemKey {
type Adjacent = (SystemKey, Direction);
type Edge = (SystemKey, SystemKey);
fn kind(&self) -> &'static str {
"system"
}
}
impl GraphNodeId for SystemSetKey {
type Adjacent = (SystemSetKey, Direction);
type Edge = (SystemSetKey, SystemSetKey);
fn kind(&self) -> &'static str {
"system set"
}
}
impl TryFrom<NodeId> for SystemKey {
type Error = SystemSetKey;
fn try_from(value: NodeId) -> Result<Self, Self::Error> {
match value {
NodeId::System(key) => Ok(key),
NodeId::Set(key) => Err(key),
}
}
}
impl TryFrom<NodeId> for SystemSetKey {
type Error = SystemKey;
fn try_from(value: NodeId) -> Result<Self, Self::Error> {
match value {
NodeId::System(key) => Err(key),
NodeId::Set(key) => Ok(key),
}
}
}
/// Unique identifier for a system or system set stored in a [`ScheduleGraph`].
///
/// [`ScheduleGraph`]: crate::schedule::ScheduleGraph
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum NodeId {
/// Identifier for a system.
System(SystemKey),
/// Identifier for a system set.
Set(SystemSetKey),
}
impl NodeId {
/// Returns `true` if the identified node is a system.
pub const fn is_system(&self) -> bool {
matches!(self, NodeId::System(_))
}
/// Returns `true` if the identified node is a system set.
pub const fn is_set(&self) -> bool {
matches!(self, NodeId::Set(_))
}
/// Returns the system key if the node is a system, otherwise `None`.
pub const fn as_system(&self) -> Option<SystemKey> {
match self {
NodeId::System(system) => Some(*system),
NodeId::Set(_) => None,
}
}
/// Returns the system set key if the node is a system set, otherwise `None`.
pub const fn as_set(&self) -> Option<SystemSetKey> {
match self {
NodeId::System(_) => None,
NodeId::Set(set) => Some(*set),
}
}
}
impl GraphNodeId for NodeId {
type Adjacent = CompactNodeIdAndDirection;
type Edge = CompactNodeIdPair;
fn kind(&self) -> &'static str {
match self {
NodeId::System(n) => n.kind(),
NodeId::Set(n) => n.kind(),
}
}
}
impl From<SystemKey> for NodeId {
fn from(system: SystemKey) -> Self {
NodeId::System(system)
}
}
impl From<SystemSetKey> for NodeId {
fn from(set: SystemSetKey) -> Self {
NodeId::Set(set)
}
}
/// Compact storage of a [`NodeId`] and a [`Direction`].
#[derive(Clone, Copy)]
pub struct CompactNodeIdAndDirection {
key: KeyData,
is_system: bool,
direction: Direction,
}
impl Debug for CompactNodeIdAndDirection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let tuple: (_, _) = (*self).into();
tuple.fmt(f)
}
}
impl From<(NodeId, Direction)> for CompactNodeIdAndDirection {
fn from((id, direction): (NodeId, Direction)) -> Self {
let key = match id {
NodeId::System(key) => key.data(),
NodeId::Set(key) => key.data(),
};
let is_system = id.is_system();
Self {
key,
is_system,
direction,
}
}
}
impl From<CompactNodeIdAndDirection> for (NodeId, Direction) {
fn from(value: CompactNodeIdAndDirection) -> Self {
let node = match value.is_system {
true => NodeId::System(value.key.into()),
false => NodeId::Set(value.key.into()),
};
(node, value.direction)
}
}
/// Compact storage of a [`NodeId`] pair.
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub struct CompactNodeIdPair {
key_a: KeyData,
key_b: KeyData,
is_system_a: bool,
is_system_b: bool,
}
impl Debug for CompactNodeIdPair {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let tuple: (_, _) = (*self).into();
tuple.fmt(f)
}
}
impl From<(NodeId, NodeId)> for CompactNodeIdPair {
fn from((a, b): (NodeId, NodeId)) -> Self {
let key_a = match a {
NodeId::System(index) => index.data(),
NodeId::Set(index) => index.data(),
};
let is_system_a = a.is_system();
let key_b = match b {
NodeId::System(index) => index.data(),
NodeId::Set(index) => index.data(),
};
let is_system_b = b.is_system();
Self {
key_a,
key_b,
is_system_a,
is_system_b,
}
}
}
impl From<CompactNodeIdPair> for (NodeId, NodeId) {
fn from(value: CompactNodeIdPair) -> Self {
let a = match value.is_system_a {
true => NodeId::System(value.key_a.into()),
false => NodeId::Set(value.key_a.into()),
};
let b = match value.is_system_b {
true => NodeId::System(value.key_b.into()),
false => NodeId::Set(value.key_b.into()),
};
(a, b)
}
}
/// Container for systems in a schedule.
#[derive(Default)]
pub struct Systems {
/// List of systems in the schedule.
nodes: SlotMap<SystemKey, SystemNode>,
/// List of conditions for each system, in the same order as `nodes`.
conditions: SecondaryMap<SystemKey, Vec<ConditionWithAccess>>,
/// Systems and their conditions that have not been initialized yet.
uninit: Vec<SystemKey>,
}
impl Systems {
/// Returns the number of systems in this container.
pub fn len(&self) -> usize {
self.nodes.len()
}
/// Returns `true` if this container is empty.
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
/// Returns a reference to the system with the given key, if it exists.
pub fn get(&self, key: SystemKey) -> Option<&SystemWithAccess> {
self.nodes.get(key).and_then(|node| node.get())
}
/// Returns a mutable reference to the system with the given key, if it exists.
pub fn get_mut(&mut self, key: SystemKey) -> Option<&mut SystemWithAccess> {
self.nodes.get_mut(key).and_then(|node| node.get_mut())
}
/// Returns a mutable reference to the system with the given key. Will return
/// `None` if the key does not exist.
pub(crate) fn node_mut(&mut self, key: SystemKey) -> Option<&mut SystemNode> {
self.nodes.get_mut(key)
}
/// Returns `true` if the system with the given key has conditions.
pub fn has_conditions(&self, key: SystemKey) -> bool {
self.conditions
.get(key)
.is_some_and(|conditions| !conditions.is_empty())
}
/// Returns a reference to the conditions for the system with the given key, if it exists.
pub fn get_conditions(&self, key: SystemKey) -> Option<&[ConditionWithAccess]> {
self.conditions.get(key).map(Vec::as_slice)
}
/// Returns a mutable reference to the conditions for the system with the given key, if it exists.
pub fn get_conditions_mut(&mut self, key: SystemKey) -> Option<&mut Vec<ConditionWithAccess>> {
self.conditions.get_mut(key)
}
/// Returns an iterator over all systems and their conditions in this
/// container.
pub fn iter(
&self,
) -> impl Iterator<Item = (SystemKey, &ScheduleSystem, &[ConditionWithAccess])> + '_ {
self.nodes.iter().filter_map(|(key, node)| {
let system = &node.get()?.system;
let conditions = self
.conditions
.get(key)
.map(Vec::as_slice)
.unwrap_or_default();
Some((key, system, conditions))
})
}
/// Inserts a new system into the container, along with its conditions,
/// and queues it to be initialized later in [`Systems::initialize`].
///
/// We have to defer initialization of systems in the container until we have
/// `&mut World` access, so we store these in a list until
/// [`Systems::initialize`] is called. This is usually done upon the first
/// run of the schedule.
pub fn insert(
&mut self,
system: ScheduleSystem,
conditions: Vec<Box<dyn ReadOnlySystem<In = (), Out = bool>>>,
) -> SystemKey {
let key = self.nodes.insert(SystemNode::new(system));
self.conditions.insert(
key,
conditions
.into_iter()
.map(ConditionWithAccess::new)
.collect(),
);
self.uninit.push(key);
key
}
/// Remove a system with [`SystemKey`]
pub(crate) fn remove(&mut self, key: SystemKey) -> bool {
let mut found = false;
if self.nodes.remove(key).is_some() {
found = true;
}
if self.conditions.remove(key).is_some() {
found = true;
}
if let Some(index) = self.uninit.iter().position(|value| *value == key) {
self.uninit.remove(index);
found = true;
}
found
}
/// Returns `true` if all systems in this container have been initialized.
pub fn is_initialized(&self) -> bool {
self.uninit.is_empty()
}
/// Initializes all systems and their conditions that have not been
/// initialized yet.
pub fn initialize(&mut self, world: &mut World) {
for key in self.uninit.drain(..) {
let Some(system) = self.nodes.get_mut(key).and_then(|node| node.get_mut()) else {
continue;
};
system.access = system.system.initialize(world);
let Some(conditions) = self.conditions.get_mut(key) else {
continue;
};
for condition in conditions {
condition.access = condition.condition.initialize(world);
}
}
}
/// Calculates the list of systems that conflict with each other based on
/// their access patterns.
///
/// If the `Box<[ComponentId]>` is empty for a given pair of systems, then the
/// systems conflict on [`World`] access in general (e.g. one of them is
/// exclusive, or both systems have `Query<EntityMut>`).
pub fn get_conflicting_systems(
&self,
flat_dependency_analysis: &DagAnalysis<SystemKey>,
flat_ambiguous_with: &UnGraph<SystemKey>,
ambiguous_with_all: &HashSet<NodeId>,
ignored_ambiguities: &BTreeSet<ComponentId>,
) -> ConflictingSystems {
let mut conflicting_systems: Vec<(_, _, Box<[_]>)> = Vec::new();
for &(a, b) in flat_dependency_analysis.disconnected() {
if flat_ambiguous_with.contains_edge(a, b)
|| ambiguous_with_all.contains(&NodeId::System(a))
|| ambiguous_with_all.contains(&NodeId::System(b))
{
continue;
}
let system_a = &self[a];
let system_b = &self[b];
if system_a.is_exclusive() || system_b.is_exclusive() {
conflicting_systems.push((a, b, Box::new([])));
} else {
let access_a = &system_a.access;
let access_b = &system_b.access;
if !access_a.is_compatible(access_b) {
match access_a.get_conflicts(access_b) {
AccessConflicts::Individual(conflicts) => {
let conflicts: Box<[_]> = conflicts
.ones()
.map(ComponentId::get_sparse_set_index)
.filter(|id| !ignored_ambiguities.contains(id))
.collect();
if !conflicts.is_empty() {
conflicting_systems.push((a, b, conflicts));
}
}
AccessConflicts::All => {
// there is no specific component conflicting, but the systems are overall incompatible
// for example 2 systems with `Query<EntityMut>`
conflicting_systems.push((a, b, Box::new([])));
}
}
}
}
}
ConflictingSystems(conflicting_systems)
}
}
impl Index<SystemKey> for Systems {
type Output = SystemWithAccess;
#[track_caller]
fn index(&self, key: SystemKey) -> &Self::Output {
self.get(key)
.unwrap_or_else(|| panic!("System with key {:?} does not exist in the schedule", key))
}
}
impl IndexMut<SystemKey> for Systems {
#[track_caller]
fn index_mut(&mut self, key: SystemKey) -> &mut Self::Output {
self.get_mut(key)
.unwrap_or_else(|| panic!("System with key {:?} does not exist in the schedule", key))
}
}
/// Pairs of systems that conflict with each other along with the components
/// they conflict on, which prevents them from running in parallel. If the
/// component list is empty, the systems conflict on [`World`] access in general
/// (e.g. one of them is exclusive, or both systems have `Query<EntityMut>`).
#[derive(Clone, Debug, Default)]
pub struct ConflictingSystems(pub Vec<(SystemKey, SystemKey, Box<[ComponentId]>)>);
impl ConflictingSystems {
/// Checks if there are any conflicting systems, returning [`Ok`] if there
/// are none, or an [`AmbiguousSystemConflictsWarning`] if there are.
pub fn check_if_not_empty(&self) -> Result<(), AmbiguousSystemConflictsWarning> {
if self.0.is_empty() {
Ok(())
} else {
Err(AmbiguousSystemConflictsWarning(self.clone()))
}
}
/// Converts the conflicting systems into an iterator of their system names
/// and the names of the components they conflict on.
pub fn to_string(
&self,
graph: &ScheduleGraph,
components: &Components,
) -> impl Iterator<Item = (String, String, Box<[DebugName]>)> {
self.iter().map(move |(system_a, system_b, conflicts)| {
let name_a = graph.get_node_name(&NodeId::System(*system_a));
let name_b = graph.get_node_name(&NodeId::System(*system_b));
let conflict_names: Box<[_]> = conflicts
.iter()
.map(|id| components.get_name(*id).unwrap())
.collect();
(name_a, name_b, conflict_names)
})
}
}
impl Deref for ConflictingSystems {
type Target = Vec<(SystemKey, SystemKey, Box<[ComponentId]>)>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Error returned when there are ambiguous system conflicts detected.
#[derive(Error, Debug)]
#[error("Systems with conflicting access have indeterminate run order: {:?}", .0.0)]
pub struct AmbiguousSystemConflictsWarning(pub ConflictingSystems);
/// Container for system sets in a schedule.
#[derive(Default)]
pub struct SystemSets {
/// List of system sets in the schedule.
sets: SlotMap<SystemSetKey, InternedSystemSet>,
/// List of conditions for each system set, in the same order as `sets`.
conditions: SecondaryMap<SystemSetKey, Vec<ConditionWithAccess>>,
/// Map from system sets to their keys.
ids: HashMap<InternedSystemSet, SystemSetKey>,
/// System sets that have not been initialized yet.
uninit: Vec<UninitializedSet>,
}
/// A system set's conditions that have not been initialized yet.
struct UninitializedSet {
key: SystemSetKey,
/// The range of indices in [`SystemSets::conditions`] that correspond
/// to conditions that have not been initialized yet.
///
/// [`SystemSets::conditions`] for a given set may be appended to
/// multiple times (e.g. when `configure_sets` is called multiple with
/// the same set), so we need to track which conditions in that list
/// are newly added and not yet initialized.
///
/// Systems don't need this tracking because each `add_systems` call
/// creates separate nodes in the graph with their own conditions,
/// so all conditions are initialized together.
uninitialized_conditions: Range<usize>,
}
impl SystemSets {
/// Returns the number of system sets in this container.
pub fn len(&self) -> usize {
self.sets.len()
}
/// Returns `true` if this container is empty.
pub fn is_empty(&self) -> bool {
self.sets.is_empty()
}
/// Returns `true` if the given set is present in this container.
pub fn contains(&self, set: impl SystemSet) -> bool {
self.ids.contains_key(&set.intern())
}
/// Returns a reference to the system set with the given key, if it exists.
pub fn get(&self, key: SystemSetKey) -> Option<&dyn SystemSet> {
self.sets.get(key).map(|set| &**set)
}
/// Returns the key for the given system set, returns None if it does not exist.
pub fn get_key(&self, set: InternedSystemSet) -> Option<SystemSetKey> {
self.ids.get(&set).copied()
}
/// Returns the key for the given system set, inserting it into this
/// container if it does not already exist.
pub fn get_key_or_insert(&mut self, set: InternedSystemSet) -> SystemSetKey {
*self.ids.entry(set).or_insert_with(|| {
let key = self.sets.insert(set);
self.conditions.insert(key, Vec::new());
key
})
}
/// Returns `true` if the system set with the given key has conditions.
pub fn has_conditions(&self, key: SystemSetKey) -> bool {
self.conditions
.get(key)
.is_some_and(|conditions| !conditions.is_empty())
}
/// Returns a reference to the conditions for the system set with the given
/// key, if it exists.
pub fn get_conditions(&self, key: SystemSetKey) -> Option<&[ConditionWithAccess]> {
self.conditions.get(key).map(Vec::as_slice)
}
/// Returns a mutable reference to the conditions for the system set with
/// the given key, if it exists.
pub fn get_conditions_mut(
&mut self,
key: SystemSetKey,
) -> Option<&mut Vec<ConditionWithAccess>> {
self.conditions.get_mut(key)
}
/// Returns an iterator over all system sets in this container, along with
/// their conditions.
pub fn iter(
&self,
) -> impl Iterator<Item = (SystemSetKey, &dyn SystemSet, &[ConditionWithAccess])> {
self.sets.iter().filter_map(|(key, set)| {
let conditions = self.conditions.get(key)?.as_slice();
Some((key, &**set, conditions))
})
}
/// Inserts conditions for a system set into the container, and queues the
/// newly added conditions to be initialized later in [`SystemSets::initialize`].
///
/// If the set was not already present in the container, it is added automatically.
///
/// We have to defer initialization of system set conditions in the container
/// until we have `&mut World` access, so we store these in a list until
/// [`SystemSets::initialize`] is called. This is usually done upon the
/// first run of the schedule.
pub fn insert(
&mut self,
set: InternedSystemSet,
new_conditions: Vec<Box<dyn ReadOnlySystem<In = (), Out = bool>>>,
) -> SystemSetKey {
let key = self.get_key_or_insert(set);
if !new_conditions.is_empty() {
let current_conditions = &mut self.conditions[key];
let start = current_conditions.len();
self.uninit.push(UninitializedSet {
key,
uninitialized_conditions: start..(start + new_conditions.len()),
});
current_conditions.extend(new_conditions.into_iter().map(ConditionWithAccess::new));
}
key
}
/// Remove a set with a [`SystemSetKey`]
pub(crate) fn remove(&mut self, key: SystemSetKey) -> bool {
self.sets.remove(key);
self.conditions.remove(key);
self.uninit.retain(|uninit| uninit.key != key);
true
}
/// Returns `true` if all system sets' conditions in this container have
/// been initialized.
pub fn is_initialized(&self) -> bool {
self.uninit.is_empty()
}
/// Initializes all system sets' conditions that have not been
/// initialized yet. Because a system set's conditions may be appended to
/// multiple times, we track which conditions were added since the last
/// initialization and only initialize those.
pub fn initialize(&mut self, world: &mut World) {
for uninit in self.uninit.drain(..) {
let Some(conditions) = self.conditions.get_mut(uninit.key) else {
continue;
};
for condition in &mut conditions[uninit.uninitialized_conditions] {
condition.access = condition.initialize(world);
}
}
}
/// Ensures that there are no edges to system-type sets that have multiple
/// instances.
pub fn check_type_set_ambiguity(
&self,
set_systems: &DagGroups<SystemSetKey, SystemKey>,
ambiguous_with: &UnGraph<NodeId>,
dependency: &DiGraph<NodeId>,
) -> Result<(), SystemTypeSetAmbiguityError> {
for (&key, systems) in set_systems.iter() {
let set = &self[key];
if set.system_type().is_some() {
let instances = systems.len();
let ambiguous_with = ambiguous_with.edges(NodeId::Set(key));
let before = dependency.edges_directed(NodeId::Set(key), Incoming);
let after = dependency.edges_directed(NodeId::Set(key), Outgoing);
let relations = before.count() + after.count() + ambiguous_with.count();
if instances > 1 && relations > 0 {
return Err(SystemTypeSetAmbiguityError(key));
}
}
}
Ok(())
}
}
impl Index<SystemSetKey> for SystemSets {
type Output = dyn SystemSet;
#[track_caller]
fn index(&self, key: SystemSetKey) -> &Self::Output {
self.get(key).unwrap_or_else(|| {
panic!(
"System set with key {:?} does not exist in the schedule",
key
)
})
}
}
/// Error returned when calling [`SystemSets::check_type_set_ambiguity`].
#[derive(Error, Debug)]
#[error("Tried to order against `{0:?}` in a schedule that has more than one `{0:?}` instance. `{0:?}` is a `SystemTypeSet` and cannot be used for ordering if ambiguous. Use a different set without this restriction.")]
pub struct SystemTypeSetAmbiguityError(pub SystemSetKey);
#[cfg(test)]
mod tests {
use alloc::{boxed::Box, vec};
use crate::{
prelude::SystemSet,
schedule::{SystemSets, Systems},
system::IntoSystem,
world::World,
};
#[derive(SystemSet, Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub struct TestSet;
#[test]
fn systems() {
fn empty_system() {}
let mut systems = Systems::default();
assert!(systems.is_empty());
assert_eq!(systems.len(), 0);
let system = Box::new(IntoSystem::into_system(empty_system));
let key = systems.insert(system, vec![]);
assert!(!systems.is_empty());
assert_eq!(systems.len(), 1);
assert!(systems.get(key).is_some());
assert!(systems.get_conditions(key).is_some());
assert!(systems.get_conditions(key).unwrap().is_empty());
assert!(systems.get_mut(key).is_some());
assert!(!systems.is_initialized());
assert!(systems.iter().next().is_some());
let mut world = World::new();
systems.initialize(&mut world);
assert!(systems.is_initialized());
}
#[test]
fn system_sets() {
fn always_true() -> bool {
true
}
let mut sets = SystemSets::default();
assert!(sets.is_empty());
assert_eq!(sets.len(), 0);
let condition = Box::new(IntoSystem::into_system(always_true));
let key = sets.insert(TestSet.intern(), vec![condition]);
assert!(!sets.is_empty());
assert_eq!(sets.len(), 1);
assert!(sets.get(key).is_some());
assert!(sets.get_conditions(key).is_some());
assert!(!sets.get_conditions(key).unwrap().is_empty());
assert!(!sets.is_initialized());
assert!(sets.iter().next().is_some());
let mut world = World::new();
sets.initialize(&mut world);
assert!(sets.is_initialized());
}
}
| 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/schedule/schedule.rs | crates/bevy_ecs/src/schedule/schedule.rs | #![expect(
clippy::module_inception,
reason = "This instance of module inception is being discussed; see #17344."
)]
use alloc::{
boxed::Box,
collections::BTreeSet,
format,
string::{String, ToString},
vec,
vec::Vec,
};
use bevy_platform::{
collections::{HashMap, HashSet},
hash::FixedHasher,
};
use bevy_utils::{default, TypeIdMap};
use core::{
any::{Any, TypeId},
fmt::{Debug, Write},
};
use fixedbitset::FixedBitSet;
use indexmap::{IndexMap, IndexSet};
use log::{info, warn};
use pass::ScheduleBuildPassObj;
use thiserror::Error;
#[cfg(feature = "trace")]
use tracing::info_span;
use crate::{change_detection::CheckChangeTicks, system::System};
use crate::{
component::{ComponentId, Components},
prelude::Component,
resource::Resource,
schedule::*,
system::ScheduleSystem,
world::World,
};
pub use stepping::Stepping;
use Direction::{Incoming, Outgoing};
/// Resource that stores [`Schedule`]s mapped to [`ScheduleLabel`]s excluding the current running [`Schedule`].
#[derive(Default, Resource)]
pub struct Schedules {
inner: HashMap<InternedScheduleLabel, Schedule>,
/// List of [`ComponentId`]s to ignore when reporting system order ambiguity conflicts
pub ignored_scheduling_ambiguities: BTreeSet<ComponentId>,
}
impl Schedules {
/// Constructs an empty `Schedules` with zero initial capacity.
pub fn new() -> Self {
Self::default()
}
/// Inserts a labeled schedule into the map.
///
/// If the map already had an entry for `label`, `schedule` is inserted,
/// and the old schedule is returned. Otherwise, `None` is returned.
pub fn insert(&mut self, schedule: Schedule) -> Option<Schedule> {
self.inner.insert(schedule.label, schedule)
}
/// Removes the schedule corresponding to the `label` from the map, returning it if it existed.
pub fn remove(&mut self, label: impl ScheduleLabel) -> Option<Schedule> {
self.inner.remove(&label.intern())
}
/// Removes the (schedule, label) pair corresponding to the `label` from the map, returning it if it existed.
pub fn remove_entry(
&mut self,
label: impl ScheduleLabel,
) -> Option<(InternedScheduleLabel, Schedule)> {
self.inner.remove_entry(&label.intern())
}
/// Does a schedule with the provided label already exist?
pub fn contains(&self, label: impl ScheduleLabel) -> bool {
self.inner.contains_key(&label.intern())
}
/// Returns a reference to the schedule associated with `label`, if it exists.
pub fn get(&self, label: impl ScheduleLabel) -> Option<&Schedule> {
self.inner.get(&label.intern())
}
/// Returns a mutable reference to the schedule associated with `label`, if it exists.
pub fn get_mut(&mut self, label: impl ScheduleLabel) -> Option<&mut Schedule> {
self.inner.get_mut(&label.intern())
}
/// Returns a mutable reference to the schedules associated with `label`, creating one if it doesn't already exist.
pub fn entry(&mut self, label: impl ScheduleLabel) -> &mut Schedule {
self.inner
.entry(label.intern())
.or_insert_with(|| Schedule::new(label))
}
/// Returns an iterator over all schedules. Iteration order is undefined.
pub fn iter(&self) -> impl Iterator<Item = (&dyn ScheduleLabel, &Schedule)> {
self.inner
.iter()
.map(|(label, schedule)| (&**label, schedule))
}
/// Returns an iterator over mutable references to all schedules. Iteration order is undefined.
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&dyn ScheduleLabel, &mut Schedule)> {
self.inner
.iter_mut()
.map(|(label, schedule)| (&**label, schedule))
}
/// Iterates the change ticks of all systems in all stored schedules and clamps any older than
/// [`MAX_CHANGE_AGE`](crate::change_detection::MAX_CHANGE_AGE).
/// This prevents overflow and thus prevents false positives.
pub(crate) fn check_change_ticks(&mut self, check: CheckChangeTicks) {
#[cfg(feature = "trace")]
let _all_span = info_span!("check stored schedule ticks").entered();
#[cfg_attr(
not(feature = "trace"),
expect(
unused_variables,
reason = "The `label` variable goes unused if the `trace` feature isn't active"
)
)]
for (label, schedule) in &mut self.inner {
#[cfg(feature = "trace")]
let name = format!("{label:?}");
#[cfg(feature = "trace")]
let _one_span = info_span!("check schedule ticks", name = &name).entered();
schedule.check_change_ticks(check);
}
}
/// Applies the provided [`ScheduleBuildSettings`] to all schedules.
pub fn configure_schedules(&mut self, schedule_build_settings: ScheduleBuildSettings) {
for (_, schedule) in &mut self.inner {
schedule.set_build_settings(schedule_build_settings.clone());
}
}
/// Ignore system order ambiguities caused by conflicts on [`Component`]s of type `T`.
pub fn allow_ambiguous_component<T: Component>(&mut self, world: &mut World) {
self.ignored_scheduling_ambiguities
.insert(world.register_component::<T>());
}
/// Ignore system order ambiguities caused by conflicts on [`Resource`]s of type `T`.
pub fn allow_ambiguous_resource<T: Resource>(&mut self, world: &mut World) {
self.ignored_scheduling_ambiguities
.insert(world.components_registrator().register_resource::<T>());
}
/// Iterate through the [`ComponentId`]'s that will be ignored.
pub fn iter_ignored_ambiguities(&self) -> impl Iterator<Item = &ComponentId> + '_ {
self.ignored_scheduling_ambiguities.iter()
}
/// Prints the names of the components and resources with [`info`]
///
/// May panic or retrieve incorrect names if [`Components`] is not from the same
/// world
pub fn print_ignored_ambiguities(&self, components: &Components) {
let mut message =
"System order ambiguities caused by conflicts on the following types are ignored:\n"
.to_string();
for id in self.iter_ignored_ambiguities() {
writeln!(message, "{}", components.get_name(*id).unwrap()).unwrap();
}
info!("{message}");
}
/// Adds one or more systems to the [`Schedule`] matching the provided [`ScheduleLabel`].
pub fn add_systems<M>(
&mut self,
schedule: impl ScheduleLabel,
systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
) -> &mut Self {
self.entry(schedule).add_systems(systems);
self
}
/// Removes all systems in a [`SystemSet`]. This will cause the schedule to be rebuilt when
/// the schedule is run again. A [`ScheduleError`] is returned if the schedule needs to be
/// [`Schedule::initialize`]'d or the `set` is not found.
pub fn remove_systems_in_set<M>(
&mut self,
schedule: impl ScheduleLabel,
set: impl IntoSystemSet<M>,
world: &mut World,
policy: ScheduleCleanupPolicy,
) -> Result<usize, ScheduleError> {
self.get_mut(schedule)
.ok_or(ScheduleError::ScheduleNotFound)?
.remove_systems_in_set(set, world, policy)
}
/// Configures a collection of system sets in the provided schedule, adding any sets that do not exist.
#[track_caller]
pub fn configure_sets<M>(
&mut self,
schedule: impl ScheduleLabel,
sets: impl IntoScheduleConfigs<InternedSystemSet, M>,
) -> &mut Self {
self.entry(schedule).configure_sets(sets);
self
}
/// Suppress warnings and errors that would result from systems in these sets having ambiguities
/// (conflicting access but indeterminate order) with systems in `set`.
///
/// When possible, do this directly in the `.add_systems(Update, a.ambiguous_with(b))` call.
/// However, sometimes two independent plugins `A` and `B` are reported as ambiguous, which you
/// can only suppress as the consumer of both.
#[track_caller]
pub fn ignore_ambiguity<M1, M2, S1, S2>(
&mut self,
schedule: impl ScheduleLabel,
a: S1,
b: S2,
) -> &mut Self
where
S1: IntoSystemSet<M1>,
S2: IntoSystemSet<M2>,
{
self.entry(schedule).ignore_ambiguity(a, b);
self
}
}
fn make_executor(kind: ExecutorKind) -> Box<dyn SystemExecutor> {
match kind {
ExecutorKind::SingleThreaded => Box::new(SingleThreadedExecutor::new()),
#[cfg(feature = "std")]
ExecutorKind::MultiThreaded => Box::new(MultiThreadedExecutor::new()),
}
}
/// Chain systems into dependencies
#[derive(Default)]
pub enum Chain {
/// Systems are independent. Nodes are allowed to run in any order.
#[default]
Unchained,
/// Systems are chained. `before -> after` ordering constraints
/// will be added between the successive elements.
Chained(TypeIdMap<Box<dyn Any>>),
}
impl Chain {
/// Specify that the systems must be chained.
pub fn set_chained(&mut self) {
if matches!(self, Chain::Unchained) {
*self = Self::Chained(Default::default());
};
}
/// Specify that the systems must be chained, and add the specified configuration for
/// all dependencies created between these systems.
pub fn set_chained_with_config<T: 'static>(&mut self, config: T) {
self.set_chained();
if let Chain::Chained(config_map) = self {
config_map.insert(TypeId::of::<T>(), Box::new(config));
} else {
unreachable!()
};
}
}
/// A collection of systems, and the metadata and executor needed to run them
/// in a certain order under certain conditions.
///
/// # Schedule labels
///
/// Each schedule has a [`ScheduleLabel`] value. This value is used to uniquely identify the
/// schedule when added to a [`World`]βs [`Schedules`], and may be used to specify which schedule
/// a system should be added to.
///
/// # Example
///
/// Here is an example of a `Schedule` running a "Hello world" system:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// fn hello_world() { println!("Hello world!") }
///
/// fn main() {
/// let mut world = World::new();
/// let mut schedule = Schedule::default();
/// schedule.add_systems(hello_world);
///
/// schedule.run(&mut world);
/// }
/// ```
///
/// A schedule can also run several systems in an ordered way:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// fn system_one() { println!("System 1 works!") }
/// fn system_two() { println!("System 2 works!") }
/// fn system_three() { println!("System 3 works!") }
///
/// fn main() {
/// let mut world = World::new();
/// let mut schedule = Schedule::default();
/// schedule.add_systems((
/// system_two,
/// system_one.before(system_two),
/// system_three.after(system_two),
/// ));
///
/// schedule.run(&mut world);
/// }
/// ```
///
/// Schedules are often inserted into a [`World`] and identified by their [`ScheduleLabel`] only:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// use bevy_ecs::schedule::ScheduleLabel;
///
/// // Declare a new schedule label.
/// #[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
/// struct Update;
///
/// // This system shall be part of the schedule.
/// fn an_update_system() {
/// println!("Hello world!");
/// }
///
/// fn main() {
/// let mut world = World::new();
///
/// // Add a system to the schedule with that label (creating it automatically).
/// world.get_resource_or_init::<Schedules>().add_systems(Update, an_update_system);
///
/// // Run the schedule, and therefore run the system.
/// world.run_schedule(Update);
/// }
/// ```
pub struct Schedule {
label: InternedScheduleLabel,
graph: ScheduleGraph,
executable: SystemSchedule,
executor: Box<dyn SystemExecutor>,
executor_initialized: bool,
warnings: Vec<ScheduleBuildWarning>,
}
#[derive(ScheduleLabel, Hash, PartialEq, Eq, Debug, Clone)]
struct DefaultSchedule;
impl Default for Schedule {
/// Creates a schedule with a default label. Only use in situations where
/// you don't care about the [`ScheduleLabel`]. Inserting a default schedule
/// into the world risks overwriting another schedule. For most situations
/// you should use [`Schedule::new`].
fn default() -> Self {
Self::new(DefaultSchedule)
}
}
impl Schedule {
/// Constructs an empty `Schedule`.
pub fn new(label: impl ScheduleLabel) -> Self {
let mut this = Self {
label: label.intern(),
graph: ScheduleGraph::new(),
executable: SystemSchedule::new(),
executor: make_executor(ExecutorKind::default()),
executor_initialized: false,
warnings: Vec::new(),
};
// Call `set_build_settings` to add any default build passes
this.set_build_settings(Default::default());
this
}
/// Returns the [`InternedScheduleLabel`] for this `Schedule`,
/// corresponding to the [`ScheduleLabel`] this schedule was created with.
pub fn label(&self) -> InternedScheduleLabel {
self.label
}
/// Add a collection of systems to the schedule.
pub fn add_systems<M>(
&mut self,
systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
) -> &mut Self {
self.graph.process_configs(systems.into_configs(), false);
self
}
/// Removes all systems in a [`SystemSet`]. This will cause the schedule to be rebuilt when
/// the schedule is run again. A [`ScheduleError`] is returned if the schedule needs to be
/// [`Schedule::initialize`]'d or the `set` is not found.
///
/// Note that this can remove all systems of a type if you pass
/// the system to this function as systems implicitly create a set based
/// on the system type.
///
/// ## Example
/// ```
/// # use bevy_ecs::prelude::*;
/// # use bevy_ecs::schedule::ScheduleCleanupPolicy;
/// #
/// # fn my_system() {}
/// #
/// let mut schedule = Schedule::default();
/// // add the system to the schedule
/// schedule.add_systems(my_system);
/// let mut world = World::default();
///
/// // remove the system
/// schedule.remove_systems_in_set(my_system, &mut world, ScheduleCleanupPolicy::RemoveSystemsOnly);
/// ```
pub fn remove_systems_in_set<M>(
&mut self,
set: impl IntoSystemSet<M>,
world: &mut World,
policy: ScheduleCleanupPolicy,
) -> Result<usize, ScheduleError> {
if self.graph.changed {
self.initialize(world)?;
}
self.graph.remove_systems_in_set(set, policy)
}
/// Suppress warnings and errors that would result from systems in these sets having ambiguities
/// (conflicting access but indeterminate order) with systems in `set`.
#[track_caller]
pub fn ignore_ambiguity<M1, M2, S1, S2>(&mut self, a: S1, b: S2) -> &mut Self
where
S1: IntoSystemSet<M1>,
S2: IntoSystemSet<M2>,
{
let a = a.into_system_set();
let b = b.into_system_set();
let a_id = self.graph.system_sets.get_key_or_insert(a.intern());
let b_id = self.graph.system_sets.get_key_or_insert(b.intern());
self.graph
.ambiguous_with
.add_edge(NodeId::Set(a_id), NodeId::Set(b_id));
self
}
/// Configures a collection of system sets in this schedule, adding them if they does not exist.
#[track_caller]
pub fn configure_sets<M>(
&mut self,
sets: impl IntoScheduleConfigs<InternedSystemSet, M>,
) -> &mut Self {
self.graph.configure_sets(sets);
self
}
/// Add a custom build pass to the schedule.
pub fn add_build_pass<T: ScheduleBuildPass>(&mut self, pass: T) -> &mut Self {
self.graph.passes.insert(TypeId::of::<T>(), Box::new(pass));
self
}
/// Remove a custom build pass.
pub fn remove_build_pass<T: ScheduleBuildPass>(&mut self) {
self.graph.passes.shift_remove(&TypeId::of::<T>());
}
/// Changes miscellaneous build settings.
///
/// If [`settings.auto_insert_apply_deferred`][ScheduleBuildSettings::auto_insert_apply_deferred]
/// is `false`, this clears `*_ignore_deferred` edge settings configured so far.
///
/// Generally this method should be used before adding systems or set configurations to the schedule,
/// not after.
pub fn set_build_settings(&mut self, settings: ScheduleBuildSettings) -> &mut Self {
if settings.auto_insert_apply_deferred {
if !self
.graph
.passes
.contains_key(&TypeId::of::<passes::AutoInsertApplyDeferredPass>())
{
self.add_build_pass(passes::AutoInsertApplyDeferredPass::default());
}
} else {
self.remove_build_pass::<passes::AutoInsertApplyDeferredPass>();
}
self.graph.settings = settings;
self
}
/// Returns the schedule's current `ScheduleBuildSettings`.
pub fn get_build_settings(&self) -> ScheduleBuildSettings {
self.graph.settings.clone()
}
/// Returns the schedule's current execution strategy.
pub fn get_executor_kind(&self) -> ExecutorKind {
self.executor.kind()
}
/// Sets the schedule's execution strategy.
pub fn set_executor_kind(&mut self, executor: ExecutorKind) -> &mut Self {
if executor != self.executor.kind() {
self.executor = make_executor(executor);
self.executor_initialized = false;
}
self
}
/// Set whether the schedule applies deferred system buffers on final time or not. This is a catch-all
/// in case a system uses commands but was not explicitly ordered before an instance of
/// [`ApplyDeferred`]. By default this
/// setting is true, but may be disabled if needed.
pub fn set_apply_final_deferred(&mut self, apply_final_deferred: bool) -> &mut Self {
self.executor.set_apply_final_deferred(apply_final_deferred);
self
}
/// Runs all systems in this schedule on the `world`, using its current execution strategy.
pub fn run(&mut self, world: &mut World) {
#[cfg(feature = "trace")]
let _span = info_span!("schedule", name = ?self.label).entered();
world.check_change_ticks();
self.initialize(world).unwrap_or_else(|e| {
panic!(
"Error when initializing schedule {:?}: {}",
self.label,
e.to_string(self.graph(), world)
)
});
let error_handler = world.default_error_handler();
#[cfg(not(feature = "bevy_debug_stepping"))]
self.executor
.run(&mut self.executable, world, None, error_handler);
#[cfg(feature = "bevy_debug_stepping")]
{
let skip_systems = match world.get_resource_mut::<Stepping>() {
None => None,
Some(mut stepping) => stepping.skipped_systems(self),
};
self.executor.run(
&mut self.executable,
world,
skip_systems.as_ref(),
error_handler,
);
}
}
/// Initializes any newly-added systems and conditions, rebuilds the executable schedule,
/// and re-initializes the executor.
///
/// Moves all systems and run conditions out of the [`ScheduleGraph`].
pub fn initialize(&mut self, world: &mut World) -> Result<(), ScheduleBuildError> {
if self.graph.changed {
self.graph.initialize(world);
let ignored_ambiguities = world
.get_resource_or_init::<Schedules>()
.ignored_scheduling_ambiguities
.clone();
self.warnings = self.graph.update_schedule(
world,
&mut self.executable,
&ignored_ambiguities,
self.label,
)?;
self.graph.changed = false;
self.executor_initialized = false;
}
if !self.executor_initialized {
self.executor.init(&self.executable);
self.executor_initialized = true;
}
Ok(())
}
/// Returns the [`ScheduleGraph`].
pub fn graph(&self) -> &ScheduleGraph {
&self.graph
}
/// Returns a mutable reference to the [`ScheduleGraph`].
pub fn graph_mut(&mut self) -> &mut ScheduleGraph {
&mut self.graph
}
/// Returns the [`SystemSchedule`].
pub(crate) fn executable(&self) -> &SystemSchedule {
&self.executable
}
/// Iterates the change ticks of all systems in the schedule and clamps any older than
/// [`MAX_CHANGE_AGE`](crate::change_detection::MAX_CHANGE_AGE).
/// This prevents overflow and thus prevents false positives.
pub fn check_change_ticks(&mut self, check: CheckChangeTicks) {
for system in &mut self.executable.systems {
if !is_apply_deferred(system) {
system.check_change_tick(check);
}
}
for conditions in &mut self.executable.system_conditions {
for condition in conditions {
condition.check_change_tick(check);
}
}
for conditions in &mut self.executable.set_conditions {
for condition in conditions {
condition.check_change_tick(check);
}
}
}
/// Directly applies any accumulated [`Deferred`](crate::system::Deferred) system parameters (like [`Commands`](crate::prelude::Commands)) to the `world`.
///
/// Like always, deferred system parameters are applied in the "topological sort order" of the schedule graph.
/// As a result, buffers from one system are only guaranteed to be applied before those of other systems
/// if there is an explicit system ordering between the two systems.
///
/// This is used in rendering to extract data from the main world, storing the data in system buffers,
/// before applying their buffers in a different world.
pub fn apply_deferred(&mut self, world: &mut World) {
for SystemWithAccess { system, .. } in &mut self.executable.systems {
system.apply_deferred(world);
}
}
/// Returns an iterator over all systems in this schedule.
///
/// Note: this method will return [`ScheduleNotInitialized`] if the
/// schedule has never been initialized or run.
pub fn systems(
&self,
) -> Result<impl Iterator<Item = (SystemKey, &ScheduleSystem)> + Sized, ScheduleNotInitialized>
{
if !self.executor_initialized {
return Err(ScheduleNotInitialized);
}
let iter = self
.executable
.system_ids
.iter()
.zip(&self.executable.systems)
.map(|(&node_id, system)| (node_id, &system.system));
Ok(iter)
}
/// Returns the number of systems in this schedule.
pub fn systems_len(&self) -> usize {
if !self.executor_initialized {
self.graph.systems.len()
} else {
self.executable.systems.len()
}
}
/// Returns warnings that were generated during the last call to
/// [`Schedule::initialize`].
pub fn warnings(&self) -> &[ScheduleBuildWarning] {
&self.warnings
}
}
/// Metadata for a [`Schedule`].
///
/// The order isn't optimized; calling `ScheduleGraph::build_schedule` will return a
/// `SystemSchedule` where the order is optimized for execution.
#[derive(Default)]
pub struct ScheduleGraph {
/// Container of systems in the schedule.
pub systems: Systems,
/// Container of system sets in the schedule.
pub system_sets: SystemSets,
/// Directed acyclic graph of the hierarchy (which systems/sets are children of which sets)
hierarchy: Dag<NodeId>,
/// Directed acyclic graph of the dependency (which systems/sets have to run before which other systems/sets)
dependency: Dag<NodeId>,
/// Map of systems in each set
set_systems: DagGroups<SystemSetKey, SystemKey>,
ambiguous_with: UnGraph<NodeId>,
/// Nodes that are allowed to have ambiguous ordering relationship with any other systems.
pub ambiguous_with_all: HashSet<NodeId>,
conflicting_systems: ConflictingSystems,
anonymous_sets: usize,
changed: bool,
settings: ScheduleBuildSettings,
passes: IndexMap<TypeId, Box<dyn ScheduleBuildPassObj>, FixedHasher>,
}
impl ScheduleGraph {
/// Creates an empty [`ScheduleGraph`] with default settings.
pub fn new() -> Self {
Self {
systems: Systems::default(),
system_sets: SystemSets::default(),
hierarchy: Dag::new(),
dependency: Dag::new(),
set_systems: DagGroups::default(),
ambiguous_with: UnGraph::default(),
ambiguous_with_all: HashSet::default(),
conflicting_systems: ConflictingSystems::default(),
anonymous_sets: 0,
changed: false,
settings: default(),
passes: default(),
}
}
/// Returns the [`Dag`] of the hierarchy.
///
/// The hierarchy is a directed acyclic graph of the systems and sets,
/// where an edge denotes that a system or set is the child of another set.
pub fn hierarchy(&self) -> &Dag<NodeId> {
&self.hierarchy
}
/// Returns the [`Dag`] of the dependencies in the schedule.
///
/// Nodes in this graph are systems and sets, and edges denote that
/// a system or set has to run before another system or set.
pub fn dependency(&self) -> &Dag<NodeId> {
&self.dependency
}
/// Returns the list of systems that conflict with each other, i.e. have ambiguities in their access.
///
/// If the `Vec<ComponentId>` is empty, the systems conflict on [`World`] access.
/// Must be called after [`ScheduleGraph::build_schedule`] to be non-empty.
pub fn conflicting_systems(&self) -> &ConflictingSystems {
&self.conflicting_systems
}
fn process_config<T: ProcessScheduleConfig + Schedulable>(
&mut self,
config: ScheduleConfig<T>,
collect_nodes: bool,
) -> ProcessConfigsResult {
ProcessConfigsResult {
densely_chained: true,
nodes: collect_nodes
.then_some(T::process_config(self, config))
.into_iter()
.collect(),
}
}
fn apply_collective_conditions<
T: ProcessScheduleConfig + Schedulable<Metadata = GraphInfo, GroupMetadata = Chain>,
>(
&mut self,
configs: &mut [ScheduleConfigs<T>],
collective_conditions: Vec<BoxedCondition>,
) {
if !collective_conditions.is_empty() {
if let [config] = configs {
for condition in collective_conditions {
config.run_if_dyn(condition);
}
} else {
let set = self.create_anonymous_set();
for config in configs.iter_mut() {
config.in_set_inner(set.intern());
}
let mut set_config = InternedSystemSet::into_config(set.intern());
set_config.conditions.extend(collective_conditions);
self.configure_set_inner(set_config);
}
}
}
/// Adds the config nodes to the graph.
///
/// `collect_nodes` controls whether the `NodeId`s of the processed config nodes are stored in the returned [`ProcessConfigsResult`].
/// `process_config` is the function which processes each individual config node and returns a corresponding `NodeId`.
///
/// The fields on the returned [`ProcessConfigsResult`] are:
/// - `nodes`: a vector of all node ids contained in the nested `ScheduleConfigs`
/// - `densely_chained`: a boolean that is true if all nested nodes are linearly chained (with successive `after` orderings) in the order they are defined
#[track_caller]
fn process_configs<
T: ProcessScheduleConfig + Schedulable<Metadata = GraphInfo, GroupMetadata = Chain>,
>(
&mut self,
configs: ScheduleConfigs<T>,
collect_nodes: bool,
) -> ProcessConfigsResult {
match configs {
ScheduleConfigs::ScheduleConfig(config) => self.process_config(config, collect_nodes),
ScheduleConfigs::Configs {
metadata,
mut configs,
collective_conditions,
} => {
self.apply_collective_conditions(&mut configs, collective_conditions);
let is_chained = matches!(metadata, Chain::Chained(_));
// Densely chained if
// * chained and all configs in the chain are densely chained, or
// * unchained with a single densely chained config
let mut densely_chained = is_chained || configs.len() == 1;
let mut configs = configs.into_iter();
let mut nodes = Vec::new();
let Some(first) = configs.next() else {
return ProcessConfigsResult {
nodes: Vec::new(),
densely_chained,
};
};
let mut previous_result = self.process_configs(first, collect_nodes || is_chained);
densely_chained &= previous_result.densely_chained;
for current in configs {
let current_result = self.process_configs(current, collect_nodes || is_chained);
densely_chained &= current_result.densely_chained;
if let Chain::Chained(chain_options) = &metadata {
// if the current result is densely chained, we only need to chain the first node
let current_nodes = if current_result.densely_chained {
¤t_result.nodes[..1]
} else {
¤t_result.nodes
};
// if the previous result was densely chained, we only need to chain the last node
let previous_nodes = if previous_result.densely_chained {
&previous_result.nodes[previous_result.nodes.len() - 1..]
} else {
&previous_result.nodes
};
self.dependency
.reserve_edges(previous_nodes.len() * current_nodes.len());
for previous_node in previous_nodes {
for current_node in current_nodes {
self.dependency.add_edge(*previous_node, *current_node);
for pass in self.passes.values_mut() {
pass.add_dependency(
*previous_node,
*current_node,
chain_options,
);
}
}
}
}
if collect_nodes {
nodes.append(&mut previous_result.nodes);
}
previous_result = current_result;
}
if collect_nodes {
nodes.append(&mut previous_result.nodes);
}
ProcessConfigsResult {
nodes,
densely_chained,
}
}
}
}
/// Add a [`ScheduleConfig`] to the graph, including its dependencies and conditions.
fn add_system_inner(&mut self, config: ScheduleConfig<ScheduleSystem>) -> SystemKey {
let key = self.systems.insert(config.node, config.conditions);
// graph updates are immediate
self.update_graphs(NodeId::System(key), config.metadata);
key
}
#[track_caller]
fn configure_sets<M>(&mut self, sets: impl IntoScheduleConfigs<InternedSystemSet, M>) {
self.process_configs(sets.into_configs(), false);
}
| 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/schedule/error.rs | crates/bevy_ecs/src/schedule/error.rs | use alloc::{format, string::String, vec::Vec};
use core::fmt::Write as _;
use thiserror::Error;
use crate::{
component::Components,
schedule::{
graph::{
DagCrossDependencyError, DagOverlappingGroupError, DagRedundancyError,
DiGraphToposortError, GraphNodeId,
},
AmbiguousSystemConflictsWarning, ConflictingSystems, NodeId, ScheduleGraph, SystemKey,
SystemSetKey, SystemTypeSetAmbiguityError,
},
world::World,
};
/// Category of errors encountered during [`Schedule::initialize`](crate::schedule::Schedule::initialize).
#[non_exhaustive]
#[derive(Error, Debug)]
pub enum ScheduleBuildError {
/// Tried to topologically sort the hierarchy of system sets.
#[error("Failed to topologically sort the hierarchy of system sets: {0}")]
HierarchySort(DiGraphToposortError<NodeId>),
/// Tried to topologically sort the dependency graph.
#[error("Failed to topologically sort the dependency graph: {0}")]
DependencySort(DiGraphToposortError<NodeId>),
/// Tried to topologically sort the flattened dependency graph.
#[error("Failed to topologically sort the flattened dependency graph: {0}")]
FlatDependencySort(DiGraphToposortError<SystemKey>),
/// Tried to order a system (set) relative to a system set it belongs to.
#[error("`{:?}` and `{:?}` have both `in_set` and `before`-`after` relationships (these might be transitive). This combination is unsolvable as a system cannot run before or after a set it belongs to.", .0.0, .0.1)]
CrossDependency(#[from] DagCrossDependencyError<NodeId>),
/// Tried to order system sets that share systems.
#[error("`{:?}` and `{:?}` have a `before`-`after` relationship (which may be transitive) but share systems.", .0.0, .0.1)]
SetsHaveOrderButIntersect(#[from] DagOverlappingGroupError<SystemSetKey>),
/// Tried to order a system (set) relative to all instances of some system function.
#[error(transparent)]
SystemTypeSetAmbiguity(#[from] SystemTypeSetAmbiguityError),
/// Tried to run a schedule before all of its systems have been initialized.
#[error("Tried to run a schedule before all of its systems have been initialized.")]
Uninitialized,
/// A warning that was elevated to an error.
#[error(transparent)]
Elevated(#[from] ScheduleBuildWarning),
}
/// Category of warnings encountered during [`Schedule::initialize`](crate::schedule::Schedule::initialize).
#[non_exhaustive]
#[derive(Error, Debug)]
pub enum ScheduleBuildWarning {
/// The hierarchy of system sets contains redundant edges.
///
/// This warning is **enabled** by default, but can be disabled by setting
/// [`ScheduleBuildSettings::hierarchy_detection`] to [`LogLevel::Ignore`]
/// or upgraded to a [`ScheduleBuildError`] by setting it to [`LogLevel::Error`].
///
/// [`ScheduleBuildSettings::hierarchy_detection`]: crate::schedule::ScheduleBuildSettings::hierarchy_detection
/// [`LogLevel::Ignore`]: crate::schedule::LogLevel::Ignore
/// [`LogLevel::Error`]: crate::schedule::LogLevel::Error
#[error("The hierarchy of system sets contains redundant edges: {0:?}")]
HierarchyRedundancy(#[from] DagRedundancyError<NodeId>),
/// Systems with conflicting access have indeterminate run order.
///
/// This warning is **disabled** by default, but can be enabled by setting
/// [`ScheduleBuildSettings::ambiguity_detection`] to [`LogLevel::Warn`]
/// or upgraded to a [`ScheduleBuildError`] by setting it to [`LogLevel::Error`].
///
/// [`ScheduleBuildSettings::ambiguity_detection`]: crate::schedule::ScheduleBuildSettings::ambiguity_detection
/// [`LogLevel::Warn`]: crate::schedule::LogLevel::Warn
/// [`LogLevel::Error`]: crate::schedule::LogLevel::Error
#[error(transparent)]
Ambiguity(#[from] AmbiguousSystemConflictsWarning),
}
impl ScheduleBuildError {
/// Renders the error as a human-readable string with node identifiers
/// replaced with their names.
///
/// The given `graph` and `world` are used to resolve the names of the nodes
/// and components involved in the error. The same `graph` and `world`
/// should be used as those used to [`initialize`] the [`Schedule`]. Failure
/// to do so will result in incorrect or incomplete error messages.
///
/// [`initialize`]: crate::schedule::Schedule::initialize
/// [`Schedule`]: crate::schedule::Schedule
pub fn to_string(&self, graph: &ScheduleGraph, world: &World) -> String {
match self {
ScheduleBuildError::HierarchySort(DiGraphToposortError::Loop(node_id)) => {
Self::hierarchy_loop_to_string(node_id, graph)
}
ScheduleBuildError::HierarchySort(DiGraphToposortError::Cycle(cycles)) => {
Self::hierarchy_cycle_to_string(cycles, graph)
}
ScheduleBuildError::DependencySort(DiGraphToposortError::Loop(node_id)) => {
Self::dependency_loop_to_string(node_id, graph)
}
ScheduleBuildError::DependencySort(DiGraphToposortError::Cycle(cycles)) => {
Self::dependency_cycle_to_string(cycles, graph)
}
ScheduleBuildError::FlatDependencySort(DiGraphToposortError::Loop(node_id)) => {
Self::dependency_loop_to_string(&NodeId::System(*node_id), graph)
}
ScheduleBuildError::FlatDependencySort(DiGraphToposortError::Cycle(cycles)) => {
Self::dependency_cycle_to_string(cycles, graph)
}
ScheduleBuildError::CrossDependency(error) => {
Self::cross_dependency_to_string(error, graph)
}
ScheduleBuildError::SetsHaveOrderButIntersect(DagOverlappingGroupError(a, b)) => {
Self::sets_have_order_but_intersect_to_string(a, b, graph)
}
ScheduleBuildError::SystemTypeSetAmbiguity(SystemTypeSetAmbiguityError(set)) => {
Self::system_type_set_ambiguity_to_string(set, graph)
}
ScheduleBuildError::Uninitialized => Self::uninitialized_to_string(),
ScheduleBuildError::Elevated(e) => e.to_string(graph, world),
}
}
fn hierarchy_loop_to_string(node_id: &NodeId, graph: &ScheduleGraph) -> String {
format!(
"{} `{}` contains itself",
node_id.kind(),
graph.get_node_name(node_id)
)
}
fn hierarchy_cycle_to_string(cycles: &[Vec<NodeId>], graph: &ScheduleGraph) -> String {
let mut message = format!("schedule has {} in_set cycle(s):\n", cycles.len());
for (i, cycle) in cycles.iter().enumerate() {
let mut names = cycle.iter().map(|id| (id.kind(), graph.get_node_name(id)));
let (first_kind, first_name) = names.next().unwrap();
writeln!(
message,
"cycle {}: {first_kind} `{first_name}` contains itself",
i + 1,
)
.unwrap();
writeln!(message, "{first_kind} `{first_name}`").unwrap();
for (kind, name) in names.chain(core::iter::once((first_kind, first_name))) {
writeln!(message, " ... which contains {kind} `{name}`").unwrap();
}
writeln!(message).unwrap();
}
message
}
fn hierarchy_redundancy_to_string(
transitive_edges: &[(NodeId, NodeId)],
graph: &ScheduleGraph,
) -> String {
let mut message = String::from("hierarchy contains redundant edge(s)");
for (parent, child) in transitive_edges {
writeln!(
message,
" -- {} `{}` cannot be child of {} `{}`, longer path exists",
child.kind(),
graph.get_node_name(child),
parent.kind(),
graph.get_node_name(parent),
)
.unwrap();
}
message
}
fn dependency_loop_to_string(node_id: &NodeId, graph: &ScheduleGraph) -> String {
format!(
"{} `{}` has been told to run before itself",
node_id.kind(),
graph.get_node_name(node_id)
)
}
fn dependency_cycle_to_string<N: GraphNodeId + Into<NodeId>>(
cycles: &[Vec<N>],
graph: &ScheduleGraph,
) -> String {
let mut message = format!("schedule has {} before/after cycle(s):\n", cycles.len());
for (i, cycle) in cycles.iter().enumerate() {
let mut names = cycle
.iter()
.map(|&id| (id.kind(), graph.get_node_name(&id.into())));
let (first_kind, first_name) = names.next().unwrap();
writeln!(
message,
"cycle {}: {first_kind} `{first_name}` must run before itself",
i + 1,
)
.unwrap();
writeln!(message, "{first_kind} `{first_name}`").unwrap();
for (kind, name) in names.chain(core::iter::once((first_kind, first_name))) {
writeln!(message, " ... which must run before {kind} `{name}`").unwrap();
}
writeln!(message).unwrap();
}
message
}
fn cross_dependency_to_string(
error: &DagCrossDependencyError<NodeId>,
graph: &ScheduleGraph,
) -> String {
let DagCrossDependencyError(a, b) = error;
format!(
"{} `{}` and {} `{}` have both `in_set` and `before`-`after` relationships (these might be transitive). \
This combination is unsolvable as a system cannot run before or after a set it belongs to.",
a.kind(),
graph.get_node_name(a),
b.kind(),
graph.get_node_name(b)
)
}
fn sets_have_order_but_intersect_to_string(
a: &SystemSetKey,
b: &SystemSetKey,
graph: &ScheduleGraph,
) -> String {
format!(
"`{}` and `{}` have a `before`-`after` relationship (which may be transitive) but share systems.",
graph.get_node_name(&NodeId::Set(*a)),
graph.get_node_name(&NodeId::Set(*b)),
)
}
fn system_type_set_ambiguity_to_string(set: &SystemSetKey, graph: &ScheduleGraph) -> String {
let name = graph.get_node_name(&NodeId::Set(*set));
format!(
"Tried to order against `{name}` in a schedule that has more than one `{name}` instance. `{name}` is a \
`SystemTypeSet` and cannot be used for ordering if ambiguous. Use a different set without this restriction."
)
}
pub(crate) fn ambiguity_to_string(
ambiguities: &ConflictingSystems,
graph: &ScheduleGraph,
components: &Components,
) -> String {
let n_ambiguities = ambiguities.len();
let mut message = format!(
"{n_ambiguities} pairs of systems with conflicting data access have indeterminate execution order. \
Consider adding `before`, `after`, or `ambiguous_with` relationships between these:\n",
);
let ambiguities = ambiguities.to_string(graph, components);
for (name_a, name_b, conflicts) in ambiguities {
writeln!(message, " -- {name_a} and {name_b}").unwrap();
if !conflicts.is_empty() {
writeln!(message, " conflict on: {conflicts:?}").unwrap();
} else {
// one or both systems must be exclusive
let world = core::any::type_name::<World>();
writeln!(message, " conflict on: {world}").unwrap();
}
}
message
}
fn uninitialized_to_string() -> String {
String::from("tried to run a schedule before all of its systems have been initialized")
}
}
impl ScheduleBuildWarning {
/// Renders the warning as a human-readable string with node identifiers
/// replaced with their names.
pub fn to_string(&self, graph: &ScheduleGraph, world: &World) -> String {
match self {
ScheduleBuildWarning::HierarchyRedundancy(DagRedundancyError(transitive_edges)) => {
ScheduleBuildError::hierarchy_redundancy_to_string(transitive_edges, graph)
}
ScheduleBuildWarning::Ambiguity(AmbiguousSystemConflictsWarning(ambiguities)) => {
ScheduleBuildError::ambiguity_to_string(ambiguities, graph, world.components())
}
}
}
}
/// Error returned from some `Schedule` methods
#[derive(Error, Debug)]
pub enum ScheduleError {
/// Operation cannot be completed because the schedule has changed and `Schedule::initialize` needs to be called
#[error("Operation cannot be completed because the schedule has changed and `Schedule::initialize` needs to be called")]
Uninitialized,
/// Method could not find set
#[error("Set not found")]
SetNotFound,
/// Schedule not found
#[error("Schedule not found.")]
ScheduleNotFound,
/// Error initializing schedule
#[error("{0}")]
ScheduleBuildError(ScheduleBuildError),
}
impl From<ScheduleBuildError> for ScheduleError {
fn from(value: ScheduleBuildError) -> Self {
Self::ScheduleBuildError(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/schedule/mod.rs | crates/bevy_ecs/src/schedule/mod.rs | //! Contains APIs for ordering systems and executing them on a [`World`](crate::world::World)
mod auto_insert_apply_deferred;
mod condition;
mod config;
mod error;
mod executor;
mod node;
mod pass;
mod schedule;
mod set;
mod stepping;
pub use self::graph::GraphInfo;
pub use self::{condition::*, config::*, error::*, executor::*, node::*, schedule::*, set::*};
pub use pass::ScheduleBuildPass;
/// An implementation of a graph data structure.
pub mod graph;
/// Included optional schedule build passes.
pub mod passes {
pub use crate::schedule::auto_insert_apply_deferred::*;
}
use self::graph::*;
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "trace")]
use alloc::string::ToString;
use alloc::{vec, vec::Vec};
use core::sync::atomic::{AtomicU32, Ordering};
pub use crate::{
prelude::World,
resource::Resource,
schedule::{Schedule, SystemSet},
system::{Res, ResMut},
};
#[derive(SystemSet, Clone, Debug, PartialEq, Eq, Hash)]
enum TestSystems {
A,
B,
C,
D,
X,
}
#[derive(Resource, Default)]
struct SystemOrder(Vec<u32>);
#[derive(Resource, Default)]
struct RunConditionBool(bool);
#[derive(Resource, Default)]
struct Counter(AtomicU32);
fn make_exclusive_system(tag: u32) -> impl FnMut(&mut World) {
move |world| world.resource_mut::<SystemOrder>().0.push(tag)
}
fn make_function_system(tag: u32) -> impl FnMut(ResMut<SystemOrder>) {
move |mut resource: ResMut<SystemOrder>| resource.0.push(tag)
}
fn named_system(mut resource: ResMut<SystemOrder>) {
resource.0.push(u32::MAX);
}
fn named_exclusive_system(world: &mut World) {
world.resource_mut::<SystemOrder>().0.push(u32::MAX);
}
fn counting_system(counter: Res<Counter>) {
counter.0.fetch_add(1, Ordering::Relaxed);
}
mod system_execution {
use super::*;
#[test]
fn run_system() {
let mut world = World::default();
let mut schedule = Schedule::default();
world.init_resource::<SystemOrder>();
schedule.add_systems(make_function_system(0));
schedule.run(&mut world);
assert_eq!(world.resource::<SystemOrder>().0, vec![0]);
}
#[test]
fn run_exclusive_system() {
let mut world = World::default();
let mut schedule = Schedule::default();
world.init_resource::<SystemOrder>();
schedule.add_systems(make_exclusive_system(0));
schedule.run(&mut world);
assert_eq!(world.resource::<SystemOrder>().0, vec![0]);
}
#[test]
#[cfg(not(miri))]
fn parallel_execution() {
use alloc::sync::Arc;
use bevy_tasks::{ComputeTaskPool, TaskPool};
use std::sync::Barrier;
let mut world = World::default();
let mut schedule = Schedule::default();
let thread_count = ComputeTaskPool::get_or_init(TaskPool::default).thread_num();
let barrier = Arc::new(Barrier::new(thread_count));
for _ in 0..thread_count {
let inner = barrier.clone();
schedule.add_systems(move || {
inner.wait();
});
}
schedule.run(&mut world);
}
}
mod system_ordering {
use super::*;
#[test]
fn order_systems() {
let mut world = World::default();
let mut schedule = Schedule::default();
world.init_resource::<SystemOrder>();
schedule.add_systems((
named_system,
make_function_system(1).before(named_system),
make_function_system(0)
.after(named_system)
.in_set(TestSystems::A),
));
schedule.run(&mut world);
assert_eq!(world.resource::<SystemOrder>().0, vec![1, u32::MAX, 0]);
world.insert_resource(SystemOrder::default());
assert_eq!(world.resource::<SystemOrder>().0, vec![]);
// modify the schedule after it's been initialized and test ordering with sets
schedule.configure_sets(TestSystems::A.after(named_system));
schedule.add_systems((
make_function_system(3)
.before(TestSystems::A)
.after(named_system),
make_function_system(4).after(TestSystems::A),
));
schedule.run(&mut world);
assert_eq!(
world.resource::<SystemOrder>().0,
vec![1, u32::MAX, 3, 0, 4]
);
}
#[test]
fn order_exclusive_systems() {
let mut world = World::default();
let mut schedule = Schedule::default();
world.init_resource::<SystemOrder>();
schedule.add_systems((
named_exclusive_system,
make_exclusive_system(1).before(named_exclusive_system),
make_exclusive_system(0).after(named_exclusive_system),
));
schedule.run(&mut world);
assert_eq!(world.resource::<SystemOrder>().0, vec![1, u32::MAX, 0]);
}
#[test]
fn add_systems_correct_order() {
let mut world = World::new();
let mut schedule = Schedule::default();
world.init_resource::<SystemOrder>();
schedule.add_systems(
(
make_function_system(0),
make_function_system(1),
make_exclusive_system(2),
make_function_system(3),
)
.chain(),
);
schedule.run(&mut world);
assert_eq!(world.resource::<SystemOrder>().0, vec![0, 1, 2, 3]);
}
#[test]
fn add_systems_correct_order_nested() {
let mut world = World::new();
let mut schedule = Schedule::default();
world.init_resource::<SystemOrder>();
schedule.add_systems(
(
(make_function_system(0), make_function_system(1)).chain(),
make_function_system(2),
(make_function_system(3), make_function_system(4)).chain(),
(
make_function_system(5),
(make_function_system(6), make_function_system(7)),
),
(
(make_function_system(8), make_function_system(9)).chain(),
make_function_system(10),
),
)
.chain(),
);
schedule.run(&mut world);
let order = &world.resource::<SystemOrder>().0;
assert_eq!(
&order[0..5],
&[0, 1, 2, 3, 4],
"first five items should be exactly ordered"
);
let unordered = &order[5..8];
assert!(
unordered.contains(&5) && unordered.contains(&6) && unordered.contains(&7),
"unordered must be 5, 6, and 7 in any order"
);
let partially_ordered = &order[8..11];
assert!(
partially_ordered == [8, 9, 10] || partially_ordered == [10, 8, 9],
"partially_ordered must be [8, 9, 10] or [10, 8, 9]"
);
assert_eq!(order.len(), 11, "must have exactly 11 order entries");
}
}
mod conditions {
use crate::{
change_detection::DetectChanges,
error::{ignore, DefaultErrorHandler, Result},
};
use super::*;
#[test]
fn system_with_condition_bool() {
let mut world = World::default();
let mut schedule = Schedule::default();
world.init_resource::<RunConditionBool>();
world.init_resource::<SystemOrder>();
schedule.add_systems(
make_function_system(0).run_if(|condition: Res<RunConditionBool>| condition.0),
);
schedule.run(&mut world);
assert_eq!(world.resource::<SystemOrder>().0, vec![]);
world.resource_mut::<RunConditionBool>().0 = true;
schedule.run(&mut world);
assert_eq!(world.resource::<SystemOrder>().0, vec![0]);
}
#[test]
fn system_with_condition_result_bool() {
let mut world = World::default();
world.insert_resource(DefaultErrorHandler(ignore));
let mut schedule = Schedule::default();
world.init_resource::<SystemOrder>();
schedule.add_systems((
make_function_system(0).run_if(|| -> Result<bool> { Err(core::fmt::Error.into()) }),
make_function_system(1).run_if(|| -> Result<bool> { Ok(false) }),
));
schedule.run(&mut world);
assert_eq!(world.resource::<SystemOrder>().0, vec![]);
schedule.add_systems(make_function_system(2).run_if(|| -> Result<bool> { Ok(true) }));
schedule.run(&mut world);
assert_eq!(world.resource::<SystemOrder>().0, vec![2]);
}
#[test]
fn systems_with_distributive_condition() {
let mut world = World::default();
let mut schedule = Schedule::default();
world.insert_resource(RunConditionBool(true));
world.init_resource::<SystemOrder>();
fn change_condition(mut condition: ResMut<RunConditionBool>) {
condition.0 = false;
}
schedule.add_systems(
(
make_function_system(0),
change_condition,
make_function_system(1),
)
.chain()
.distributive_run_if(|condition: Res<RunConditionBool>| condition.0),
);
schedule.run(&mut world);
assert_eq!(world.resource::<SystemOrder>().0, vec![0]);
}
#[test]
fn run_exclusive_system_with_condition() {
let mut world = World::default();
let mut schedule = Schedule::default();
world.init_resource::<RunConditionBool>();
world.init_resource::<SystemOrder>();
schedule.add_systems(
make_exclusive_system(0).run_if(|condition: Res<RunConditionBool>| condition.0),
);
schedule.run(&mut world);
assert_eq!(world.resource::<SystemOrder>().0, vec![]);
world.resource_mut::<RunConditionBool>().0 = true;
schedule.run(&mut world);
assert_eq!(world.resource::<SystemOrder>().0, vec![0]);
}
#[test]
fn multiple_conditions_on_system() {
let mut world = World::default();
let mut schedule = Schedule::default();
world.init_resource::<Counter>();
schedule.add_systems((
counting_system.run_if(|| false).run_if(|| false),
counting_system.run_if(|| true).run_if(|| false),
counting_system.run_if(|| false).run_if(|| true),
counting_system.run_if(|| true).run_if(|| true),
));
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
}
#[test]
fn multiple_conditions_on_system_sets() {
let mut world = World::default();
let mut schedule = Schedule::default();
world.init_resource::<Counter>();
schedule.configure_sets(TestSystems::A.run_if(|| false).run_if(|| false));
schedule.add_systems(counting_system.in_set(TestSystems::A));
schedule.configure_sets(TestSystems::B.run_if(|| true).run_if(|| false));
schedule.add_systems(counting_system.in_set(TestSystems::B));
schedule.configure_sets(TestSystems::C.run_if(|| false).run_if(|| true));
schedule.add_systems(counting_system.in_set(TestSystems::C));
schedule.configure_sets(TestSystems::D.run_if(|| true).run_if(|| true));
schedule.add_systems(counting_system.in_set(TestSystems::D));
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
}
#[test]
fn systems_nested_in_system_sets() {
let mut world = World::default();
let mut schedule = Schedule::default();
world.init_resource::<Counter>();
schedule.configure_sets(TestSystems::A.run_if(|| false));
schedule.add_systems(counting_system.in_set(TestSystems::A).run_if(|| false));
schedule.configure_sets(TestSystems::B.run_if(|| true));
schedule.add_systems(counting_system.in_set(TestSystems::B).run_if(|| false));
schedule.configure_sets(TestSystems::C.run_if(|| false));
schedule.add_systems(counting_system.in_set(TestSystems::C).run_if(|| true));
schedule.configure_sets(TestSystems::D.run_if(|| true));
schedule.add_systems(counting_system.in_set(TestSystems::D).run_if(|| true));
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
}
#[test]
fn system_conditions_and_change_detection() {
#[derive(Resource, Default)]
struct Bool2(pub bool);
let mut world = World::default();
world.init_resource::<Counter>();
world.init_resource::<RunConditionBool>();
world.init_resource::<Bool2>();
let mut schedule = Schedule::default();
schedule.add_systems(
counting_system
.run_if(|res1: Res<RunConditionBool>| res1.is_changed())
.run_if(|res2: Res<Bool2>| res2.is_changed()),
);
// both resource were just added.
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
// nothing has changed
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
// RunConditionBool has changed, but counting_system did not run
world.get_resource_mut::<RunConditionBool>().unwrap().0 = false;
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
// internal state for the bool2 run criteria was updated in the
// previous run, so system still does not run
world.get_resource_mut::<Bool2>().unwrap().0 = false;
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
// internal state for bool2 was updated, so system still does not run
world.get_resource_mut::<RunConditionBool>().unwrap().0 = false;
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
// now check that it works correctly changing Bool2 first and then RunConditionBool
world.get_resource_mut::<Bool2>().unwrap().0 = false;
world.get_resource_mut::<RunConditionBool>().unwrap().0 = false;
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 2);
}
#[test]
fn system_set_conditions_and_change_detection() {
#[derive(Resource, Default)]
struct Bool2(pub bool);
let mut world = World::default();
world.init_resource::<Counter>();
world.init_resource::<RunConditionBool>();
world.init_resource::<Bool2>();
let mut schedule = Schedule::default();
schedule.configure_sets(
TestSystems::A
.run_if(|res1: Res<RunConditionBool>| res1.is_changed())
.run_if(|res2: Res<Bool2>| res2.is_changed()),
);
schedule.add_systems(counting_system.in_set(TestSystems::A));
// both resource were just added.
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
// nothing has changed
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
// RunConditionBool has changed, but counting_system did not run
world.get_resource_mut::<RunConditionBool>().unwrap().0 = false;
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
// internal state for the bool2 run criteria was updated in the
// previous run, so system still does not run
world.get_resource_mut::<Bool2>().unwrap().0 = false;
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
// internal state for bool2 was updated, so system still does not run
world.get_resource_mut::<RunConditionBool>().unwrap().0 = false;
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
// the system only runs when both are changed on the same run
world.get_resource_mut::<Bool2>().unwrap().0 = false;
world.get_resource_mut::<RunConditionBool>().unwrap().0 = false;
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 2);
}
#[test]
fn mixed_conditions_and_change_detection() {
#[derive(Resource, Default)]
struct Bool2(pub bool);
let mut world = World::default();
world.init_resource::<Counter>();
world.init_resource::<RunConditionBool>();
world.init_resource::<Bool2>();
let mut schedule = Schedule::default();
schedule.configure_sets(
TestSystems::A.run_if(|res1: Res<RunConditionBool>| res1.is_changed()),
);
schedule.add_systems(
counting_system
.run_if(|res2: Res<Bool2>| res2.is_changed())
.in_set(TestSystems::A),
);
// both resource were just added.
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
// nothing has changed
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
// RunConditionBool has changed, but counting_system did not run
world.get_resource_mut::<RunConditionBool>().unwrap().0 = false;
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
// we now only change bool2 and the system also should not run
world.get_resource_mut::<Bool2>().unwrap().0 = false;
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
// internal state for the bool2 run criteria was updated in the
// previous run, so system still does not run
world.get_resource_mut::<RunConditionBool>().unwrap().0 = false;
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 1);
// the system only runs when both are changed on the same run
world.get_resource_mut::<Bool2>().unwrap().0 = false;
world.get_resource_mut::<RunConditionBool>().unwrap().0 = false;
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0.load(Ordering::Relaxed), 2);
}
}
mod schedule_build_errors {
use super::*;
#[test]
fn dependency_loop() {
let mut schedule = Schedule::default();
schedule.configure_sets(TestSystems::X.after(TestSystems::X));
let mut world = World::new();
let result = schedule.initialize(&mut world);
assert!(matches!(
result,
Err(ScheduleBuildError::DependencySort(
DiGraphToposortError::Loop(_)
))
));
}
#[test]
fn dependency_loop_from_chain() {
let mut schedule = Schedule::default();
schedule.configure_sets((TestSystems::X, TestSystems::X).chain());
let mut world = World::new();
let result = schedule.initialize(&mut world);
assert!(matches!(
result,
Err(ScheduleBuildError::DependencySort(
DiGraphToposortError::Loop(_)
))
));
}
#[test]
fn dependency_cycle() {
let mut world = World::new();
let mut schedule = Schedule::default();
schedule.configure_sets(TestSystems::A.after(TestSystems::B));
schedule.configure_sets(TestSystems::B.after(TestSystems::A));
let result = schedule.initialize(&mut world);
assert!(matches!(
result,
Err(ScheduleBuildError::DependencySort(
DiGraphToposortError::Cycle(_)
))
));
fn foo() {}
fn bar() {}
let mut world = World::new();
let mut schedule = Schedule::default();
schedule.add_systems((foo.after(bar), bar.after(foo)));
let result = schedule.initialize(&mut world);
assert!(matches!(
result,
Err(ScheduleBuildError::FlatDependencySort(
DiGraphToposortError::Cycle(_)
))
));
}
#[test]
fn hierarchy_loop() {
let mut schedule = Schedule::default();
schedule.configure_sets(TestSystems::X.in_set(TestSystems::X));
let mut world = World::new();
let result = schedule.initialize(&mut world);
assert!(matches!(
result,
Err(ScheduleBuildError::HierarchySort(
DiGraphToposortError::Loop(_)
))
));
}
#[test]
fn hierarchy_cycle() {
let mut world = World::new();
let mut schedule = Schedule::default();
schedule.configure_sets(TestSystems::A.in_set(TestSystems::B));
schedule.configure_sets(TestSystems::B.in_set(TestSystems::A));
let result = schedule.initialize(&mut world);
assert!(matches!(
result,
Err(ScheduleBuildError::HierarchySort(
DiGraphToposortError::Cycle(_)
))
));
}
#[test]
fn system_type_set_ambiguity() {
// Define some systems.
fn foo() {}
fn bar() {}
let mut world = World::new();
let mut schedule = Schedule::default();
// Schedule `bar` to run after `foo`.
schedule.add_systems((foo, bar.after(foo)));
// There's only one `foo`, so it's fine.
let result = schedule.initialize(&mut world);
assert!(result.is_ok());
// Schedule another `foo`.
schedule.add_systems(foo);
// When there are multiple instances of `foo`, dependencies on
// `foo` are no longer allowed. Too much ambiguity.
let result = schedule.initialize(&mut world);
assert!(matches!(
result,
Err(ScheduleBuildError::SystemTypeSetAmbiguity(_))
));
// same goes for `ambiguous_with`
let mut schedule = Schedule::default();
schedule.add_systems(foo);
schedule.add_systems(bar.ambiguous_with(foo));
let result = schedule.initialize(&mut world);
assert!(result.is_ok());
schedule.add_systems(foo);
let result = schedule.initialize(&mut world);
assert!(matches!(
result,
Err(ScheduleBuildError::SystemTypeSetAmbiguity(_))
));
}
#[test]
#[should_panic]
fn configure_system_type_set() {
fn foo() {}
let mut schedule = Schedule::default();
schedule.configure_sets(foo.into_system_set());
}
#[test]
fn hierarchy_redundancy() {
let mut world = World::new();
let mut schedule = Schedule::default();
schedule.set_build_settings(ScheduleBuildSettings {
hierarchy_detection: LogLevel::Error,
..Default::default()
});
// Add `A`.
schedule.configure_sets(TestSystems::A);
// Add `B` as child of `A`.
schedule.configure_sets(TestSystems::B.in_set(TestSystems::A));
// Add `X` as child of both `A` and `B`.
schedule.configure_sets(TestSystems::X.in_set(TestSystems::A).in_set(TestSystems::B));
// `X` cannot be the `A`'s child and grandchild at the same time.
let result = schedule.initialize(&mut world);
assert!(matches!(
result,
Err(ScheduleBuildError::Elevated(
ScheduleBuildWarning::HierarchyRedundancy(_)
))
));
}
#[test]
fn cross_dependency() {
let mut world = World::new();
let mut schedule = Schedule::default();
// Add `B` and give it both kinds of relationships with `A`.
schedule.configure_sets(TestSystems::B.in_set(TestSystems::A));
schedule.configure_sets(TestSystems::B.after(TestSystems::A));
let result = schedule.initialize(&mut world);
assert!(matches!(
result,
Err(ScheduleBuildError::CrossDependency(_))
));
}
#[test]
fn sets_have_order_but_intersect() {
let mut world = World::new();
let mut schedule = Schedule::default();
fn foo() {}
// Add `foo` to both `A` and `C`.
schedule.add_systems(foo.in_set(TestSystems::A).in_set(TestSystems::C));
// Order `A -> B -> C`.
schedule.configure_sets((
TestSystems::A,
TestSystems::B.after(TestSystems::A),
TestSystems::C.after(TestSystems::B),
));
let result = schedule.initialize(&mut world);
// `foo` can't be in both `A` and `C` because they can't run at the same time.
assert!(matches!(
result,
Err(ScheduleBuildError::SetsHaveOrderButIntersect(_))
));
}
#[test]
fn ambiguity() {
#[derive(Resource)]
struct X;
fn res_ref(_x: Res<X>) {}
fn res_mut(_x: ResMut<X>) {}
let mut world = World::new();
let mut schedule = Schedule::default();
schedule.set_build_settings(ScheduleBuildSettings {
ambiguity_detection: LogLevel::Error,
..Default::default()
});
schedule.add_systems((res_ref, res_mut));
let result = schedule.initialize(&mut world);
assert!(matches!(
result,
Err(ScheduleBuildError::Elevated(
ScheduleBuildWarning::Ambiguity(_)
))
));
}
}
mod system_ambiguity {
#[cfg(feature = "trace")]
use alloc::collections::BTreeSet;
use super::*;
use crate::prelude::*;
#[derive(Resource)]
struct R;
#[derive(Component)]
struct A;
#[derive(Component)]
struct B;
#[derive(Message)]
struct E;
fn empty_system() {}
fn res_system(_res: Res<R>) {}
fn resmut_system(_res: ResMut<R>) {}
fn nonsend_system(_ns: NonSend<R>) {}
fn nonsendmut_system(_ns: NonSendMut<R>) {}
fn read_component_system(_query: Query<&A>) {}
fn write_component_system(_query: Query<&mut A>) {}
fn with_filtered_component_system(_query: Query<&mut A, With<B>>) {}
fn without_filtered_component_system(_query: Query<&mut A, Without<B>>) {}
fn entity_ref_system(_query: Query<EntityRef>) {}
fn entity_mut_system(_query: Query<EntityMut>) {}
fn message_reader_system(_reader: MessageReader<E>) {}
fn message_writer_system(_writer: MessageWriter<E>) {}
fn message_resource_system(_events: ResMut<Messages<E>>) {}
fn read_world_system(_world: &World) {}
fn write_world_system(_world: &mut World) {}
// Tests for conflict detection
#[test]
fn one_of_everything() {
let mut world = World::new();
world.insert_resource(R);
world.spawn(A);
world.init_resource::<Messages<E>>();
let mut schedule = Schedule::default();
schedule
// nonsendmut system deliberately conflicts with resmut system
.add_systems((resmut_system, write_component_system, message_writer_system));
let _ = schedule.initialize(&mut world);
assert_eq!(schedule.graph().conflicting_systems().len(), 0);
}
#[test]
fn read_only() {
let mut world = World::new();
world.insert_resource(R);
world.spawn(A);
world.init_resource::<Messages<E>>();
let mut schedule = Schedule::default();
schedule.add_systems((
empty_system,
empty_system,
res_system,
res_system,
nonsend_system,
nonsend_system,
read_component_system,
read_component_system,
entity_ref_system,
entity_ref_system,
message_reader_system,
message_reader_system,
read_world_system,
read_world_system,
));
let _ = schedule.initialize(&mut world);
assert_eq!(schedule.graph().conflicting_systems().len(), 0);
}
#[test]
fn read_world() {
let mut world = World::new();
world.insert_resource(R);
world.spawn(A);
world.init_resource::<Messages<E>>();
let mut schedule = Schedule::default();
schedule.add_systems((
resmut_system,
write_component_system,
message_writer_system,
read_world_system,
));
let _ = schedule.initialize(&mut world);
assert_eq!(schedule.graph().conflicting_systems().len(), 3);
}
#[test]
fn resources() {
let mut world = World::new();
world.insert_resource(R);
let mut schedule = Schedule::default();
schedule.add_systems((resmut_system, res_system));
let _ = schedule.initialize(&mut world);
assert_eq!(schedule.graph().conflicting_systems().len(), 1);
}
#[test]
fn nonsend() {
let mut world = World::new();
world.insert_resource(R);
let mut schedule = Schedule::default();
schedule.add_systems((nonsendmut_system, nonsend_system));
let _ = schedule.initialize(&mut world);
assert_eq!(schedule.graph().conflicting_systems().len(), 1);
}
#[test]
fn components() {
let mut world = World::new();
world.spawn(A);
let mut schedule = Schedule::default();
schedule.add_systems((read_component_system, write_component_system));
let _ = schedule.initialize(&mut world);
assert_eq!(schedule.graph().conflicting_systems().len(), 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/schedule/stepping.rs | crates/bevy_ecs/src/schedule/stepping.rs | use crate::{
resource::Resource,
schedule::{InternedScheduleLabel, NodeId, Schedule, ScheduleLabel, SystemKey},
system::{IntoSystem, ResMut},
};
use alloc::vec::Vec;
use bevy_platform::collections::HashMap;
use bevy_utils::TypeIdMap;
use core::any::TypeId;
use fixedbitset::FixedBitSet;
use log::{info, warn};
use thiserror::Error;
#[cfg(not(feature = "bevy_debug_stepping"))]
use log::error;
#[cfg(test)]
use log::debug;
#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
enum Action {
/// Stepping is disabled; run all systems
#[default]
RunAll,
/// Stepping is enabled, but we're only running required systems this frame
Waiting,
/// Stepping is enabled; run all systems until the end of the frame, or
/// until we encounter a system marked with [`SystemBehavior::Break`] or all
/// systems in the frame have run.
Continue,
/// stepping is enabled; only run the next system in our step list
Step,
}
#[derive(Debug, Copy, Clone)]
enum SystemBehavior {
/// System will always run regardless of stepping action
AlwaysRun,
/// System will never run while stepping is enabled
NeverRun,
/// When [`Action::Waiting`] this system will not be run
/// When [`Action::Step`] this system will be stepped
/// When [`Action::Continue`] system execution will stop before executing
/// this system unless its the first system run when continuing
Break,
/// When [`Action::Waiting`] this system will not be run
/// When [`Action::Step`] this system will be stepped
/// When [`Action::Continue`] this system will be run
Continue,
}
// schedule_order index, and schedule start point
#[derive(Debug, Default, Clone, Copy)]
struct Cursor {
/// index within `Stepping::schedule_order`
pub schedule: usize,
/// index within the schedule's system list
pub system: usize,
}
// Two methods of referring to Systems, via TypeId, or per-Schedule NodeId
enum SystemIdentifier {
Type(TypeId),
Node(NodeId),
}
/// Updates to [`Stepping::schedule_states`] that will be applied at the start
/// of the next render frame
enum Update {
/// Set the action stepping will perform for this render frame
SetAction(Action),
/// Enable stepping for this schedule
AddSchedule(InternedScheduleLabel),
/// Disable stepping for this schedule
RemoveSchedule(InternedScheduleLabel),
/// Clear any system-specific behaviors for this schedule
ClearSchedule(InternedScheduleLabel),
/// Set a system-specific behavior for this schedule & system
SetBehavior(InternedScheduleLabel, SystemIdentifier, SystemBehavior),
/// Clear any system-specific behavior for this schedule & system
ClearBehavior(InternedScheduleLabel, SystemIdentifier),
}
#[derive(Error, Debug)]
#[error("not available until all configured schedules have been run; try again next frame")]
pub struct NotReady;
#[derive(Resource, Default)]
/// Resource for controlling system stepping behavior
pub struct Stepping {
// [`ScheduleState`] for each [`Schedule`] with stepping enabled
schedule_states: HashMap<InternedScheduleLabel, ScheduleState>,
// dynamically generated [`Schedule`] order
schedule_order: Vec<InternedScheduleLabel>,
// current position in the stepping frame
cursor: Cursor,
// index in [`schedule_order`] of the last schedule to call `skipped_systems()`
previous_schedule: Option<usize>,
// Action to perform during this render frame
action: Action,
// Updates apply at the start of the next render frame
updates: Vec<Update>,
}
impl core::fmt::Debug for Stepping {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"Stepping {{ action: {:?}, schedules: {:?}, order: {:?}",
self.action,
self.schedule_states.keys(),
self.schedule_order
)?;
if self.action != Action::RunAll {
let Cursor { schedule, system } = self.cursor;
match self.schedule_order.get(schedule) {
Some(label) => write!(f, "cursor: {label:?}[{system}], ")?,
None => write!(f, "cursor: None, ")?,
};
}
write!(f, "}}")
}
}
impl Stepping {
/// Create a new instance of the `Stepping` resource.
pub fn new() -> Self {
Stepping::default()
}
/// System to call denoting that a new render frame has begun
///
/// Note: This system is automatically added to the default `MainSchedule`.
pub fn begin_frame(stepping: Option<ResMut<Self>>) {
if let Some(mut stepping) = stepping {
stepping.next_frame();
}
}
/// Return the list of schedules with stepping enabled in the order
/// they are executed in.
pub fn schedules(&self) -> Result<&Vec<InternedScheduleLabel>, NotReady> {
if self.schedule_order.len() == self.schedule_states.len() {
Ok(&self.schedule_order)
} else {
Err(NotReady)
}
}
/// Return our current position within the stepping frame
///
/// NOTE: This function **will** return `None` during normal execution with
/// stepping enabled. This can happen at the end of the stepping frame
/// after the last system has been run, but before the start of the next
/// render frame.
pub fn cursor(&self) -> Option<(InternedScheduleLabel, NodeId)> {
if self.action == Action::RunAll {
return None;
}
let label = self.schedule_order.get(self.cursor.schedule)?;
let state = self.schedule_states.get(label)?;
state
.node_ids
.get(self.cursor.system)
.map(|node_id| (*label, NodeId::System(*node_id)))
}
/// Enable stepping for the provided schedule
pub fn add_schedule(&mut self, schedule: impl ScheduleLabel) -> &mut Self {
self.updates.push(Update::AddSchedule(schedule.intern()));
self
}
/// Disable stepping for the provided schedule
///
/// NOTE: This function will also clear any system-specific behaviors that
/// may have been configured.
pub fn remove_schedule(&mut self, schedule: impl ScheduleLabel) -> &mut Self {
self.updates.push(Update::RemoveSchedule(schedule.intern()));
self
}
/// Clear behavior set for all systems in the provided [`Schedule`]
pub fn clear_schedule(&mut self, schedule: impl ScheduleLabel) -> &mut Self {
self.updates.push(Update::ClearSchedule(schedule.intern()));
self
}
/// Begin stepping at the start of the next frame
pub fn enable(&mut self) -> &mut Self {
#[cfg(feature = "bevy_debug_stepping")]
self.updates.push(Update::SetAction(Action::Waiting));
#[cfg(not(feature = "bevy_debug_stepping"))]
error!(
"Stepping cannot be enabled; \
bevy was compiled without the bevy_debug_stepping feature"
);
self
}
/// Disable stepping, resume normal systems execution
pub fn disable(&mut self) -> &mut Self {
self.updates.push(Update::SetAction(Action::RunAll));
self
}
/// Check if stepping is enabled
pub fn is_enabled(&self) -> bool {
self.action != Action::RunAll
}
/// Run the next system during the next render frame
///
/// NOTE: This will have no impact unless stepping has been enabled
pub fn step_frame(&mut self) -> &mut Self {
self.updates.push(Update::SetAction(Action::Step));
self
}
/// Run all remaining systems in the stepping frame during the next render
/// frame
///
/// NOTE: This will have no impact unless stepping has been enabled
pub fn continue_frame(&mut self) -> &mut Self {
self.updates.push(Update::SetAction(Action::Continue));
self
}
/// Ensure this system always runs when stepping is enabled
///
/// Note: if the system is run multiple times in the [`Schedule`], this
/// will apply for all instances of the system.
pub fn always_run<Marker>(
&mut self,
schedule: impl ScheduleLabel,
system: impl IntoSystem<(), (), Marker>,
) -> &mut Self {
let type_id = system.system_type_id();
self.updates.push(Update::SetBehavior(
schedule.intern(),
SystemIdentifier::Type(type_id),
SystemBehavior::AlwaysRun,
));
self
}
/// Ensure this system instance always runs when stepping is enabled
pub fn always_run_node(&mut self, schedule: impl ScheduleLabel, node: NodeId) -> &mut Self {
self.updates.push(Update::SetBehavior(
schedule.intern(),
SystemIdentifier::Node(node),
SystemBehavior::AlwaysRun,
));
self
}
/// Ensure this system never runs when stepping is enabled
pub fn never_run<Marker>(
&mut self,
schedule: impl ScheduleLabel,
system: impl IntoSystem<(), (), Marker>,
) -> &mut Self {
let type_id = system.system_type_id();
self.updates.push(Update::SetBehavior(
schedule.intern(),
SystemIdentifier::Type(type_id),
SystemBehavior::NeverRun,
));
self
}
/// Ensure this system instance never runs when stepping is enabled
pub fn never_run_node(&mut self, schedule: impl ScheduleLabel, node: NodeId) -> &mut Self {
self.updates.push(Update::SetBehavior(
schedule.intern(),
SystemIdentifier::Node(node),
SystemBehavior::NeverRun,
));
self
}
/// Add a breakpoint for system
pub fn set_breakpoint<Marker>(
&mut self,
schedule: impl ScheduleLabel,
system: impl IntoSystem<(), (), Marker>,
) -> &mut Self {
let type_id = system.system_type_id();
self.updates.push(Update::SetBehavior(
schedule.intern(),
SystemIdentifier::Type(type_id),
SystemBehavior::Break,
));
self
}
/// Add a breakpoint for system instance
pub fn set_breakpoint_node(&mut self, schedule: impl ScheduleLabel, node: NodeId) -> &mut Self {
self.updates.push(Update::SetBehavior(
schedule.intern(),
SystemIdentifier::Node(node),
SystemBehavior::Break,
));
self
}
/// Clear a breakpoint for the system
pub fn clear_breakpoint<Marker>(
&mut self,
schedule: impl ScheduleLabel,
system: impl IntoSystem<(), (), Marker>,
) -> &mut Self {
self.clear_system(schedule, system);
self
}
/// clear a breakpoint for system instance
pub fn clear_breakpoint_node(
&mut self,
schedule: impl ScheduleLabel,
node: NodeId,
) -> &mut Self {
self.clear_node(schedule, node);
self
}
/// Clear any behavior set for the system
pub fn clear_system<Marker>(
&mut self,
schedule: impl ScheduleLabel,
system: impl IntoSystem<(), (), Marker>,
) -> &mut Self {
let type_id = system.system_type_id();
self.updates.push(Update::ClearBehavior(
schedule.intern(),
SystemIdentifier::Type(type_id),
));
self
}
/// clear a breakpoint for system instance
pub fn clear_node(&mut self, schedule: impl ScheduleLabel, node: NodeId) -> &mut Self {
self.updates.push(Update::ClearBehavior(
schedule.intern(),
SystemIdentifier::Node(node),
));
self
}
/// lookup the first system for the supplied schedule index
fn first_system_index_for_schedule(&self, index: usize) -> usize {
let Some(label) = self.schedule_order.get(index) else {
return 0;
};
let Some(state) = self.schedule_states.get(label) else {
return 0;
};
state.first.unwrap_or(0)
}
/// Move the cursor to the start of the first schedule
fn reset_cursor(&mut self) {
self.cursor = Cursor {
schedule: 0,
system: self.first_system_index_for_schedule(0),
};
}
/// Advance schedule states for the next render frame
fn next_frame(&mut self) {
// if stepping is enabled; reset our internal state for the start of
// the next frame
if self.action != Action::RunAll {
self.action = Action::Waiting;
self.previous_schedule = None;
// if the cursor passed the last schedule, reset it
if self.cursor.schedule >= self.schedule_order.len() {
self.reset_cursor();
}
}
if self.updates.is_empty() {
return;
}
let mut reset_cursor = false;
for update in self.updates.drain(..) {
match update {
Update::SetAction(Action::RunAll) => {
self.action = Action::RunAll;
reset_cursor = true;
}
Update::SetAction(action) => {
// This match block is really just to filter out invalid
// transitions, and add debugging messages for permitted
// transitions. Any action transition that falls through
// this match block will be performed.
#[expect(
clippy::match_same_arms,
reason = "Readability would be negatively impacted by combining the `(Waiting, RunAll)` and `(Continue, RunAll)` match arms."
)]
match (self.action, action) {
// ignore non-transition updates, and prevent a call to
// enable() from overwriting a step or continue call
(Action::RunAll, Action::RunAll)
| (Action::Waiting, Action::Waiting)
| (Action::Continue, Action::Continue)
| (Action::Step, Action::Step)
| (Action::Continue, Action::Waiting)
| (Action::Step, Action::Waiting) => continue,
// when stepping is disabled
(Action::RunAll, Action::Waiting) => info!("enabled stepping"),
(Action::RunAll, _) => {
warn!(
"stepping not enabled; call Stepping::enable() \
before step_frame() or continue_frame()"
);
continue;
}
// stepping enabled; waiting
(Action::Waiting, Action::RunAll) => info!("disabled stepping"),
(Action::Waiting, Action::Continue) => info!("continue frame"),
(Action::Waiting, Action::Step) => info!("step frame"),
// stepping enabled; continue frame
(Action::Continue, Action::RunAll) => info!("disabled stepping"),
(Action::Continue, Action::Step) => {
warn!("ignoring step_frame(); already continuing next frame");
continue;
}
// stepping enabled; step frame
(Action::Step, Action::RunAll) => info!("disabled stepping"),
(Action::Step, Action::Continue) => {
warn!("ignoring continue_frame(); already stepping next frame");
continue;
}
}
// permitted action transition; make the change
self.action = action;
}
Update::AddSchedule(l) => {
self.schedule_states.insert(l, ScheduleState::default());
}
Update::RemoveSchedule(label) => {
self.schedule_states.remove(&label);
if let Some(index) = self.schedule_order.iter().position(|l| l == &label) {
self.schedule_order.remove(index);
}
reset_cursor = true;
}
Update::ClearSchedule(label) => match self.schedule_states.get_mut(&label) {
Some(state) => state.clear_behaviors(),
None => {
warn!(
"stepping is not enabled for schedule {label:?}; \
use `.add_stepping({label:?})` to enable stepping"
);
}
},
Update::SetBehavior(label, system, behavior) => {
match self.schedule_states.get_mut(&label) {
Some(state) => state.set_behavior(system, behavior),
None => {
warn!(
"stepping is not enabled for schedule {label:?}; \
use `.add_stepping({label:?})` to enable stepping"
);
}
}
}
Update::ClearBehavior(label, system) => {
match self.schedule_states.get_mut(&label) {
Some(state) => state.clear_behavior(system),
None => {
warn!(
"stepping is not enabled for schedule {label:?}; \
use `.add_stepping({label:?})` to enable stepping"
);
}
}
}
}
}
if reset_cursor {
self.reset_cursor();
}
}
/// get the list of systems this schedule should skip for this render
/// frame
pub fn skipped_systems(&mut self, schedule: &Schedule) -> Option<FixedBitSet> {
if self.action == Action::RunAll {
return None;
}
// grab the label and state for this schedule
let label = schedule.label();
let state = self.schedule_states.get_mut(&label)?;
// Stepping is enabled, and this schedule is supposed to be stepped.
//
// We need to maintain a list of schedules in the order that they call
// this function. We'll check the ordered list now to see if this
// schedule is present. If not, we'll add it after the last schedule
// that called this function. Finally we want to save off the index of
// this schedule in the ordered schedule list. This is used to
// determine if this is the schedule the cursor is pointed at.
let index = self.schedule_order.iter().position(|l| *l == label);
let index = match (index, self.previous_schedule) {
(Some(index), _) => index,
(None, None) => {
self.schedule_order.insert(0, label);
0
}
(None, Some(last)) => {
self.schedule_order.insert(last + 1, label);
last + 1
}
};
// Update the index of the previous schedule to be the index of this
// schedule for the next call
self.previous_schedule = Some(index);
#[cfg(test)]
debug!(
"cursor {:?}, index {}, label {:?}",
self.cursor, index, label
);
// if the stepping frame cursor is pointing at this schedule, we'll run
// the schedule with the current stepping action. If this is not the
// cursor schedule, we'll run the schedule with the waiting action.
let cursor = self.cursor;
let (skip_list, next_system) = if index == cursor.schedule {
let (skip_list, next_system) =
state.skipped_systems(schedule, cursor.system, self.action);
// if we just stepped this schedule, then we'll switch the action
// to be waiting
if self.action == Action::Step {
self.action = Action::Waiting;
}
(skip_list, next_system)
} else {
// we're not supposed to run any systems in this schedule, so pull
// the skip list, but ignore any changes it makes to the cursor.
let (skip_list, _) = state.skipped_systems(schedule, 0, Action::Waiting);
(skip_list, Some(cursor.system))
};
// update the stepping frame cursor based on if there are any systems
// remaining to be run in the schedule
// Note: Don't try to detect the end of the render frame here using the
// schedule index. We don't know all schedules have been added to the
// schedule_order, so only next_frame() knows its safe to reset the
// cursor.
match next_system {
Some(i) => self.cursor.system = i,
None => {
let index = cursor.schedule + 1;
self.cursor = Cursor {
schedule: index,
system: self.first_system_index_for_schedule(index),
};
#[cfg(test)]
debug!("advanced schedule index: {} -> {}", cursor.schedule, index);
}
}
Some(skip_list)
}
}
#[derive(Default)]
struct ScheduleState {
/// per-system [`SystemBehavior`]
behaviors: HashMap<NodeId, SystemBehavior>,
/// order of [`NodeId`]s in the schedule
///
/// This is a cached copy of `SystemExecutable::system_ids`. We need it
/// available here to be accessed by [`Stepping::cursor()`] so we can return
/// [`NodeId`]s to the caller.
node_ids: Vec<SystemKey>,
/// changes to system behavior that should be applied the next time
/// [`ScheduleState::skipped_systems()`] is called
behavior_updates: TypeIdMap<Option<SystemBehavior>>,
/// This field contains the first steppable system in the schedule.
first: Option<usize>,
}
impl ScheduleState {
// set the stepping behavior for a system in this schedule
fn set_behavior(&mut self, system: SystemIdentifier, behavior: SystemBehavior) {
self.first = None;
match system {
SystemIdentifier::Node(node_id) => {
self.behaviors.insert(node_id, behavior);
}
// Behaviors are indexed by NodeId, but we cannot map a system
// TypeId to a NodeId without the `Schedule`. So queue this update
// to be processed the next time `skipped_systems()` is called.
SystemIdentifier::Type(type_id) => {
self.behavior_updates.insert(type_id, Some(behavior));
}
}
}
// clear the stepping behavior for a system in this schedule
fn clear_behavior(&mut self, system: SystemIdentifier) {
self.first = None;
match system {
SystemIdentifier::Node(node_id) => {
self.behaviors.remove(&node_id);
}
// queue TypeId updates to be processed later when we have Schedule
SystemIdentifier::Type(type_id) => {
self.behavior_updates.insert(type_id, None);
}
}
}
// clear all system behaviors
fn clear_behaviors(&mut self) {
self.behaviors.clear();
self.behavior_updates.clear();
self.first = None;
}
// apply system behavior updates by looking up the node id of the system in
// the schedule, and updating `systems`
fn apply_behavior_updates(&mut self, schedule: &Schedule) {
// Systems may be present multiple times within a schedule, so we
// iterate through all systems in the schedule, and check our behavior
// updates for the system TypeId.
// PERF: If we add a way to efficiently query schedule systems by their TypeId, we could remove the full
// system scan here
for (key, system) in schedule.systems().unwrap() {
let behavior = self.behavior_updates.get(&system.type_id());
match behavior {
None => continue,
Some(None) => {
self.behaviors.remove(&NodeId::System(key));
}
Some(Some(behavior)) => {
self.behaviors.insert(NodeId::System(key), *behavior);
}
}
}
self.behavior_updates.clear();
#[cfg(test)]
debug!("apply_updates(): {:?}", self.behaviors);
}
fn skipped_systems(
&mut self,
schedule: &Schedule,
start: usize,
mut action: Action,
) -> (FixedBitSet, Option<usize>) {
use core::cmp::Ordering;
// if our NodeId list hasn't been populated, copy it over from the
// schedule
if self.node_ids.len() != schedule.systems_len() {
self.node_ids.clone_from(&schedule.executable().system_ids);
}
// Now that we have the schedule, apply any pending system behavior
// updates. The schedule is required to map from system `TypeId` to
// `NodeId`.
if !self.behavior_updates.is_empty() {
self.apply_behavior_updates(schedule);
}
// if we don't have a first system set, set it now
if self.first.is_none() {
for (i, (key, _)) in schedule.systems().unwrap().enumerate() {
match self.behaviors.get(&NodeId::System(key)) {
Some(SystemBehavior::AlwaysRun | SystemBehavior::NeverRun) => continue,
Some(_) | None => {
self.first = Some(i);
break;
}
}
}
}
let mut skip = FixedBitSet::with_capacity(schedule.systems_len());
let mut pos = start;
for (i, (key, _system)) in schedule.systems().unwrap().enumerate() {
let behavior = self
.behaviors
.get(&NodeId::System(key))
.unwrap_or(&SystemBehavior::Continue);
#[cfg(test)]
debug!(
"skipped_systems(): systems[{}], pos {}, Action::{:?}, Behavior::{:?}, {}",
i,
pos,
action,
behavior,
_system.name()
);
match (action, behavior) {
// regardless of which action we're performing, if the system
// is marked as NeverRun, add it to the skip list.
// Also, advance the cursor past this system if it is our
// current position
(_, SystemBehavior::NeverRun) => {
skip.insert(i);
if i == pos {
pos += 1;
}
}
// similarly, ignore any system marked as AlwaysRun; they should
// never be added to the skip list
// Also, advance the cursor past this system if it is our
// current position
(_, SystemBehavior::AlwaysRun) => {
if i == pos {
pos += 1;
}
}
// if we're waiting, no other systems besides AlwaysRun should
// be run, so add systems to the skip list
(Action::Waiting, _) => skip.insert(i),
// If we're stepping, the remaining behaviors don't matter,
// we're only going to run the system at our cursor. Any system
// prior to the cursor is skipped. Once we encounter the system
// at the cursor, we'll advance the cursor, and set behavior to
// Waiting to skip remaining systems.
(Action::Step, _) => match i.cmp(&pos) {
Ordering::Less => skip.insert(i),
Ordering::Equal => {
pos += 1;
action = Action::Waiting;
}
Ordering::Greater => unreachable!(),
},
// If we're continuing, and the step behavior is continue, we
// want to skip any systems prior to our start position. That's
// where the stepping frame left off last time we ran anything.
(Action::Continue, SystemBehavior::Continue) => {
if i < start {
skip.insert(i);
}
}
// If we're continuing, and we encounter a breakpoint we may
// want to stop before executing the system. To do this we
// skip this system and set the action to Waiting.
//
// Note: if the cursor is pointing at this system, we will run
// it anyway. This allows the user to continue, hit a
// breakpoint, then continue again to run the breakpoint system
// and any following systems.
(Action::Continue, SystemBehavior::Break) => {
if i != start {
skip.insert(i);
// stop running systems if the breakpoint isn't the
// system under the cursor.
if i > start {
action = Action::Waiting;
}
}
}
// should have never gotten into this method if stepping is
// disabled
(Action::RunAll, _) => unreachable!(),
}
// If we're at the cursor position, and not waiting, advance the
// cursor.
if i == pos && action != Action::Waiting {
pos += 1;
}
}
// output is the skip list, and the index of the next system to run in
// this schedule.
if pos >= schedule.systems_len() {
(skip, None)
} else {
(skip, Some(pos))
}
}
}
#[cfg(all(test, feature = "bevy_debug_stepping"))]
#[expect(clippy::print_stdout, reason = "Allowed in tests.")]
mod tests {
use super::*;
use crate::{prelude::*, schedule::ScheduleLabel};
use alloc::{format, vec};
use slotmap::SlotMap;
use std::println;
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash)]
struct TestSchedule;
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash)]
struct TestScheduleA;
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash)]
struct TestScheduleB;
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash)]
struct TestScheduleC;
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash)]
struct TestScheduleD;
fn first_system() {}
fn second_system() {}
fn third_system() {}
fn setup() -> (Schedule, World) {
let mut world = World::new();
let mut schedule = Schedule::new(TestSchedule);
schedule.add_systems((first_system, second_system).chain());
schedule.initialize(&mut world).unwrap();
(schedule, world)
}
// Helper for verifying skip_lists are equal, and if not, printing a human
// readable message.
macro_rules! assert_skip_list_eq {
($actual:expr, $expected:expr, $system_names:expr) => {
let actual = $actual;
let expected = $expected;
let systems: &Vec<&str> = $system_names;
if (actual != expected) {
use core::fmt::Write as _;
// mismatch, let's construct a human-readable message of what
// was returned
let mut msg = format!(
"Schedule:\n {:9} {:16}{:6} {:6} {:6}\n",
"index", "name", "expect", "actual", "result"
);
for (i, name) in systems.iter().enumerate() {
let _ = write!(msg, " system[{:1}] {:16}", i, name);
match (expected.contains(i), actual.contains(i)) {
(true, true) => msg.push_str("skip skip pass\n"),
(true, false) => {
msg.push_str("skip run FAILED; system should not have run\n")
}
(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/schedule/condition.rs | crates/bevy_ecs/src/schedule/condition.rs | use alloc::{boxed::Box, format};
use bevy_utils::prelude::DebugName;
use core::ops::Not;
use crate::system::{
Adapt, AdapterSystem, CombinatorSystem, Combine, IntoSystem, ReadOnlySystem, RunSystemError,
System, SystemIn, SystemInput,
};
/// A type-erased run condition stored in a [`Box`].
pub type BoxedCondition<In = ()> = Box<dyn ReadOnlySystem<In = In, Out = bool>>;
/// A system that determines if one or more scheduled systems should run.
///
/// Implemented for functions and closures that convert into [`System<Out=bool>`](System)
/// with [read-only](crate::system::ReadOnlySystemParam) parameters.
///
/// # Marker type parameter
///
/// `SystemCondition` trait has `Marker` type parameter, which has no special meaning,
/// but exists to work around the limitation of Rust's trait system.
///
/// Type parameter in return type can be set to `<()>` by calling [`IntoSystem::into_system`],
/// but usually have to be specified when passing a condition to a function.
///
/// ```
/// # use bevy_ecs::schedule::SystemCondition;
/// # use bevy_ecs::system::IntoSystem;
/// fn not_condition<Marker>(a: impl SystemCondition<Marker>) -> impl SystemCondition<()> {
/// IntoSystem::into_system(a.map(|x| !x))
/// }
/// ```
///
/// # Examples
/// A condition that returns true every other time it's called.
/// ```
/// # use bevy_ecs::prelude::*;
/// fn every_other_time() -> impl SystemCondition<()> {
/// IntoSystem::into_system(|mut flag: Local<bool>| {
/// *flag = !*flag;
/// *flag
/// })
/// }
///
/// # #[derive(Resource)] struct DidRun(bool);
/// # fn my_system(mut did_run: ResMut<DidRun>) { did_run.0 = true; }
/// # let mut schedule = Schedule::default();
/// schedule.add_systems(my_system.run_if(every_other_time()));
/// # let mut world = World::new();
/// # world.insert_resource(DidRun(false));
/// # schedule.run(&mut world);
/// # assert!(world.resource::<DidRun>().0);
/// # world.insert_resource(DidRun(false));
/// # schedule.run(&mut world);
/// # assert!(!world.resource::<DidRun>().0);
/// ```
///
/// A condition that takes a bool as an input and returns it unchanged.
///
/// ```
/// # use bevy_ecs::prelude::*;
/// fn identity() -> impl SystemCondition<(), In<bool>> {
/// IntoSystem::into_system(|In(x): In<bool>| x)
/// }
///
/// # fn always_true() -> bool { true }
/// # let mut app = Schedule::default();
/// # #[derive(Resource)] struct DidRun(bool);
/// # fn my_system(mut did_run: ResMut<DidRun>) { did_run.0 = true; }
/// app.add_systems(my_system.run_if(always_true.pipe(identity())));
/// # let mut world = World::new();
/// # world.insert_resource(DidRun(false));
/// # app.run(&mut world);
/// # assert!(world.resource::<DidRun>().0);
pub trait SystemCondition<Marker, In: SystemInput = ()>:
IntoSystem<In, bool, Marker, System: ReadOnlySystem>
{
/// Returns a new run condition that only returns `true`
/// if both this one and the passed `and` return `true`.
///
/// The returned run condition is short-circuiting, meaning
/// `and` will only be invoked if `self` returns `true`.
///
/// # Examples
///
/// ```should_panic
/// use bevy_ecs::prelude::*;
///
/// #[derive(Resource, PartialEq)]
/// struct R(u32);
///
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// # fn my_system() {}
/// app.add_systems(
/// // The `resource_equals` run condition will panic since we don't initialize `R`,
/// // just like if we used `Res<R>` in a system.
/// my_system.run_if(resource_equals(R(0))),
/// );
/// # app.run(&mut world);
/// ```
///
/// Use `.and()` to avoid checking the condition.
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Resource, PartialEq)]
/// # struct R(u32);
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// # fn my_system() {}
/// app.add_systems(
/// // `resource_equals` will only get run if the resource `R` exists.
/// my_system.run_if(resource_exists::<R>.and(resource_equals(R(0)))),
/// );
/// # app.run(&mut world);
/// ```
///
/// Note that in this case, it's better to just use the run condition [`resource_exists_and_equals`].
///
/// [`resource_exists_and_equals`]: common_conditions::resource_exists_and_equals
fn and<M, C: SystemCondition<M, In>>(self, and: C) -> And<Self::System, C::System> {
let a = IntoSystem::into_system(self);
let b = IntoSystem::into_system(and);
let name = format!("{} && {}", a.name(), b.name());
CombinatorSystem::new(a, b, DebugName::owned(name))
}
/// Returns a new run condition that only returns `false`
/// if both this one and the passed `nand` return `true`.
///
/// The returned run condition is short-circuiting, meaning
/// `nand` will only be invoked if `self` returns `true`.
///
/// # Examples
///
/// ```compile_fail
/// use bevy::prelude::*;
///
/// #[derive(States, Debug, Clone, PartialEq, Eq, Hash)]
/// pub enum PlayerState {
/// Alive,
/// Dead,
/// }
///
/// #[derive(States, Debug, Clone, PartialEq, Eq, Hash)]
/// pub enum EnemyState {
/// Alive,
/// Dead,
/// }
///
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// # fn game_over_credits() {}
/// app.add_systems(
/// // The game_over_credits system will only execute if either the `in_state(PlayerState::Alive)`
/// // run condition or `in_state(EnemyState::Alive)` run condition evaluates to `false`.
/// game_over_credits.run_if(
/// in_state(PlayerState::Alive).nand(in_state(EnemyState::Alive))
/// ),
/// );
/// # app.run(&mut world);
/// ```
///
/// Equivalent logic can be achieved by using `not` in concert with `and`:
///
/// ```compile_fail
/// app.add_systems(
/// game_over_credits.run_if(
/// not(in_state(PlayerState::Alive).and(in_state(EnemyState::Alive)))
/// ),
/// );
/// ```
fn nand<M, C: SystemCondition<M, In>>(self, nand: C) -> Nand<Self::System, C::System> {
let a = IntoSystem::into_system(self);
let b = IntoSystem::into_system(nand);
let name = format!("!({} && {})", a.name(), b.name());
CombinatorSystem::new(a, b, DebugName::owned(name))
}
/// Returns a new run condition that only returns `true`
/// if both this one and the passed `nor` return `false`.
///
/// The returned run condition is short-circuiting, meaning
/// `nor` will only be invoked if `self` returns `false`.
///
/// # Examples
///
/// ```compile_fail
/// use bevy::prelude::*;
///
/// #[derive(States, Debug, Clone, PartialEq, Eq, Hash)]
/// pub enum WeatherState {
/// Sunny,
/// Cloudy,
/// }
///
/// #[derive(States, Debug, Clone, PartialEq, Eq, Hash)]
/// pub enum SoilState {
/// Fertilized,
/// NotFertilized,
/// }
///
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// # fn slow_plant_growth() {}
/// app.add_systems(
/// // The slow_plant_growth system will only execute if both the `in_state(WeatherState::Sunny)`
/// // run condition and `in_state(SoilState::Fertilized)` run condition evaluate to `false`.
/// slow_plant_growth.run_if(
/// in_state(WeatherState::Sunny).nor(in_state(SoilState::Fertilized))
/// ),
/// );
/// # app.run(&mut world);
/// ```
///
/// Equivalent logic can be achieved by using `not` in concert with `or`:
///
/// ```compile_fail
/// app.add_systems(
/// slow_plant_growth.run_if(
/// not(in_state(WeatherState::Sunny).or(in_state(SoilState::Fertilized)))
/// ),
/// );
/// ```
fn nor<M, C: SystemCondition<M, In>>(self, nor: C) -> Nor<Self::System, C::System> {
let a = IntoSystem::into_system(self);
let b = IntoSystem::into_system(nor);
let name = format!("!({} || {})", a.name(), b.name());
CombinatorSystem::new(a, b, DebugName::owned(name))
}
/// Returns a new run condition that returns `true`
/// if either this one or the passed `or` return `true`.
///
/// The returned run condition is short-circuiting, meaning
/// `or` will only be invoked if `self` returns `false`.
///
/// # Examples
///
/// ```
/// use bevy_ecs::prelude::*;
///
/// #[derive(Resource, PartialEq)]
/// struct A(u32);
///
/// #[derive(Resource, PartialEq)]
/// struct B(u32);
///
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// # #[derive(Resource)] struct C(bool);
/// # fn my_system(mut c: ResMut<C>) { c.0 = true; }
/// app.add_systems(
/// // Only run the system if either `A` or `B` exist.
/// my_system.run_if(resource_exists::<A>.or(resource_exists::<B>)),
/// );
/// #
/// # world.insert_resource(C(false));
/// # app.run(&mut world);
/// # assert!(!world.resource::<C>().0);
/// #
/// # world.insert_resource(A(0));
/// # app.run(&mut world);
/// # assert!(world.resource::<C>().0);
/// #
/// # world.remove_resource::<A>();
/// # world.insert_resource(B(0));
/// # world.insert_resource(C(false));
/// # app.run(&mut world);
/// # assert!(world.resource::<C>().0);
/// ```
fn or<M, C: SystemCondition<M, In>>(self, or: C) -> Or<Self::System, C::System> {
let a = IntoSystem::into_system(self);
let b = IntoSystem::into_system(or);
let name = format!("{} || {}", a.name(), b.name());
CombinatorSystem::new(a, b, DebugName::owned(name))
}
/// Returns a new run condition that only returns `true`
/// if `self` and `xnor` **both** return `false` or **both** return `true`.
///
/// # Examples
///
/// ```compile_fail
/// use bevy::prelude::*;
///
/// #[derive(States, Debug, Clone, PartialEq, Eq, Hash)]
/// pub enum CoffeeMachineState {
/// Heating,
/// Brewing,
/// Inactive,
/// }
///
/// #[derive(States, Debug, Clone, PartialEq, Eq, Hash)]
/// pub enum TeaKettleState {
/// Heating,
/// Steeping,
/// Inactive,
/// }
///
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// # fn take_drink_orders() {}
/// app.add_systems(
/// // The take_drink_orders system will only execute if the `in_state(CoffeeMachineState::Inactive)`
/// // run condition and `in_state(TeaKettleState::Inactive)` run conditions both evaluate to `false`,
/// // or both evaluate to `true`.
/// take_drink_orders.run_if(
/// in_state(CoffeeMachineState::Inactive).xnor(in_state(TeaKettleState::Inactive))
/// ),
/// );
/// # app.run(&mut world);
/// ```
///
/// Equivalent logic can be achieved by using `not` in concert with `xor`:
///
/// ```compile_fail
/// app.add_systems(
/// take_drink_orders.run_if(
/// not(in_state(CoffeeMachineState::Inactive).xor(in_state(TeaKettleState::Inactive)))
/// ),
/// );
/// ```
fn xnor<M, C: SystemCondition<M, In>>(self, xnor: C) -> Xnor<Self::System, C::System> {
let a = IntoSystem::into_system(self);
let b = IntoSystem::into_system(xnor);
let name = format!("!({} ^ {})", a.name(), b.name());
CombinatorSystem::new(a, b, DebugName::owned(name))
}
/// Returns a new run condition that only returns `true`
/// if either `self` or `xor` return `true`, but not both.
///
/// # Examples
///
/// ```compile_fail
/// use bevy::prelude::*;
///
/// #[derive(States, Debug, Clone, PartialEq, Eq, Hash)]
/// pub enum CoffeeMachineState {
/// Heating,
/// Brewing,
/// Inactive,
/// }
///
/// #[derive(States, Debug, Clone, PartialEq, Eq, Hash)]
/// pub enum TeaKettleState {
/// Heating,
/// Steeping,
/// Inactive,
/// }
///
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// # fn prepare_beverage() {}
/// app.add_systems(
/// // The prepare_beverage system will only execute if either the `in_state(CoffeeMachineState::Inactive)`
/// // run condition or `in_state(TeaKettleState::Inactive)` run condition evaluates to `true`,
/// // but not both.
/// prepare_beverage.run_if(
/// in_state(CoffeeMachineState::Inactive).xor(in_state(TeaKettleState::Inactive))
/// ),
/// );
/// # app.run(&mut world);
/// ```
fn xor<M, C: SystemCondition<M, In>>(self, xor: C) -> Xor<Self::System, C::System> {
let a = IntoSystem::into_system(self);
let b = IntoSystem::into_system(xor);
let name = format!("({} ^ {})", a.name(), b.name());
CombinatorSystem::new(a, b, DebugName::owned(name))
}
}
impl<Marker, In: SystemInput, F> SystemCondition<Marker, In> for F where
F: IntoSystem<In, bool, Marker, System: ReadOnlySystem>
{
}
/// A collection of [run conditions](SystemCondition) that may be useful in any bevy app.
pub mod common_conditions {
use super::{NotSystem, SystemCondition};
use crate::{
change_detection::DetectChanges,
lifecycle::RemovedComponents,
message::{Message, MessageReader},
prelude::{Component, Query, With},
query::QueryFilter,
resource::Resource,
system::{In, IntoSystem, Local, Res, System, SystemInput},
};
use alloc::format;
/// A [`SystemCondition`]-satisfying system that returns `true`
/// on the first time the condition is run and false every time after.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Resource, Default)]
/// # struct Counter(u8);
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// # world.init_resource::<Counter>();
/// app.add_systems(
/// // `run_once` will only return true the first time it's evaluated
/// my_system.run_if(run_once),
/// );
///
/// fn my_system(mut counter: ResMut<Counter>) {
/// counter.0 += 1;
/// }
///
/// // This is the first time the condition will be evaluated so `my_system` will run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 1);
///
/// // This is the seconds time the condition will be evaluated so `my_system` won't run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 1);
/// ```
pub fn run_once(mut has_run: Local<bool>) -> bool {
if !*has_run {
*has_run = true;
true
} else {
false
}
}
/// A [`SystemCondition`]-satisfying system that returns `true`
/// if the resource exists.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Resource, Default)]
/// # struct Counter(u8);
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// app.add_systems(
/// // `resource_exists` will only return true if the given resource exists in the world
/// my_system.run_if(resource_exists::<Counter>),
/// );
///
/// fn my_system(mut counter: ResMut<Counter>) {
/// counter.0 += 1;
/// }
///
/// // `Counter` hasn't been added so `my_system` won't run
/// app.run(&mut world);
/// world.init_resource::<Counter>();
///
/// // `Counter` has now been added so `my_system` can run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 1);
/// ```
pub fn resource_exists<T>(res: Option<Res<T>>) -> bool
where
T: Resource,
{
res.is_some()
}
/// Generates a [`SystemCondition`]-satisfying closure that returns `true`
/// if the resource is equal to `value`.
///
/// # Panics
///
/// The condition will panic if the resource does not exist.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Resource, Default, PartialEq)]
/// # struct Counter(u8);
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// # world.init_resource::<Counter>();
/// app.add_systems(
/// // `resource_equals` will only return true if the given resource equals the given value
/// my_system.run_if(resource_equals(Counter(0))),
/// );
///
/// fn my_system(mut counter: ResMut<Counter>) {
/// counter.0 += 1;
/// }
///
/// // `Counter` is `0` so `my_system` can run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 1);
///
/// // `Counter` is no longer `0` so `my_system` won't run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 1);
/// ```
pub fn resource_equals<T>(value: T) -> impl FnMut(Res<T>) -> bool
where
T: Resource + PartialEq,
{
move |res: Res<T>| *res == value
}
/// Generates a [`SystemCondition`]-satisfying closure that returns `true`
/// if the resource exists and is equal to `value`.
///
/// The condition will return `false` if the resource does not exist.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Resource, Default, PartialEq)]
/// # struct Counter(u8);
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// app.add_systems(
/// // `resource_exists_and_equals` will only return true
/// // if the given resource exists and equals the given value
/// my_system.run_if(resource_exists_and_equals(Counter(0))),
/// );
///
/// fn my_system(mut counter: ResMut<Counter>) {
/// counter.0 += 1;
/// }
///
/// // `Counter` hasn't been added so `my_system` can't run
/// app.run(&mut world);
/// world.init_resource::<Counter>();
///
/// // `Counter` is `0` so `my_system` can run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 1);
///
/// // `Counter` is no longer `0` so `my_system` won't run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 1);
/// ```
pub fn resource_exists_and_equals<T>(value: T) -> impl FnMut(Option<Res<T>>) -> bool
where
T: Resource + PartialEq,
{
move |res: Option<Res<T>>| match res {
Some(res) => *res == value,
None => false,
}
}
/// A [`SystemCondition`]-satisfying system that returns `true`
/// if the resource of the given type has been added since the condition was last checked.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Resource, Default)]
/// # struct Counter(u8);
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// app.add_systems(
/// // `resource_added` will only return true if the
/// // given resource was just added
/// my_system.run_if(resource_added::<Counter>),
/// );
///
/// fn my_system(mut counter: ResMut<Counter>) {
/// counter.0 += 1;
/// }
///
/// world.init_resource::<Counter>();
///
/// // `Counter` was just added so `my_system` will run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 1);
///
/// // `Counter` was not just added so `my_system` will not run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 1);
/// ```
pub fn resource_added<T>(res: Option<Res<T>>) -> bool
where
T: Resource,
{
match res {
Some(res) => res.is_added(),
None => false,
}
}
/// A [`SystemCondition`]-satisfying system that returns `true`
/// if the resource of the given type has been added or mutably dereferenced
/// since the condition was last checked.
///
/// **Note** that simply *mutably dereferencing* a resource is considered a change ([`DerefMut`](std::ops::DerefMut)).
/// Bevy does not compare resources to their previous values.
///
/// # Panics
///
/// The condition will panic if the resource does not exist.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Resource, Default)]
/// # struct Counter(u8);
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// # world.init_resource::<Counter>();
/// app.add_systems(
/// // `resource_changed` will only return true if the
/// // given resource was just changed (or added)
/// my_system.run_if(
/// resource_changed::<Counter>
/// // By default detecting changes will also trigger if the resource was
/// // just added, this won't work with my example so I will add a second
/// // condition to make sure the resource wasn't just added
/// .and(not(resource_added::<Counter>))
/// ),
/// );
///
/// fn my_system(mut counter: ResMut<Counter>) {
/// counter.0 += 1;
/// }
///
/// // `Counter` hasn't been changed so `my_system` won't run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 0);
///
/// world.resource_mut::<Counter>().0 = 50;
///
/// // `Counter` was just changed so `my_system` will run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 51);
/// ```
pub fn resource_changed<T>(res: Res<T>) -> bool
where
T: Resource,
{
res.is_changed()
}
/// A [`SystemCondition`]-satisfying system that returns `true`
/// if the resource of the given type has been added or mutably dereferenced since the condition
/// was last checked.
///
/// **Note** that simply *mutably dereferencing* a resource is considered a change ([`DerefMut`](std::ops::DerefMut)).
/// Bevy does not compare resources to their previous values.
///
/// The condition will return `false` if the resource does not exist.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Resource, Default)]
/// # struct Counter(u8);
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// app.add_systems(
/// // `resource_exists_and_changed` will only return true if the
/// // given resource exists and was just changed (or added)
/// my_system.run_if(
/// resource_exists_and_changed::<Counter>
/// // By default detecting changes will also trigger if the resource was
/// // just added, this won't work with my example so I will add a second
/// // condition to make sure the resource wasn't just added
/// .and(not(resource_added::<Counter>))
/// ),
/// );
///
/// fn my_system(mut counter: ResMut<Counter>) {
/// counter.0 += 1;
/// }
///
/// // `Counter` doesn't exist so `my_system` won't run
/// app.run(&mut world);
/// world.init_resource::<Counter>();
///
/// // `Counter` hasn't been changed so `my_system` won't run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 0);
///
/// world.resource_mut::<Counter>().0 = 50;
///
/// // `Counter` was just changed so `my_system` will run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 51);
/// ```
pub fn resource_exists_and_changed<T>(res: Option<Res<T>>) -> bool
where
T: Resource,
{
match res {
Some(res) => res.is_changed(),
None => false,
}
}
/// A [`SystemCondition`]-satisfying system that returns `true`
/// if the resource of the given type has been added, removed or mutably dereferenced since the condition
/// was last checked.
///
/// **Note** that simply *mutably dereferencing* a resource is considered a change ([`DerefMut`](std::ops::DerefMut)).
/// Bevy does not compare resources to their previous values.
///
/// The condition will return `false` if the resource does not exist.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Resource, Default)]
/// # struct Counter(u8);
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// # world.init_resource::<Counter>();
/// app.add_systems(
/// // `resource_changed_or_removed` will only return true if the
/// // given resource was just changed or removed (or added)
/// my_system.run_if(
/// resource_changed_or_removed::<Counter>
/// // By default detecting changes will also trigger if the resource was
/// // just added, this won't work with my example so I will add a second
/// // condition to make sure the resource wasn't just added
/// .and(not(resource_added::<Counter>))
/// ),
/// );
///
/// #[derive(Resource, Default)]
/// struct MyResource;
///
/// // If `Counter` exists, increment it, otherwise insert `MyResource`
/// fn my_system(mut commands: Commands, mut counter: Option<ResMut<Counter>>) {
/// if let Some(mut counter) = counter {
/// counter.0 += 1;
/// } else {
/// commands.init_resource::<MyResource>();
/// }
/// }
///
/// // `Counter` hasn't been changed so `my_system` won't run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 0);
///
/// world.resource_mut::<Counter>().0 = 50;
///
/// // `Counter` was just changed so `my_system` will run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 51);
///
/// world.remove_resource::<Counter>();
///
/// // `Counter` was just removed so `my_system` will run
/// app.run(&mut world);
/// assert_eq!(world.contains_resource::<MyResource>(), true);
/// ```
pub fn resource_changed_or_removed<T>(res: Option<Res<T>>, mut existed: Local<bool>) -> bool
where
T: Resource,
{
if let Some(value) = res {
*existed = true;
value.is_changed()
} else if *existed {
*existed = false;
true
} else {
false
}
}
/// A [`SystemCondition`]-satisfying system that returns `true`
/// if the resource of the given type has been removed since the condition was last checked.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Resource, Default)]
/// # struct Counter(u8);
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// # world.init_resource::<Counter>();
/// app.add_systems(
/// // `resource_removed` will only return true if the
/// // given resource was just removed
/// my_system.run_if(resource_removed::<MyResource>),
/// );
///
/// #[derive(Resource, Default)]
/// struct MyResource;
///
/// fn my_system(mut counter: ResMut<Counter>) {
/// counter.0 += 1;
/// }
///
/// world.init_resource::<MyResource>();
///
/// // `MyResource` hasn't just been removed so `my_system` won't run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 0);
///
/// world.remove_resource::<MyResource>();
///
/// // `MyResource` was just removed so `my_system` will run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 1);
/// ```
pub fn resource_removed<T>(res: Option<Res<T>>, mut existed: Local<bool>) -> bool
where
T: Resource,
{
if res.is_some() {
*existed = true;
false
} else if *existed {
*existed = false;
true
} else {
false
}
}
/// A [`SystemCondition`]-satisfying system that returns `true`
/// if there are any new events of the given type since it was last called.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Resource, Default)]
/// # struct Counter(u8);
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// # world.init_resource::<Counter>();
/// # world.init_resource::<Messages<MyMessage>>();
/// # app.add_systems(bevy_ecs::message::message_update_system.before(my_system));
///
/// app.add_systems(
/// my_system.run_if(on_message::<MyMessage>),
/// );
///
/// #[derive(Message)]
/// struct MyMessage;
///
/// fn my_system(mut counter: ResMut<Counter>) {
/// counter.0 += 1;
/// }
///
/// // No new `MyMessage` events have been push so `my_system` won't run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 0);
///
/// world.resource_mut::<Messages<MyMessage>>().write(MyMessage);
///
/// // A `MyMessage` event has been pushed so `my_system` will run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 1);
/// ```
pub fn on_message<M: Message>(mut reader: MessageReader<M>) -> bool {
// The messages need to be consumed, so that there are no false positives on subsequent
// calls of the run condition. Simply checking `is_empty` would not be enough.
// PERF: note that `count` is efficient (not actually looping/iterating),
// due to Bevy having a specialized implementation for messages.
reader.read().count() > 0
}
/// A [`SystemCondition`]-satisfying system that returns `true`
/// if there are any entities with the given component type.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Resource, Default)]
/// # struct Counter(u8);
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
/// # world.init_resource::<Counter>();
/// app.add_systems(
/// my_system.run_if(any_with_component::<MyComponent>),
/// );
///
/// #[derive(Component)]
/// struct MyComponent;
///
/// fn my_system(mut counter: ResMut<Counter>) {
/// counter.0 += 1;
/// }
///
/// // No entities exist yet with a `MyComponent` component so `my_system` won't run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 0);
///
/// world.spawn(MyComponent);
///
/// // An entities with `MyComponent` now exists so `my_system` will run
/// app.run(&mut world);
/// assert_eq!(world.resource::<Counter>().0, 1);
/// ```
pub fn any_with_component<T: Component>(query: Query<(), With<T>>) -> bool {
!query.is_empty()
}
/// A [`SystemCondition`]-satisfying system that returns `true`
/// if there are any entity with a component of the given type removed.
pub fn any_component_removed<T: Component>(mut removals: RemovedComponents<T>) -> bool {
// `RemovedComponents` based on events and therefore events need to be consumed,
// so that there are no false positives on subsequent calls of the run condition.
// Simply checking `is_empty` would not be enough.
// PERF: note that `count` is efficient (not actually looping/iterating),
// due to Bevy having a specialized implementation for events.
removals.read().count() > 0
}
/// A [`SystemCondition`]-satisfying system that returns `true`
/// if there are any entities that match the given [`QueryFilter`].
pub fn any_match_filter<F: QueryFilter>(query: Query<(), F>) -> bool {
!query.is_empty()
}
/// Generates a [`SystemCondition`] that inverses the result of passed one.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Resource, Default)]
/// # struct Counter(u8);
/// # let mut app = Schedule::default();
/// # let mut world = World::new();
| 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/schedule/auto_insert_apply_deferred.rs | crates/bevy_ecs/src/schedule/auto_insert_apply_deferred.rs | use alloc::{boxed::Box, collections::BTreeSet, vec::Vec};
use bevy_platform::{collections::HashMap, hash::FixedHasher};
use indexmap::IndexSet;
use crate::{
schedule::{graph::Dag, SystemKey, SystemSetKey},
system::{IntoSystem, System},
world::World,
};
use super::{
is_apply_deferred, ApplyDeferred, DiGraph, Direction, NodeId, ScheduleBuildError,
ScheduleBuildPass, ScheduleGraph,
};
/// A [`ScheduleBuildPass`] that inserts [`ApplyDeferred`] systems into the schedule graph
/// when there are [`Deferred`](crate::prelude::Deferred)
/// in one system and there are ordering dependencies on that system. [`Commands`](crate::system::Commands) is one
/// such deferred buffer.
///
/// This pass is typically automatically added to the schedule. You can disable this by setting
/// [`ScheduleBuildSettings::auto_insert_apply_deferred`](crate::schedule::ScheduleBuildSettings::auto_insert_apply_deferred)
/// to `false`. You may want to disable this if you only want to sync deferred params at the end of the schedule,
/// or want to manually insert all your sync points.
#[derive(Debug, Default)]
pub struct AutoInsertApplyDeferredPass {
/// Dependency edges that will **not** automatically insert an instance of `ApplyDeferred` on the edge.
no_sync_edges: BTreeSet<(NodeId, NodeId)>,
auto_sync_node_ids: HashMap<u32, SystemKey>,
}
/// If added to a dependency edge, the edge will not be considered for auto sync point insertions.
pub struct IgnoreDeferred;
impl AutoInsertApplyDeferredPass {
/// Returns the `NodeId` of the cached auto sync point. Will create
/// a new one if needed.
fn get_sync_point(&mut self, graph: &mut ScheduleGraph, distance: u32) -> SystemKey {
self.auto_sync_node_ids
.get(&distance)
.copied()
.unwrap_or_else(|| {
let key = self.add_auto_sync(graph);
self.auto_sync_node_ids.insert(distance, key);
key
})
}
/// add an [`ApplyDeferred`] system with no config
fn add_auto_sync(&mut self, graph: &mut ScheduleGraph) -> SystemKey {
let key = graph
.systems
.insert(Box::new(IntoSystem::into_system(ApplyDeferred)), Vec::new());
// ignore ambiguities with auto sync points
// They aren't under user control, so no one should know or care.
graph.ambiguous_with_all.insert(NodeId::System(key));
key
}
}
impl ScheduleBuildPass for AutoInsertApplyDeferredPass {
type EdgeOptions = IgnoreDeferred;
fn add_dependency(&mut self, from: NodeId, to: NodeId, options: Option<&Self::EdgeOptions>) {
if options.is_some() {
self.no_sync_edges.insert((from, to));
}
}
fn build(
&mut self,
_world: &mut World,
graph: &mut ScheduleGraph,
dependency_flattened: &mut Dag<SystemKey>,
) -> Result<(), ScheduleBuildError> {
let mut sync_point_graph = dependency_flattened.graph().clone();
let (topo, flat_dependency) = dependency_flattened
.toposort_and_graph()
.map_err(ScheduleBuildError::FlatDependencySort)?;
fn set_has_conditions(graph: &ScheduleGraph, set: SystemSetKey) -> bool {
graph.system_sets.has_conditions(set)
|| graph
.hierarchy()
.graph()
.edges_directed(NodeId::Set(set), Direction::Incoming)
.any(|(parent, _)| {
parent
.as_set()
.is_some_and(|p| set_has_conditions(graph, p))
})
}
fn system_has_conditions(graph: &ScheduleGraph, key: SystemKey) -> bool {
graph.systems.has_conditions(key)
|| graph
.hierarchy()
.graph()
.edges_directed(NodeId::System(key), Direction::Incoming)
.any(|(parent, _)| {
parent
.as_set()
.is_some_and(|p| set_has_conditions(graph, p))
})
}
let mut system_has_conditions_cache = HashMap::<SystemKey, bool>::default();
let mut is_valid_explicit_sync_point = |key: SystemKey| {
is_apply_deferred(&graph.systems[key])
&& !*system_has_conditions_cache
.entry(key)
.or_insert_with(|| system_has_conditions(graph, key))
};
// Calculate the distance for each node.
// The "distance" is the number of sync points between a node and the beginning of the graph.
// Also store if a preceding edge would have added a sync point but was ignored to add it at
// a later edge that is not ignored.
let mut distances_and_pending_sync: HashMap<SystemKey, (u32, bool)> =
HashMap::with_capacity_and_hasher(topo.len(), Default::default());
// Keep track of any explicit sync nodes for a specific distance.
let mut distance_to_explicit_sync_node: HashMap<u32, SystemKey> = HashMap::default();
// Determine the distance for every node and collect the explicit sync points.
for &key in topo {
let (node_distance, mut node_needs_sync) = distances_and_pending_sync
.get(&key)
.copied()
.unwrap_or_default();
if is_valid_explicit_sync_point(key) {
// The distance of this sync point does not change anymore as the iteration order
// makes sure that this node is no unvisited target of another node.
// Because of this, the sync point can be stored for this distance to be reused as
// automatically added sync points later.
distance_to_explicit_sync_node.insert(node_distance, key);
// This node just did a sync, so the only reason to do another sync is if one was
// explicitly scheduled afterwards.
node_needs_sync = false;
} else if !node_needs_sync {
// No previous node has postponed sync points to add so check if the system itself
// has deferred params that require a sync point to apply them.
node_needs_sync = graph.systems[key].has_deferred();
}
for target in flat_dependency.neighbors_directed(key, Direction::Outgoing) {
let (target_distance, target_pending_sync) =
distances_and_pending_sync.entry(target).or_default();
let mut edge_needs_sync = node_needs_sync;
if node_needs_sync
&& !graph.systems[target].is_exclusive()
&& self
.no_sync_edges
.contains(&(NodeId::System(key), NodeId::System(target)))
{
// The node has deferred params to apply, but this edge is ignoring sync points.
// Mark the target as 'delaying' those commands to a future edge and the current
// edge as not needing a sync point.
*target_pending_sync = true;
edge_needs_sync = false;
}
let mut weight = 0;
if edge_needs_sync || is_valid_explicit_sync_point(target) {
// The target distance grows if a sync point is added between it and the node.
// Also raise the distance if the target is a sync point itself so it then again
// raises the distance of following nodes as that is what the distance is about.
weight = 1;
}
// The target cannot have fewer sync points in front of it than the preceding node.
*target_distance = (node_distance + weight).max(*target_distance);
}
}
// Find any edges which have a different number of sync points between them and make sure
// there is a sync point between them.
for &key in topo {
let (node_distance, _) = distances_and_pending_sync
.get(&key)
.copied()
.unwrap_or_default();
for target in flat_dependency.neighbors_directed(key, Direction::Outgoing) {
let (target_distance, _) = distances_and_pending_sync
.get(&target)
.copied()
.unwrap_or_default();
if node_distance == target_distance {
// These nodes are the same distance, so they don't need an edge between them.
continue;
}
if is_apply_deferred(&graph.systems[target]) {
// We don't need to insert a sync point since ApplyDeferred is a sync point
// already!
continue;
}
let sync_point = distance_to_explicit_sync_node
.get(&target_distance)
.copied()
.unwrap_or_else(|| self.get_sync_point(graph, target_distance));
sync_point_graph.add_edge(key, sync_point);
sync_point_graph.add_edge(sync_point, target);
// The edge without the sync point is now redundant.
sync_point_graph.remove_edge(key, target);
}
}
**dependency_flattened = sync_point_graph;
Ok(())
}
fn collapse_set(
&mut self,
set: SystemSetKey,
systems: &IndexSet<SystemKey, FixedHasher>,
dependency_flattening: &DiGraph<NodeId>,
) -> impl Iterator<Item = (NodeId, NodeId)> {
if systems.is_empty() {
// collapse dependencies for empty sets
for a in dependency_flattening.neighbors_directed(NodeId::Set(set), Direction::Incoming)
{
for b in
dependency_flattening.neighbors_directed(NodeId::Set(set), Direction::Outgoing)
{
if self.no_sync_edges.contains(&(a, NodeId::Set(set)))
&& self.no_sync_edges.contains(&(NodeId::Set(set), b))
{
self.no_sync_edges.insert((a, b));
}
}
}
} else {
for a in dependency_flattening.neighbors_directed(NodeId::Set(set), Direction::Incoming)
{
for &sys in systems {
if self.no_sync_edges.contains(&(a, NodeId::Set(set))) {
self.no_sync_edges.insert((a, NodeId::System(sys)));
}
}
}
for b in dependency_flattening.neighbors_directed(NodeId::Set(set), Direction::Outgoing)
{
for &sys in systems {
if self.no_sync_edges.contains(&(NodeId::Set(set), b)) {
self.no_sync_edges.insert((NodeId::System(sys), b));
}
}
}
}
core::iter::empty()
}
}
| 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/schedule/pass.rs | crates/bevy_ecs/src/schedule/pass.rs | use alloc::{boxed::Box, vec::Vec};
use core::{
any::{Any, TypeId},
fmt::Debug,
};
use bevy_platform::hash::FixedHasher;
use bevy_utils::TypeIdMap;
use indexmap::IndexSet;
use super::{DiGraph, NodeId, ScheduleBuildError, ScheduleGraph};
use crate::{
schedule::{graph::Dag, SystemKey, SystemSetKey},
world::World,
};
/// A pass for modular modification of the dependency graph.
pub trait ScheduleBuildPass: Send + Sync + Debug + 'static {
/// Custom options for dependencies between sets or systems.
type EdgeOptions: 'static;
/// Called when a dependency between sets or systems was explicitly added to the graph.
fn add_dependency(&mut self, from: NodeId, to: NodeId, options: Option<&Self::EdgeOptions>);
/// Called while flattening the dependency graph. For each `set`, this method is called
/// with the `systems` associated with the set as well as an immutable reference to the current graph.
/// Instead of modifying the graph directly, this method should return an iterator of edges to add to the graph.
fn collapse_set(
&mut self,
set: SystemSetKey,
systems: &IndexSet<SystemKey, FixedHasher>,
dependency_flattening: &DiGraph<NodeId>,
) -> impl Iterator<Item = (NodeId, NodeId)>;
/// The implementation will be able to modify the `ScheduleGraph` here.
fn build(
&mut self,
world: &mut World,
graph: &mut ScheduleGraph,
dependency_flattened: &mut Dag<SystemKey>,
) -> Result<(), ScheduleBuildError>;
}
/// Object safe version of [`ScheduleBuildPass`].
pub(super) trait ScheduleBuildPassObj: Send + Sync + Debug {
fn build(
&mut self,
world: &mut World,
graph: &mut ScheduleGraph,
dependency_flattened: &mut Dag<SystemKey>,
) -> Result<(), ScheduleBuildError>;
fn collapse_set(
&mut self,
set: SystemSetKey,
systems: &IndexSet<SystemKey, FixedHasher>,
dependency_flattening: &DiGraph<NodeId>,
dependencies_to_add: &mut Vec<(NodeId, NodeId)>,
);
fn add_dependency(&mut self, from: NodeId, to: NodeId, all_options: &TypeIdMap<Box<dyn Any>>);
}
impl<T: ScheduleBuildPass> ScheduleBuildPassObj for T {
fn build(
&mut self,
world: &mut World,
graph: &mut ScheduleGraph,
dependency_flattened: &mut Dag<SystemKey>,
) -> Result<(), ScheduleBuildError> {
self.build(world, graph, dependency_flattened)
}
fn collapse_set(
&mut self,
set: SystemSetKey,
systems: &IndexSet<SystemKey, FixedHasher>,
dependency_flattening: &DiGraph<NodeId>,
dependencies_to_add: &mut Vec<(NodeId, NodeId)>,
) {
let iter = self.collapse_set(set, systems, dependency_flattening);
dependencies_to_add.extend(iter);
}
fn add_dependency(&mut self, from: NodeId, to: NodeId, all_options: &TypeIdMap<Box<dyn Any>>) {
let option = all_options
.get(&TypeId::of::<T::EdgeOptions>())
.and_then(|x| x.downcast_ref::<T::EdgeOptions>());
self.add_dependency(from, to, option);
}
}
| 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/schedule/set.rs | crates/bevy_ecs/src/schedule/set.rs | use alloc::boxed::Box;
use bevy_utils::prelude::DebugName;
use core::{
any::TypeId,
fmt::Debug,
hash::{Hash, Hasher},
marker::PhantomData,
};
pub use crate::label::DynEq;
pub use bevy_ecs_macros::{ScheduleLabel, SystemSet};
use crate::{
define_label,
intern::Interned,
system::{
ExclusiveFunctionSystem, ExclusiveSystemParamFunction, FromInput, FunctionSystem,
IntoResult, IsExclusiveFunctionSystem, IsFunctionSystem, SystemParamFunction,
},
};
define_label!(
/// A strongly-typed class of labels used to identify a [`Schedule`].
///
/// Each schedule in a [`World`] has a unique schedule label value, and
/// schedules can be automatically created from labels via [`Schedules::add_systems()`].
///
/// # Defining new schedule labels
///
/// By default, you should use Bevy's premade schedule labels which implement this trait.
/// If you are using [`bevy_ecs`] directly or if you need to run a group of systems outside
/// the existing schedules, you may define your own schedule labels by using
/// `#[derive(ScheduleLabel)]`.
///
/// ```
/// use bevy_ecs::prelude::*;
/// use bevy_ecs::schedule::ScheduleLabel;
///
/// // Declare a new schedule label.
/// #[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
/// struct Update;
///
/// let mut world = World::new();
///
/// // Add a system to the schedule with that label (creating it automatically).
/// fn a_system_function() {}
/// world.get_resource_or_init::<Schedules>().add_systems(Update, a_system_function);
///
/// // Run the schedule, and therefore run the system.
/// world.run_schedule(Update);
/// ```
///
/// [`Schedule`]: crate::schedule::Schedule
/// [`Schedules::add_systems()`]: crate::schedule::Schedules::add_systems
/// [`World`]: crate::world::World
#[diagnostic::on_unimplemented(
note = "consider annotating `{Self}` with `#[derive(ScheduleLabel)]`"
)]
ScheduleLabel,
SCHEDULE_LABEL_INTERNER
);
define_label!(
/// System sets are tag-like labels that can be used to group systems together.
///
/// This allows you to share configuration (like run conditions) across multiple systems,
/// and order systems or system sets relative to conceptual groups of systems.
/// To control the behavior of a system set as a whole, use [`Schedule::configure_sets`](crate::prelude::Schedule::configure_sets),
/// or the method of the same name on `App`.
///
/// Systems can belong to any number of system sets, reflecting multiple roles or facets that they might have.
/// For example, you may want to annotate a system as "consumes input" and "applies forces",
/// and ensure that your systems are ordered correctly for both of those sets.
///
/// System sets can belong to any number of other system sets,
/// allowing you to create nested hierarchies of system sets to group systems together.
/// Configuration applied to system sets will flow down to their members (including other system sets),
/// allowing you to set and modify the configuration in a single place.
///
/// Systems sets are also useful for exposing a consistent public API for dependencies
/// to hook into across versions of your crate,
/// allowing them to add systems to a specific set, or order relative to that set,
/// without leaking implementation details of the exact systems involved.
///
/// ## Defining new system sets
///
/// To create a new system set, use the `#[derive(SystemSet)]` macro.
/// Unit structs are a good choice for one-off sets.
///
/// ```rust
/// # use bevy_ecs::prelude::*;
///
/// #[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
/// struct PhysicsSystems;
/// ```
///
/// When you want to define several related system sets,
/// consider creating an enum system set.
/// Each variant will be treated as a separate system set.
///
/// ```rust
/// # use bevy_ecs::prelude::*;
///
/// #[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
/// enum CombatSystems {
/// TargetSelection,
/// DamageCalculation,
/// Cleanup,
/// }
/// ```
///
/// By convention, the listed order of the system set in the enum
/// corresponds to the order in which the systems are run.
/// Ordering must be explicitly added to ensure that this is the case,
/// but following this convention will help avoid confusion.
///
/// ### Adding systems to system sets
///
/// To add systems to a system set, call [`in_set`](crate::prelude::IntoScheduleConfigs::in_set) on the system function
/// while adding it to your app or schedule.
///
/// Like usual, these methods can be chained with other configuration methods like [`before`](crate::prelude::IntoScheduleConfigs::before),
/// or repeated to add systems to multiple sets.
///
/// ```rust
/// use bevy_ecs::prelude::*;
///
/// #[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
/// enum CombatSystems {
/// TargetSelection,
/// DamageCalculation,
/// Cleanup,
/// }
///
/// fn target_selection() {}
///
/// fn enemy_damage_calculation() {}
///
/// fn player_damage_calculation() {}
///
/// let mut schedule = Schedule::default();
/// // Configuring the sets to run in order.
/// schedule.configure_sets((CombatSystems::TargetSelection, CombatSystems::DamageCalculation, CombatSystems::Cleanup).chain());
///
/// // Adding a single system to a set.
/// schedule.add_systems(target_selection.in_set(CombatSystems::TargetSelection));
///
/// // Adding multiple systems to a set.
/// schedule.add_systems((player_damage_calculation, enemy_damage_calculation).in_set(CombatSystems::DamageCalculation));
/// ```
#[diagnostic::on_unimplemented(
note = "consider annotating `{Self}` with `#[derive(SystemSet)]`"
)]
SystemSet,
SYSTEM_SET_INTERNER,
extra_methods: {
/// Returns `Some` if this system set is a [`SystemTypeSet`].
fn system_type(&self) -> Option<TypeId> {
None
}
/// Returns `true` if this system set is an [`AnonymousSet`].
fn is_anonymous(&self) -> bool {
false
}
},
extra_methods_impl: {
fn system_type(&self) -> Option<TypeId> {
(**self).system_type()
}
fn is_anonymous(&self) -> bool {
(**self).is_anonymous()
}
}
);
/// A shorthand for `Interned<dyn SystemSet>`.
pub type InternedSystemSet = Interned<dyn SystemSet>;
/// A shorthand for `Interned<dyn ScheduleLabel>`.
pub type InternedScheduleLabel = Interned<dyn ScheduleLabel>;
/// A [`SystemSet`] grouping instances of the same function.
///
/// This kind of set is automatically populated and thus has some special rules:
/// - You cannot manually add members.
/// - You cannot configure them.
/// - You cannot order something relative to one if it has more than one member.
pub struct SystemTypeSet<T: 'static>(PhantomData<fn() -> T>);
impl<T: 'static> SystemTypeSet<T> {
pub(crate) fn new() -> Self {
Self(PhantomData)
}
}
impl<T> Debug for SystemTypeSet<T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_tuple("SystemTypeSet")
.field(&format_args!("fn {}()", DebugName::type_name::<T>()))
.finish()
}
}
impl<T> Hash for SystemTypeSet<T> {
fn hash<H: Hasher>(&self, _state: &mut H) {
// all systems of a given type are the same
}
}
impl<T> Clone for SystemTypeSet<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for SystemTypeSet<T> {}
impl<T> PartialEq for SystemTypeSet<T> {
#[inline]
fn eq(&self, _other: &Self) -> bool {
// all systems of a given type are the same
true
}
}
impl<T> Eq for SystemTypeSet<T> {}
impl<T> SystemSet for SystemTypeSet<T> {
fn system_type(&self) -> Option<TypeId> {
Some(TypeId::of::<T>())
}
fn dyn_clone(&self) -> Box<dyn SystemSet> {
Box::new(*self)
}
}
/// A [`SystemSet`] implicitly created when using
/// [`Schedule::add_systems`](super::Schedule::add_systems) or
/// [`Schedule::configure_sets`](super::Schedule::configure_sets).
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub struct AnonymousSet(usize);
impl AnonymousSet {
pub(crate) fn new(id: usize) -> Self {
Self(id)
}
}
impl SystemSet for AnonymousSet {
fn is_anonymous(&self) -> bool {
true
}
fn dyn_clone(&self) -> Box<dyn SystemSet> {
Box::new(*self)
}
}
/// Types that can be converted into a [`SystemSet`].
///
/// # Usage notes
///
/// This trait should only be used as a bound for trait implementations or as an
/// argument to a function. If a system set needs to be returned from a function
/// or stored somewhere, use [`SystemSet`] instead of this trait.
#[diagnostic::on_unimplemented(
message = "`{Self}` is not a system set",
label = "invalid system set"
)]
pub trait IntoSystemSet<Marker>: Sized {
/// The type of [`SystemSet`] this instance converts into.
type Set: SystemSet;
/// Converts this instance to its associated [`SystemSet`] type.
fn into_system_set(self) -> Self::Set;
}
// systems sets
impl<S: SystemSet> IntoSystemSet<()> for S {
type Set = Self;
#[inline]
fn into_system_set(self) -> Self::Set {
self
}
}
// systems
impl<Marker, F> IntoSystemSet<(IsFunctionSystem, Marker)> for F
where
Marker: 'static,
F: SystemParamFunction<Marker, In: FromInput<()>, Out: IntoResult<()>>,
{
type Set = SystemTypeSet<FunctionSystem<Marker, (), (), F>>;
#[inline]
fn into_system_set(self) -> Self::Set {
SystemTypeSet::<FunctionSystem<Marker, (), (), F>>::new()
}
}
// exclusive systems
impl<Marker, F> IntoSystemSet<(IsExclusiveFunctionSystem, Marker)> for F
where
Marker: 'static,
F::Out: IntoResult<()>,
F: ExclusiveSystemParamFunction<Marker>,
{
type Set = SystemTypeSet<ExclusiveFunctionSystem<Marker, (), F>>;
#[inline]
fn into_system_set(self) -> Self::Set {
SystemTypeSet::<ExclusiveFunctionSystem<Marker, (), F>>::new()
}
}
#[cfg(test)]
mod tests {
use crate::{
resource::Resource,
schedule::{tests::ResMut, Schedule},
system::{IntoSystem, System},
};
use super::*;
#[test]
fn test_schedule_label() {
use crate::world::World;
#[derive(Resource)]
struct Flag(bool);
#[derive(ScheduleLabel, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
struct A;
#[derive(ScheduleLabel, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
struct B;
let mut world = World::new();
let mut schedule = Schedule::new(A);
schedule.add_systems(|mut flag: ResMut<Flag>| flag.0 = true);
world.add_schedule(schedule);
let interned = A.intern();
world.insert_resource(Flag(false));
world.run_schedule(interned);
assert!(world.resource::<Flag>().0);
world.insert_resource(Flag(false));
world.run_schedule(interned);
assert!(world.resource::<Flag>().0);
assert_ne!(A.intern(), B.intern());
}
#[test]
fn test_derive_schedule_label() {
#[derive(ScheduleLabel, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
struct UnitLabel;
#[derive(ScheduleLabel, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
struct TupleLabel(u32, u32);
#[derive(ScheduleLabel, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
struct StructLabel {
a: u32,
b: u32,
}
#[expect(
dead_code,
reason = "This is a derive macro compilation test. It won't be constructed."
)]
#[derive(ScheduleLabel, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
struct EmptyTupleLabel();
#[expect(
dead_code,
reason = "This is a derive macro compilation test. It won't be constructed."
)]
#[derive(ScheduleLabel, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
struct EmptyStructLabel {}
#[derive(ScheduleLabel, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
enum EnumLabel {
#[default]
Unit,
Tuple(u32, u32),
Struct {
a: u32,
b: u32,
},
}
#[derive(ScheduleLabel, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
struct GenericLabel<T>(PhantomData<T>);
assert_eq!(UnitLabel.intern(), UnitLabel.intern());
assert_eq!(EnumLabel::Unit.intern(), EnumLabel::Unit.intern());
assert_ne!(UnitLabel.intern(), EnumLabel::Unit.intern());
assert_ne!(UnitLabel.intern(), TupleLabel(0, 0).intern());
assert_ne!(EnumLabel::Unit.intern(), EnumLabel::Tuple(0, 0).intern());
assert_eq!(TupleLabel(0, 0).intern(), TupleLabel(0, 0).intern());
assert_eq!(
EnumLabel::Tuple(0, 0).intern(),
EnumLabel::Tuple(0, 0).intern()
);
assert_ne!(TupleLabel(0, 0).intern(), TupleLabel(0, 1).intern());
assert_ne!(
EnumLabel::Tuple(0, 0).intern(),
EnumLabel::Tuple(0, 1).intern()
);
assert_ne!(TupleLabel(0, 0).intern(), EnumLabel::Tuple(0, 0).intern());
assert_ne!(
TupleLabel(0, 0).intern(),
StructLabel { a: 0, b: 0 }.intern()
);
assert_ne!(
EnumLabel::Tuple(0, 0).intern(),
EnumLabel::Struct { a: 0, b: 0 }.intern()
);
assert_eq!(
StructLabel { a: 0, b: 0 }.intern(),
StructLabel { a: 0, b: 0 }.intern()
);
assert_eq!(
EnumLabel::Struct { a: 0, b: 0 }.intern(),
EnumLabel::Struct { a: 0, b: 0 }.intern()
);
assert_ne!(
StructLabel { a: 0, b: 0 }.intern(),
StructLabel { a: 0, b: 1 }.intern()
);
assert_ne!(
EnumLabel::Struct { a: 0, b: 0 }.intern(),
EnumLabel::Struct { a: 0, b: 1 }.intern()
);
assert_ne!(
StructLabel { a: 0, b: 0 }.intern(),
EnumLabel::Struct { a: 0, b: 0 }.intern()
);
assert_ne!(
StructLabel { a: 0, b: 0 }.intern(),
EnumLabel::Struct { a: 0, b: 0 }.intern()
);
assert_ne!(StructLabel { a: 0, b: 0 }.intern(), UnitLabel.intern(),);
assert_ne!(
EnumLabel::Struct { a: 0, b: 0 }.intern(),
EnumLabel::Unit.intern()
);
assert_eq!(
GenericLabel::<u32>(PhantomData).intern(),
GenericLabel::<u32>(PhantomData).intern()
);
assert_ne!(
GenericLabel::<u32>(PhantomData).intern(),
GenericLabel::<u64>(PhantomData).intern()
);
}
#[test]
fn test_derive_system_set() {
#[derive(SystemSet, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
struct UnitSet;
#[derive(SystemSet, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
struct TupleSet(u32, u32);
#[derive(SystemSet, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
struct StructSet {
a: u32,
b: u32,
}
#[expect(
dead_code,
reason = "This is a derive macro compilation test. It won't be constructed."
)]
#[derive(SystemSet, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
struct EmptyTupleSet();
#[expect(
dead_code,
reason = "This is a derive macro compilation test. It won't be constructed."
)]
#[derive(SystemSet, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
struct EmptyStructSet {}
#[derive(SystemSet, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
enum EnumSet {
#[default]
Unit,
Tuple(u32, u32),
Struct {
a: u32,
b: u32,
},
}
#[derive(SystemSet, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
struct GenericSet<T>(PhantomData<T>);
assert_eq!(UnitSet.intern(), UnitSet.intern());
assert_eq!(EnumSet::Unit.intern(), EnumSet::Unit.intern());
assert_ne!(UnitSet.intern(), EnumSet::Unit.intern());
assert_ne!(UnitSet.intern(), TupleSet(0, 0).intern());
assert_ne!(EnumSet::Unit.intern(), EnumSet::Tuple(0, 0).intern());
assert_eq!(TupleSet(0, 0).intern(), TupleSet(0, 0).intern());
assert_eq!(EnumSet::Tuple(0, 0).intern(), EnumSet::Tuple(0, 0).intern());
assert_ne!(TupleSet(0, 0).intern(), TupleSet(0, 1).intern());
assert_ne!(EnumSet::Tuple(0, 0).intern(), EnumSet::Tuple(0, 1).intern());
assert_ne!(TupleSet(0, 0).intern(), EnumSet::Tuple(0, 0).intern());
assert_ne!(TupleSet(0, 0).intern(), StructSet { a: 0, b: 0 }.intern());
assert_ne!(
EnumSet::Tuple(0, 0).intern(),
EnumSet::Struct { a: 0, b: 0 }.intern()
);
assert_eq!(
StructSet { a: 0, b: 0 }.intern(),
StructSet { a: 0, b: 0 }.intern()
);
assert_eq!(
EnumSet::Struct { a: 0, b: 0 }.intern(),
EnumSet::Struct { a: 0, b: 0 }.intern()
);
assert_ne!(
StructSet { a: 0, b: 0 }.intern(),
StructSet { a: 0, b: 1 }.intern()
);
assert_ne!(
EnumSet::Struct { a: 0, b: 0 }.intern(),
EnumSet::Struct { a: 0, b: 1 }.intern()
);
assert_ne!(
StructSet { a: 0, b: 0 }.intern(),
EnumSet::Struct { a: 0, b: 0 }.intern()
);
assert_ne!(
StructSet { a: 0, b: 0 }.intern(),
EnumSet::Struct { a: 0, b: 0 }.intern()
);
assert_ne!(StructSet { a: 0, b: 0 }.intern(), UnitSet.intern(),);
assert_ne!(
EnumSet::Struct { a: 0, b: 0 }.intern(),
EnumSet::Unit.intern()
);
assert_eq!(
GenericSet::<u32>(PhantomData).intern(),
GenericSet::<u32>(PhantomData).intern()
);
assert_ne!(
GenericSet::<u32>(PhantomData).intern(),
GenericSet::<u64>(PhantomData).intern()
);
}
#[test]
fn system_set_matches_default_system_set() {
fn system() {}
let set_from_into_system_set = IntoSystemSet::into_system_set(system).intern();
let system = IntoSystem::into_system(system);
let set_from_system = system.default_system_sets()[0];
assert_eq!(set_from_into_system_set, set_from_system);
}
#[test]
fn system_set_matches_default_system_set_exclusive() {
fn system(_: &mut crate::world::World) {}
let set_from_into_system_set = IntoSystemSet::into_system_set(system).intern();
let system = IntoSystem::into_system(system);
let set_from_system = system.default_system_sets()[0];
assert_eq!(set_from_into_system_set, set_from_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/schedule/graph/graph_map.rs | crates/bevy_ecs/src/schedule/graph/graph_map.rs | //! `Graph<DIRECTED>` is a graph datastructure where node values are mapping
//! keys.
//! Based on the `GraphMap` datastructure from [`petgraph`].
//!
//! [`petgraph`]: https://docs.rs/petgraph/0.6.5/petgraph/
use alloc::{vec, vec::Vec};
use core::{
fmt::{self, Debug},
hash::{BuildHasher, Hash},
};
use thiserror::Error;
use bevy_platform::{
collections::{HashMap, HashSet},
hash::FixedHasher,
};
use indexmap::IndexMap;
use smallvec::SmallVec;
use Direction::{Incoming, Outgoing};
/// Types that can be used as node identifiers in a [`DiGraph`]/[`UnGraph`].
///
/// [`DiGraph`]: crate::schedule::graph::DiGraph
/// [`UnGraph`]: crate::schedule::graph::UnGraph
pub trait GraphNodeId: Copy + Eq + Hash + Ord + Debug {
/// The type that packs and unpacks this [`GraphNodeId`] with a [`Direction`].
/// This is used to save space in the graph's adjacency list.
type Adjacent: Copy + Debug + From<(Self, Direction)> + Into<(Self, Direction)>;
/// The type that packs and unpacks this [`GraphNodeId`] with another
/// [`GraphNodeId`]. This is used to save space in the graph's edge list.
type Edge: Copy + Eq + Hash + Debug + From<(Self, Self)> + Into<(Self, Self)>;
/// Name of the kind of this node id.
///
/// For structs, this should return a human-readable name of the struct.
/// For enums, this should return a human-readable name of the enum variant.
fn kind(&self) -> &'static str;
}
/// A `Graph` with undirected edges of some [`GraphNodeId`] `N`.
///
/// For example, an edge between *1* and *2* is equivalent to an edge between
/// *2* and *1*.
pub type UnGraph<N, S = FixedHasher> = Graph<false, N, S>;
/// A `Graph` with directed edges of some [`GraphNodeId`] `N`.
///
/// For example, an edge from *1* to *2* is distinct from an edge from *2* to
/// *1*.
pub type DiGraph<N, S = FixedHasher> = Graph<true, N, S>;
/// `Graph<DIRECTED>` is a graph datastructure using an associative array
/// of its node weights of some [`GraphNodeId`].
///
/// It uses a combined adjacency list and sparse adjacency matrix
/// representation, using **O(|N| + |E|)** space, and allows testing for edge
/// existence in constant time.
///
/// `Graph` is parameterized over:
///
/// - Constant generic bool `DIRECTED` determines whether the graph edges are directed or
/// undirected.
/// - The `GraphNodeId` type `N`, which is used as the node weight.
/// - The `BuildHasher` `S`.
///
/// You can use the type aliases `UnGraph` and `DiGraph` for convenience.
///
/// `Graph` does not allow parallel edges, but self loops are allowed.
#[derive(Clone)]
pub struct Graph<const DIRECTED: bool, N: GraphNodeId, S = FixedHasher>
where
S: BuildHasher,
{
nodes: IndexMap<N, Vec<N::Adjacent>, S>,
edges: HashSet<N::Edge, S>,
}
impl<const DIRECTED: bool, N: GraphNodeId, S: BuildHasher> Debug for Graph<DIRECTED, N, S> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.nodes.fmt(f)
}
}
impl<const DIRECTED: bool, N: GraphNodeId, S: BuildHasher> Graph<DIRECTED, N, S> {
/// Create a new `Graph` with estimated capacity.
pub fn with_capacity(nodes: usize, edges: usize) -> Self
where
S: Default,
{
Self {
nodes: IndexMap::with_capacity_and_hasher(nodes, S::default()),
edges: HashSet::with_capacity_and_hasher(edges, S::default()),
}
}
/// Use their natural order to map the node pair (a, b) to a canonical edge id.
#[inline]
fn edge_key(a: N, b: N) -> N::Edge {
let (a, b) = if DIRECTED || a <= b { (a, b) } else { (b, a) };
N::Edge::from((a, b))
}
/// Return the number of nodes in the graph.
pub fn node_count(&self) -> usize {
self.nodes.len()
}
/// Return the number of edges in the graph.
pub fn edge_count(&self) -> usize {
self.edges.len()
}
/// Add node `n` to the graph.
pub fn add_node(&mut self, n: N) {
self.nodes.entry(n).or_default();
}
/// Remove a node `n` from the graph.
///
/// Computes in **O(N)** time, due to the removal of edges with other nodes.
pub fn remove_node(&mut self, n: N) {
let Some(links) = self.nodes.swap_remove(&n) else {
return;
};
let links = links.into_iter().map(N::Adjacent::into);
for (succ, dir) in links {
let edge = if dir == Outgoing {
Self::edge_key(n, succ)
} else {
Self::edge_key(succ, n)
};
// remove all successor links
self.remove_single_edge(succ, n, dir.opposite());
// Remove all edge values
self.edges.remove(&edge);
}
}
/// Return `true` if the node is contained in the graph.
pub fn contains_node(&self, n: N) -> bool {
self.nodes.contains_key(&n)
}
/// Add an edge connecting `a` and `b` to the graph.
/// For a directed graph, the edge is directed from `a` to `b`.
///
/// Inserts nodes `a` and/or `b` if they aren't already part of the graph.
pub fn add_edge(&mut self, a: N, b: N) {
if self.edges.insert(Self::edge_key(a, b)) {
// insert in the adjacency list if it's a new edge
self.nodes
.entry(a)
.or_insert_with(|| Vec::with_capacity(1))
.push(N::Adjacent::from((b, Outgoing)));
if a != b {
// self loops don't have the Incoming entry
self.nodes
.entry(b)
.or_insert_with(|| Vec::with_capacity(1))
.push(N::Adjacent::from((a, Incoming)));
}
}
}
/// Remove edge relation from a to b.
///
/// Return `true` if it did exist.
fn remove_single_edge(&mut self, a: N, b: N, dir: Direction) -> bool {
let Some(sus) = self.nodes.get_mut(&a) else {
return false;
};
let Some(index) = sus
.iter()
.copied()
.map(N::Adjacent::into)
.position(|elt| (DIRECTED && elt == (b, dir)) || (!DIRECTED && elt.0 == b))
else {
return false;
};
sus.swap_remove(index);
true
}
/// Remove edge from `a` to `b` from the graph.
///
/// Return `false` if the edge didn't exist.
pub fn remove_edge(&mut self, a: N, b: N) -> bool {
let exist1 = self.remove_single_edge(a, b, Outgoing);
let exist2 = if a != b {
self.remove_single_edge(b, a, Incoming)
} else {
exist1
};
let weight = self.edges.remove(&Self::edge_key(a, b));
debug_assert!(exist1 == exist2 && exist1 == weight);
weight
}
/// Return `true` if the edge connecting `a` with `b` is contained in the graph.
pub fn contains_edge(&self, a: N, b: N) -> bool {
self.edges.contains(&Self::edge_key(a, b))
}
/// Reserve capacity for at least `additional` more nodes to be inserted
/// in the graph.
pub fn reserve_nodes(&mut self, additional: usize) {
self.nodes.reserve(additional);
}
/// Reserve capacity for at least `additional` more edges to be inserted
/// in the graph.
pub fn reserve_edges(&mut self, additional: usize) {
self.edges.reserve(additional);
}
/// Return an iterator over the nodes of the graph.
pub fn nodes(&self) -> impl DoubleEndedIterator<Item = N> + ExactSizeIterator<Item = N> + '_ {
self.nodes.keys().copied()
}
/// Return an iterator of all nodes with an edge starting from `a`.
pub fn neighbors(&self, a: N) -> impl DoubleEndedIterator<Item = N> + '_ {
let iter = match self.nodes.get(&a) {
Some(neigh) => neigh.iter(),
None => [].iter(),
};
iter.copied()
.map(N::Adjacent::into)
.filter_map(|(n, dir)| (!DIRECTED || dir == Outgoing).then_some(n))
}
/// Return an iterator of all neighbors that have an edge between them and
/// `a`, in the specified direction.
/// If the graph's edges are undirected, this is equivalent to *.neighbors(a)*.
pub fn neighbors_directed(
&self,
a: N,
dir: Direction,
) -> impl DoubleEndedIterator<Item = N> + '_ {
let iter = match self.nodes.get(&a) {
Some(neigh) => neigh.iter(),
None => [].iter(),
};
iter.copied()
.map(N::Adjacent::into)
.filter_map(move |(n, d)| (!DIRECTED || d == dir || n == a).then_some(n))
}
/// Return an iterator of target nodes with an edge starting from `a`,
/// paired with their respective edge weights.
pub fn edges(&self, a: N) -> impl DoubleEndedIterator<Item = (N, N)> + '_ {
self.neighbors(a)
.map(move |b| match self.edges.get(&Self::edge_key(a, b)) {
None => unreachable!(),
Some(_) => (a, b),
})
}
/// Return an iterator of target nodes with an edge starting from `a`,
/// paired with their respective edge weights.
pub fn edges_directed(
&self,
a: N,
dir: Direction,
) -> impl DoubleEndedIterator<Item = (N, N)> + '_ {
self.neighbors_directed(a, dir).map(move |b| {
let (a, b) = if dir == Incoming { (b, a) } else { (a, b) };
match self.edges.get(&Self::edge_key(a, b)) {
None => unreachable!(),
Some(_) => (a, b),
}
})
}
/// Return an iterator over all edges of the graph with their weight in arbitrary order.
pub fn all_edges(&self) -> impl ExactSizeIterator<Item = (N, N)> + '_ {
self.edges.iter().copied().map(N::Edge::into)
}
pub(crate) fn to_index(&self, ix: N) -> usize {
self.nodes.get_index_of(&ix).unwrap()
}
/// Converts from one [`GraphNodeId`] type to another. If the conversion fails,
/// it returns the error from the target type's [`TryFrom`] implementation.
///
/// Nodes must uniquely convert from `N` to `T` (i.e. no two `N` can convert
/// to the same `T`).
///
/// # Errors
///
/// If the conversion fails, it returns an error of type `N::Error`.
pub fn try_convert<T>(self) -> Result<Graph<DIRECTED, T, S>, N::Error>
where
N: TryInto<T>,
T: GraphNodeId,
S: Default,
{
// Converts the node key and every adjacency list entry from `N` to `T`.
fn try_convert_node<N: GraphNodeId + TryInto<T>, T: GraphNodeId>(
(key, adj): (N, Vec<N::Adjacent>),
) -> Result<(T, Vec<T::Adjacent>), N::Error> {
let key = key.try_into()?;
let adj = adj
.into_iter()
.map(|node| {
let (id, dir) = node.into();
Ok(T::Adjacent::from((id.try_into()?, dir)))
})
.collect::<Result<_, N::Error>>()?;
Ok((key, adj))
}
// Unpacks the edge pair, converts the nodes from `N` to `T`, and repacks them.
fn try_convert_edge<N: GraphNodeId + TryInto<T>, T: GraphNodeId>(
edge: N::Edge,
) -> Result<T::Edge, N::Error> {
let (a, b) = edge.into();
Ok(T::Edge::from((a.try_into()?, b.try_into()?)))
}
let nodes = self
.nodes
.into_iter()
.map(try_convert_node::<N, T>)
.collect::<Result<_, N::Error>>()?;
let edges = self
.edges
.into_iter()
.map(try_convert_edge::<N, T>)
.collect::<Result<_, N::Error>>()?;
Ok(Graph { nodes, edges })
}
}
/// Create a new empty `Graph`.
impl<const DIRECTED: bool, N, S> Default for Graph<DIRECTED, N, S>
where
N: GraphNodeId,
S: BuildHasher + Default,
{
fn default() -> Self {
Self::with_capacity(0, 0)
}
}
impl<N: GraphNodeId, S: BuildHasher> DiGraph<N, S> {
/// Tries to topologically sort this directed graph.
///
/// If the graph is acyclic, returns [`Ok`] with the list of [`GraphNodeId`]s
/// in a valid topological order. If the graph contains cycles, returns [`Err`]
/// with the list of strongly-connected components that contain cycles
/// (also in a valid topological order).
///
/// # Errors
///
/// - If the graph contains a self-loop, returns [`DiGraphToposortError::Loop`].
/// - If the graph contains cycles, returns [`DiGraphToposortError::Cycle`].
pub fn toposort(&self, mut scratch: Vec<N>) -> Result<Vec<N>, DiGraphToposortError<N>> {
// Check explicitly for self-edges.
// `iter_sccs` won't report them as cycles because they still form components of one node.
if let Some((node, _)) = self.all_edges().find(|(left, right)| left == right) {
return Err(DiGraphToposortError::Loop(node));
}
// Tarjan's SCC algorithm returns elements in *reverse* topological order.
scratch.clear();
scratch.reserve_exact(self.node_count().saturating_sub(scratch.capacity()));
let mut top_sorted_nodes = scratch;
let mut sccs_with_cycles = Vec::new();
for scc in self.iter_sccs() {
// A strongly-connected component is a group of nodes who can all reach each other
// through one or more paths. If an SCC contains more than one node, there must be
// at least one cycle within them.
top_sorted_nodes.extend_from_slice(&scc);
if scc.len() > 1 {
sccs_with_cycles.push(scc);
}
}
if sccs_with_cycles.is_empty() {
// reverse to get topological order
top_sorted_nodes.reverse();
Ok(top_sorted_nodes)
} else {
let mut cycles = Vec::new();
for scc in &sccs_with_cycles {
cycles.append(&mut self.simple_cycles_in_component(scc));
}
Err(DiGraphToposortError::Cycle(cycles))
}
}
/// Returns the simple cycles in a strongly-connected component of a directed graph.
///
/// The algorithm implemented comes from
/// ["Finding all the elementary circuits of a directed graph"][1] by D. B. Johnson.
///
/// [1]: https://doi.org/10.1137/0204007
pub fn simple_cycles_in_component(&self, scc: &[N]) -> Vec<Vec<N>> {
let mut cycles = vec![];
let mut sccs = vec![SmallVec::from_slice(scc)];
while let Some(mut scc) = sccs.pop() {
// only look at nodes and edges in this strongly-connected component
let mut subgraph = DiGraph::<N>::with_capacity(scc.len(), 0);
for &node in &scc {
subgraph.add_node(node);
}
for &node in &scc {
for successor in self.neighbors(node) {
if subgraph.contains_node(successor) {
subgraph.add_edge(node, successor);
}
}
}
// path of nodes that may form a cycle
let mut path = Vec::with_capacity(subgraph.node_count());
// we mark nodes as "blocked" to avoid finding permutations of the same cycles
let mut blocked: HashSet<_> =
HashSet::with_capacity_and_hasher(subgraph.node_count(), Default::default());
// connects nodes along path segments that can't be part of a cycle (given current root)
// those nodes can be unblocked at the same time
let mut unblock_together: HashMap<N, HashSet<N>> =
HashMap::with_capacity_and_hasher(subgraph.node_count(), Default::default());
// stack for unblocking nodes
let mut unblock_stack = Vec::with_capacity(subgraph.node_count());
// nodes can be involved in multiple cycles
let mut maybe_in_more_cycles: HashSet<N> =
HashSet::with_capacity_and_hasher(subgraph.node_count(), Default::default());
// stack for DFS
let mut stack = Vec::with_capacity(subgraph.node_count());
// we're going to look for all cycles that begin and end at this node
let root = scc.pop().unwrap();
// start a path at the root
path.clear();
path.push(root);
// mark this node as blocked
blocked.insert(root);
// DFS
stack.clear();
stack.push((root, subgraph.neighbors(root)));
while !stack.is_empty() {
let &mut (ref node, ref mut successors) = stack.last_mut().unwrap();
if let Some(next) = successors.next() {
if next == root {
// found a cycle
maybe_in_more_cycles.extend(path.iter());
cycles.push(path.clone());
} else if !blocked.contains(&next) {
// first time seeing `next` on this path
maybe_in_more_cycles.remove(&next);
path.push(next);
blocked.insert(next);
stack.push((next, subgraph.neighbors(next)));
continue;
} else {
// not first time seeing `next` on this path
}
}
if successors.peekable().peek().is_none() {
if maybe_in_more_cycles.contains(node) {
unblock_stack.push(*node);
// unblock this node's ancestors
while let Some(n) = unblock_stack.pop() {
if blocked.remove(&n) {
let unblock_predecessors = unblock_together.entry(n).or_default();
unblock_stack.extend(unblock_predecessors.iter());
unblock_predecessors.clear();
}
}
} else {
// if its descendants can be unblocked later, this node will be too
for successor in subgraph.neighbors(*node) {
unblock_together.entry(successor).or_default().insert(*node);
}
}
// remove node from path and DFS stack
path.pop();
stack.pop();
}
}
drop(stack);
// remove node from subgraph
subgraph.remove_node(root);
// divide remainder into smaller SCCs
sccs.extend(subgraph.iter_sccs().filter(|scc| scc.len() > 1));
}
cycles
}
/// Iterate over all *Strongly Connected Components* in this graph.
pub(crate) fn iter_sccs(&self) -> impl Iterator<Item = SmallVec<[N; 4]>> + '_ {
super::tarjan_scc::new_tarjan_scc(self)
}
}
/// Error returned when topologically sorting a directed graph fails.
#[derive(Error, Debug)]
pub enum DiGraphToposortError<N: GraphNodeId> {
/// A self-loop was detected.
#[error("self-loop detected at node `{0:?}`")]
Loop(N),
/// Cycles were detected.
#[error("cycles detected: {0:?}")]
Cycle(Vec<Vec<N>>),
}
/// Edge direction.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Ord, Eq, Hash)]
#[repr(u8)]
pub enum Direction {
/// An `Outgoing` edge is an outward edge *from* the current node.
Outgoing = 0,
/// An `Incoming` edge is an inbound edge *to* the current node.
Incoming = 1,
}
impl Direction {
/// Return the opposite `Direction`.
#[inline]
pub fn opposite(self) -> Self {
match self {
Self::Outgoing => Self::Incoming,
Self::Incoming => Self::Outgoing,
}
}
}
#[cfg(test)]
mod tests {
use crate::schedule::{NodeId, SystemKey};
use super::*;
use alloc::vec;
use slotmap::SlotMap;
/// The `Graph` type _must_ preserve the order that nodes are inserted in if
/// no removals occur. Removals are permitted to swap the latest node into the
/// location of the removed node.
#[test]
fn node_order_preservation() {
use NodeId::System;
let mut slotmap = SlotMap::<SystemKey, ()>::with_key();
let mut graph = DiGraph::<NodeId>::default();
let sys1 = slotmap.insert(());
let sys2 = slotmap.insert(());
let sys3 = slotmap.insert(());
let sys4 = slotmap.insert(());
graph.add_node(System(sys1));
graph.add_node(System(sys2));
graph.add_node(System(sys3));
graph.add_node(System(sys4));
assert_eq!(
graph.nodes().collect::<Vec<_>>(),
vec![System(sys1), System(sys2), System(sys3), System(sys4)]
);
graph.remove_node(System(sys1));
assert_eq!(
graph.nodes().collect::<Vec<_>>(),
vec![System(sys4), System(sys2), System(sys3)]
);
graph.remove_node(System(sys4));
assert_eq!(
graph.nodes().collect::<Vec<_>>(),
vec![System(sys3), System(sys2)]
);
graph.remove_node(System(sys2));
assert_eq!(graph.nodes().collect::<Vec<_>>(), vec![System(sys3)]);
graph.remove_node(System(sys3));
assert_eq!(graph.nodes().collect::<Vec<_>>(), vec![]);
}
/// Nodes that have bidirectional edges (or any edge in the case of undirected graphs) are
/// considered strongly connected. A strongly connected component is a collection of
/// nodes where there exists a path from any node to any other node in the collection.
#[test]
fn strongly_connected_components() {
use NodeId::System;
let mut slotmap = SlotMap::<SystemKey, ()>::with_key();
let mut graph = DiGraph::<NodeId>::default();
let sys1 = slotmap.insert(());
let sys2 = slotmap.insert(());
let sys3 = slotmap.insert(());
let sys4 = slotmap.insert(());
let sys5 = slotmap.insert(());
let sys6 = slotmap.insert(());
graph.add_edge(System(sys1), System(sys2));
graph.add_edge(System(sys2), System(sys1));
graph.add_edge(System(sys2), System(sys3));
graph.add_edge(System(sys3), System(sys2));
graph.add_edge(System(sys4), System(sys5));
graph.add_edge(System(sys5), System(sys4));
graph.add_edge(System(sys6), System(sys2));
let sccs = graph
.iter_sccs()
.map(|scc| scc.to_vec())
.collect::<Vec<_>>();
assert_eq!(
sccs,
vec![
vec![System(sys3), System(sys2), System(sys1)],
vec![System(sys5), System(sys4)],
vec![System(sys6)]
]
);
}
}
| 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/schedule/graph/dag.rs | crates/bevy_ecs/src/schedule/graph/dag.rs | use alloc::vec::Vec;
use core::{
fmt::{self, Debug},
hash::{BuildHasher, Hash},
ops::{Deref, DerefMut},
};
use bevy_platform::{
collections::{HashMap, HashSet},
hash::FixedHasher,
};
use fixedbitset::FixedBitSet;
use indexmap::IndexSet;
use thiserror::Error;
use crate::{
error::Result,
schedule::graph::{
index, row_col, DiGraph, DiGraphToposortError,
Direction::{Incoming, Outgoing},
GraphNodeId, UnGraph,
},
};
/// A directed acyclic graph structure.
#[derive(Clone)]
pub struct Dag<N: GraphNodeId, S: BuildHasher = FixedHasher> {
/// The underlying directed graph.
graph: DiGraph<N, S>,
/// A cached topological ordering of the graph. This is recomputed when the
/// graph is modified, and is not valid when `dirty` is true.
toposort: Vec<N>,
/// Whether the graph has been modified since the last topological sort.
dirty: bool,
}
impl<N: GraphNodeId, S: BuildHasher> Dag<N, S> {
/// Creates a new directed acyclic graph.
pub fn new() -> Self
where
S: Default,
{
Self::default()
}
/// Read-only access to the underlying directed graph.
#[must_use]
pub fn graph(&self) -> &DiGraph<N, S> {
&self.graph
}
/// Mutable access to the underlying directed graph. Marks the graph as dirty.
#[must_use = "This function marks the graph as dirty, so it should be used."]
pub fn graph_mut(&mut self) -> &mut DiGraph<N, S> {
self.dirty = true;
&mut self.graph
}
/// Returns whether the graph is dirty (i.e., has been modified since the
/// last topological sort).
#[must_use]
pub fn is_dirty(&self) -> bool {
self.dirty
}
/// Returns whether the graph is topologically sorted (i.e., not dirty).
#[must_use]
pub fn is_toposorted(&self) -> bool {
!self.dirty
}
/// Ensures the graph is topologically sorted, recomputing the toposort if
/// the graph is dirty.
///
/// # Errors
///
/// Returns [`DiGraphToposortError`] if the DAG is dirty and cannot be
/// topologically sorted.
pub fn ensure_toposorted(&mut self) -> Result<(), DiGraphToposortError<N>> {
if self.dirty {
// recompute the toposort, reusing the existing allocation
self.toposort = self.graph.toposort(core::mem::take(&mut self.toposort))?;
self.dirty = false;
}
Ok(())
}
/// Returns the cached toposort if the graph is not dirty, otherwise returns
/// `None`.
#[must_use = "This method only returns a cached value and does not compute anything."]
pub fn get_toposort(&self) -> Option<&[N]> {
if self.dirty {
None
} else {
Some(&self.toposort)
}
}
/// Returns a topological ordering of the graph, computing it if the graph
/// is dirty.
///
/// # Errors
///
/// Returns [`DiGraphToposortError`] if the DAG is dirty and cannot be
/// topologically sorted.
pub fn toposort(&mut self) -> Result<&[N], DiGraphToposortError<N>> {
self.ensure_toposorted()?;
Ok(&self.toposort)
}
/// Returns both the topological ordering and the underlying graph,
/// computing the toposort if the graph is dirty.
///
/// This function is useful to avoid multiple borrow issues when both
/// the graph and the toposort are needed.
///
/// # Errors
///
/// Returns [`DiGraphToposortError`] if the DAG is dirty and cannot be
/// topologically sorted.
pub fn toposort_and_graph(
&mut self,
) -> Result<(&[N], &DiGraph<N, S>), DiGraphToposortError<N>> {
self.ensure_toposorted()?;
Ok((&self.toposort, &self.graph))
}
/// Processes a DAG and computes various properties about it.
///
/// See [`DagAnalysis::new`] for details on what is computed.
///
/// # Note
///
/// If the DAG is dirty, this method will first attempt to topologically sort it.
///
/// # Errors
///
/// Returns [`DiGraphToposortError`] if the DAG is dirty and cannot be
/// topologically sorted.
///
pub fn analyze(&mut self) -> Result<DagAnalysis<N, S>, DiGraphToposortError<N>>
where
S: Default,
{
let (toposort, graph) = self.toposort_and_graph()?;
Ok(DagAnalysis::new(graph, toposort))
}
/// Replaces the current graph with its transitive reduction based on the
/// provided analysis.
///
/// # Note
///
/// The given [`DagAnalysis`] must have been generated from this DAG.
pub fn remove_redundant_edges(&mut self, analysis: &DagAnalysis<N, S>)
where
S: Clone,
{
// We don't need to mark the graph as dirty, since transitive reduction
// is guaranteed to have the same topological ordering as the original graph.
self.graph = analysis.transitive_reduction.clone();
}
/// Groups nodes in this DAG by a key type `K`, collecting value nodes `V`
/// under all of their ancestor key nodes. `num_groups` hints at the
/// expected number of groups, for memory allocation optimization.
///
/// The node type `N` must be convertible into either a key type `K` or
/// a value type `V` via the [`TryInto`] trait.
///
/// # Errors
///
/// Returns [`DiGraphToposortError`] if the DAG is dirty and cannot be
/// topologically sorted.
pub fn group_by_key<K, V>(
&mut self,
num_groups: usize,
) -> Result<DagGroups<K, V, S>, DiGraphToposortError<N>>
where
N: TryInto<K, Error = V>,
K: Eq + Hash,
V: Clone + Eq + Hash,
S: BuildHasher + Default,
{
let (toposort, graph) = self.toposort_and_graph()?;
Ok(DagGroups::with_capacity(num_groups, graph, toposort))
}
/// Converts from one [`GraphNodeId`] type to another. If the conversion fails,
/// it returns the error from the target type's [`TryFrom`] implementation.
///
/// Nodes must uniquely convert from `N` to `T` (i.e. no two `N` can convert
/// to the same `T`). The resulting DAG must be re-topologically sorted.
///
/// # Errors
///
/// If the conversion fails, it returns an error of type `N::Error`.
pub fn try_convert<T>(self) -> Result<Dag<T, S>, N::Error>
where
N: TryInto<T>,
T: GraphNodeId,
S: Default,
{
Ok(Dag {
graph: self.graph.try_convert()?,
toposort: Vec::new(),
dirty: true,
})
}
}
impl<N: GraphNodeId, S: BuildHasher> Deref for Dag<N, S> {
type Target = DiGraph<N, S>;
fn deref(&self) -> &Self::Target {
self.graph()
}
}
impl<N: GraphNodeId, S: BuildHasher> DerefMut for Dag<N, S> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.graph_mut()
}
}
impl<N: GraphNodeId, S: BuildHasher + Default> Default for Dag<N, S> {
fn default() -> Self {
Self {
graph: Default::default(),
toposort: Default::default(),
dirty: false,
}
}
}
impl<N: GraphNodeId, S: BuildHasher> Debug for Dag<N, S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.dirty {
f.debug_struct("Dag")
.field("graph", &self.graph)
.field("dirty", &self.dirty)
.finish()
} else {
f.debug_struct("Dag")
.field("graph", &self.graph)
.field("toposort", &self.toposort)
.finish()
}
}
}
/// Stores the results of a call to [`Dag::analyze`].
pub struct DagAnalysis<N: GraphNodeId, S: BuildHasher = FixedHasher> {
/// Boolean reachability matrix for the graph.
reachable: FixedBitSet,
/// Pairs of nodes that have a path connecting them.
connected: HashSet<(N, N), S>,
/// Pairs of nodes that don't have a path connecting them.
disconnected: Vec<(N, N)>,
/// Edges that are redundant because a longer path exists.
transitive_edges: Vec<(N, N)>,
/// Variant of the graph with no transitive edges.
transitive_reduction: DiGraph<N, S>,
/// Variant of the graph with all possible transitive edges.
transitive_closure: DiGraph<N, S>,
}
impl<N: GraphNodeId, S: BuildHasher> DagAnalysis<N, S> {
/// Processes a DAG and computes its:
/// - transitive reduction (along with the set of removed edges)
/// - transitive closure
/// - reachability matrix (as a bitset)
/// - pairs of nodes connected by a path
/// - pairs of nodes not connected by a path
///
/// The algorithm implemented comes from
/// ["On the calculation of transitive reduction-closure of orders"][1] by Habib, Morvan and Rampon.
///
/// [1]: https://doi.org/10.1016/0012-365X(93)90164-O
pub fn new(graph: &DiGraph<N, S>, topological_order: &[N]) -> Self
where
S: Default,
{
if graph.node_count() == 0 {
return DagAnalysis::default();
}
let n = graph.node_count();
// build a copy of the graph where the nodes and edges appear in topsorted order
let mut map = <HashMap<_, _>>::with_capacity_and_hasher(n, Default::default());
let mut topsorted =
DiGraph::<N>::with_capacity(topological_order.len(), graph.edge_count());
// iterate nodes in topological order
for (i, &node) in topological_order.iter().enumerate() {
map.insert(node, i);
topsorted.add_node(node);
// insert nodes as successors to their predecessors
for pred in graph.neighbors_directed(node, Incoming) {
topsorted.add_edge(pred, node);
}
}
let mut reachable = FixedBitSet::with_capacity(n * n);
let mut connected = HashSet::default();
let mut disconnected = Vec::default();
let mut transitive_edges = Vec::default();
let mut transitive_reduction = DiGraph::with_capacity(topsorted.node_count(), 0);
let mut transitive_closure = DiGraph::with_capacity(topsorted.node_count(), 0);
let mut visited = FixedBitSet::with_capacity(n);
// iterate nodes in topological order
for node in topsorted.nodes() {
transitive_reduction.add_node(node);
transitive_closure.add_node(node);
}
// iterate nodes in reverse topological order
for a in topsorted.nodes().rev() {
let index_a = *map.get(&a).unwrap();
// iterate their successors in topological order
for b in topsorted.neighbors_directed(a, Outgoing) {
let index_b = *map.get(&b).unwrap();
debug_assert!(index_a < index_b);
if !visited[index_b] {
// edge <a, b> is not redundant
transitive_reduction.add_edge(a, b);
transitive_closure.add_edge(a, b);
reachable.insert(index(index_a, index_b, n));
let successors = transitive_closure
.neighbors_directed(b, Outgoing)
.collect::<Vec<_>>();
for c in successors {
let index_c = *map.get(&c).unwrap();
debug_assert!(index_b < index_c);
if !visited[index_c] {
visited.insert(index_c);
transitive_closure.add_edge(a, c);
reachable.insert(index(index_a, index_c, n));
}
}
} else {
// edge <a, b> is redundant
transitive_edges.push((a, b));
}
}
visited.clear();
}
// partition pairs of nodes into "connected by path" and "not connected by path"
for i in 0..(n - 1) {
// reachable is upper triangular because the nodes were topsorted
for index in index(i, i + 1, n)..=index(i, n - 1, n) {
let (a, b) = row_col(index, n);
let pair = (topological_order[a], topological_order[b]);
if reachable[index] {
connected.insert(pair);
} else {
disconnected.push(pair);
}
}
}
// fill diagonal (nodes reach themselves)
// for i in 0..n {
// reachable.set(index(i, i, n), true);
// }
DagAnalysis {
reachable,
connected,
disconnected,
transitive_edges,
transitive_reduction,
transitive_closure,
}
}
/// Returns the reachability matrix.
pub fn reachable(&self) -> &FixedBitSet {
&self.reachable
}
/// Returns the set of node pairs that are connected by a path.
pub fn connected(&self) -> &HashSet<(N, N), S> {
&self.connected
}
/// Returns the list of node pairs that are not connected by a path.
pub fn disconnected(&self) -> &[(N, N)] {
&self.disconnected
}
/// Returns the list of redundant edges because a longer path exists.
pub fn transitive_edges(&self) -> &[(N, N)] {
&self.transitive_edges
}
/// Returns the transitive reduction of the graph.
pub fn transitive_reduction(&self) -> &DiGraph<N, S> {
&self.transitive_reduction
}
/// Returns the transitive closure of the graph.
pub fn transitive_closure(&self) -> &DiGraph<N, S> {
&self.transitive_closure
}
/// Checks if the graph has any redundant (transitive) edges.
///
/// # Errors
///
/// If there are redundant edges, returns a [`DagRedundancyError`]
/// containing the list of redundant edges.
pub fn check_for_redundant_edges(&self) -> Result<(), DagRedundancyError<N>>
where
S: Clone,
{
if self.transitive_edges.is_empty() {
Ok(())
} else {
Err(DagRedundancyError(self.transitive_edges.clone()))
}
}
/// Checks if there are any pairs of nodes that have a path in both this
/// graph and another graph.
///
/// # Errors
///
/// Returns [`DagCrossDependencyError`] if any node pair is connected in
/// both graphs.
pub fn check_for_cross_dependencies(
&self,
other: &Self,
) -> Result<(), DagCrossDependencyError<N>> {
for &(a, b) in &self.connected {
if other.connected.contains(&(a, b)) || other.connected.contains(&(b, a)) {
return Err(DagCrossDependencyError(a, b));
}
}
Ok(())
}
/// Checks if any connected node pairs that are both keys have overlapping
/// groups.
///
/// # Errors
///
/// If there are overlapping groups, returns a [`DagOverlappingGroupError`]
/// containing the first pair of keys that have overlapping groups.
pub fn check_for_overlapping_groups<K, V>(
&self,
groups: &DagGroups<K, V>,
) -> Result<(), DagOverlappingGroupError<K>>
where
N: TryInto<K>,
K: Eq + Hash,
V: Eq + Hash,
{
for &(a, b) in &self.connected {
let (Ok(a_key), Ok(b_key)) = (a.try_into(), b.try_into()) else {
continue;
};
let a_group = groups.get(&a_key).unwrap();
let b_group = groups.get(&b_key).unwrap();
if !a_group.is_disjoint(b_group) {
return Err(DagOverlappingGroupError(a_key, b_key));
}
}
Ok(())
}
}
impl<N: GraphNodeId, S: BuildHasher + Default> Default for DagAnalysis<N, S> {
fn default() -> Self {
Self {
reachable: Default::default(),
connected: Default::default(),
disconnected: Default::default(),
transitive_edges: Default::default(),
transitive_reduction: Default::default(),
transitive_closure: Default::default(),
}
}
}
impl<N: GraphNodeId, S: BuildHasher> Debug for DagAnalysis<N, S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DagAnalysis")
.field("reachable", &self.reachable)
.field("connected", &self.connected)
.field("disconnected", &self.disconnected)
.field("transitive_edges", &self.transitive_edges)
.field("transitive_reduction", &self.transitive_reduction)
.field("transitive_closure", &self.transitive_closure)
.finish()
}
}
/// A mapping of keys to groups of values in a [`Dag`].
pub struct DagGroups<K, V, S = FixedHasher>(HashMap<K, IndexSet<V, S>, S>);
impl<K: Eq + Hash, V: Clone + Eq + Hash, S: BuildHasher + Default> DagGroups<K, V, S> {
/// Groups nodes in this DAG by a key type `K`, collecting value nodes `V`
/// under all of their ancestor key nodes.
///
/// The node type `N` must be convertible into either a key type `K` or
/// a value type `V` via the [`TryInto`] trait.
pub fn new<N>(graph: &DiGraph<N, S>, toposort: &[N]) -> Self
where
N: GraphNodeId + TryInto<K, Error = V>,
{
Self::with_capacity(0, graph, toposort)
}
/// Groups nodes in this DAG by a key type `K`, collecting value nodes `V`
/// under all of their ancestor key nodes. `capacity` hints at the
/// expected number of groups, for memory allocation optimization.
///
/// The node type `N` must be convertible into either a key type `K` or
/// a value type `V` via the [`TryInto`] trait.
pub fn with_capacity<N>(capacity: usize, graph: &DiGraph<N, S>, toposort: &[N]) -> Self
where
N: GraphNodeId + TryInto<K, Error = V>,
{
let mut groups: HashMap<K, IndexSet<V, S>, S> =
HashMap::with_capacity_and_hasher(capacity, Default::default());
// Iterate in reverse topological order (bottom-up) so we hit children before parents.
for &id in toposort.iter().rev() {
let Ok(key) = id.try_into() else {
continue;
};
let mut children = IndexSet::default();
for node in graph.neighbors_directed(id, Outgoing) {
match node.try_into() {
Ok(key) => {
// If the child is a key, this key inherits all of its children.
let key_children = groups.get(&key).unwrap();
children.extend(key_children.iter().cloned());
}
Err(value) => {
// If the child is a value, add it directly.
children.insert(value);
}
}
}
groups.insert(key, children);
}
Self(groups)
}
}
impl<K: GraphNodeId, V: GraphNodeId, S: BuildHasher> DagGroups<K, V, S> {
/// Converts the given [`Dag`] into a flattened version where key nodes
/// (`K`) are replaced by their associated value nodes (`V`). Edges to/from
/// key nodes are redirected to connect their value nodes instead.
///
/// The `collapse_group` function is called for each key node to customize
/// how its group is collapsed.
///
/// The resulting [`Dag`] will have only value nodes (`V`).
pub fn flatten<N>(
&self,
dag: Dag<N>,
mut collapse_group: impl FnMut(K, &IndexSet<V, S>, &Dag<N>, &mut Vec<(N, N)>),
) -> Dag<V>
where
N: GraphNodeId + TryInto<V, Error = K> + From<K> + From<V>,
{
let mut flattening = dag;
let mut temp = Vec::new();
for (&key, values) in self.iter() {
// Call the user-provided function to handle collapsing the group.
collapse_group(key, values, &flattening, &mut temp);
if values.is_empty() {
// Replace connections to the key node with connections between its neighbors.
for a in flattening.neighbors_directed(N::from(key), Incoming) {
for b in flattening.neighbors_directed(N::from(key), Outgoing) {
temp.push((a, b));
}
}
} else {
// Redirect edges to/from the key node to connect to its value nodes.
for a in flattening.neighbors_directed(N::from(key), Incoming) {
for &value in values {
temp.push((a, N::from(value)));
}
}
for b in flattening.neighbors_directed(N::from(key), Outgoing) {
for &value in values {
temp.push((N::from(value), b));
}
}
}
// Remove the key node from the graph.
flattening.remove_node(N::from(key));
// Add all previously collected edges.
flattening.reserve_edges(temp.len());
for (a, b) in temp.drain(..) {
flattening.add_edge(a, b);
}
}
// By this point, we should have removed all keys from the graph,
// so this conversion should never fail.
flattening
.try_convert::<V>()
.unwrap_or_else(|n| unreachable!("Flattened graph has a leftover key {n:?}"))
}
/// Converts an undirected graph by replacing key nodes (`K`) with their
/// associated value nodes (`V`). Edges connected to key nodes are
/// redirected to connect their value nodes instead.
///
/// The resulting undirected graph will have only value nodes (`V`).
pub fn flatten_undirected<N>(&self, graph: &UnGraph<N>) -> UnGraph<V>
where
N: GraphNodeId + TryInto<V, Error = K>,
{
let mut flattened = UnGraph::default();
for (lhs, rhs) in graph.all_edges() {
match (lhs.try_into(), rhs.try_into()) {
(Ok(lhs), Ok(rhs)) => {
// Normal edge between two value nodes
flattened.add_edge(lhs, rhs);
}
(Err(lhs_key), Ok(rhs)) => {
// Edge from a key node to a value node, expand to all values in the key's group
let Some(lhs_group) = self.get(&lhs_key) else {
continue;
};
flattened.reserve_edges(lhs_group.len());
for &lhs in lhs_group {
flattened.add_edge(lhs, rhs);
}
}
(Ok(lhs), Err(rhs_key)) => {
// Edge from a value node to a key node, expand to all values in the key's group
let Some(rhs_group) = self.get(&rhs_key) else {
continue;
};
flattened.reserve_edges(rhs_group.len());
for &rhs in rhs_group {
flattened.add_edge(lhs, rhs);
}
}
(Err(lhs_key), Err(rhs_key)) => {
// Edge between two key nodes, expand to all combinations of their value nodes
let Some(lhs_group) = self.get(&lhs_key) else {
continue;
};
let Some(rhs_group) = self.get(&rhs_key) else {
continue;
};
flattened.reserve_edges(lhs_group.len() * rhs_group.len());
for &lhs in lhs_group {
for &rhs in rhs_group {
flattened.add_edge(lhs, rhs);
}
}
}
}
}
flattened
}
}
impl<K, V, S> Deref for DagGroups<K, V, S> {
type Target = HashMap<K, IndexSet<V, S>, S>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<K, V, S> DerefMut for DagGroups<K, V, S> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<K, V, S> Default for DagGroups<K, V, S>
where
S: BuildHasher + Default,
{
fn default() -> Self {
Self(Default::default())
}
}
impl<K: Debug, V: Debug, S> Debug for DagGroups<K, V, S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("DagGroups").field(&self.0).finish()
}
}
/// Error indicating that the graph has redundant edges.
#[derive(Error, Debug)]
#[error("DAG has redundant edges: {0:?}")]
pub struct DagRedundancyError<N: GraphNodeId>(pub Vec<(N, N)>);
/// Error indicating that two graphs both have a dependency between the same nodes.
#[derive(Error, Debug)]
#[error("DAG has a cross-dependency between nodes {0:?} and {1:?}")]
pub struct DagCrossDependencyError<N>(pub N, pub N);
/// Error indicating that the graph has overlapping groups between two keys.
#[derive(Error, Debug)]
#[error("DAG has overlapping groups between keys {0:?} and {1:?}")]
pub struct DagOverlappingGroupError<K>(pub K, pub K);
#[cfg(test)]
mod tests {
use core::ops::DerefMut;
use crate::schedule::graph::{index, Dag, Direction, GraphNodeId, UnGraph};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct TestNode(u32);
impl GraphNodeId for TestNode {
type Adjacent = (TestNode, Direction);
type Edge = (TestNode, TestNode);
fn kind(&self) -> &'static str {
"test node"
}
}
#[test]
fn mark_dirty() {
{
let mut dag = Dag::<TestNode>::new();
dag.add_node(TestNode(1));
assert!(dag.is_dirty());
}
{
let mut dag = Dag::<TestNode>::new();
dag.add_edge(TestNode(1), TestNode(2));
assert!(dag.is_dirty());
}
{
let mut dag = Dag::<TestNode>::new();
dag.deref_mut();
assert!(dag.is_dirty());
}
{
let mut dag = Dag::<TestNode>::new();
let _ = dag.graph_mut();
assert!(dag.is_dirty());
}
}
#[test]
fn toposort() {
let mut dag = Dag::<TestNode>::new();
dag.add_edge(TestNode(1), TestNode(2));
dag.add_edge(TestNode(2), TestNode(3));
dag.add_edge(TestNode(1), TestNode(3));
assert_eq!(
dag.toposort().unwrap(),
&[TestNode(1), TestNode(2), TestNode(3)]
);
assert_eq!(
dag.get_toposort().unwrap(),
&[TestNode(1), TestNode(2), TestNode(3)]
);
}
#[test]
fn analyze() {
let mut dag1 = Dag::<TestNode>::new();
dag1.add_edge(TestNode(1), TestNode(2));
dag1.add_edge(TestNode(2), TestNode(3));
dag1.add_edge(TestNode(1), TestNode(3)); // redundant edge
let analysis1 = dag1.analyze().unwrap();
assert!(analysis1.reachable().contains(index(0, 1, 3)));
assert!(analysis1.reachable().contains(index(1, 2, 3)));
assert!(analysis1.reachable().contains(index(0, 2, 3)));
assert!(analysis1.connected().contains(&(TestNode(1), TestNode(2))));
assert!(analysis1.connected().contains(&(TestNode(2), TestNode(3))));
assert!(analysis1.connected().contains(&(TestNode(1), TestNode(3))));
assert!(!analysis1
.disconnected()
.contains(&(TestNode(2), TestNode(1))));
assert!(!analysis1
.disconnected()
.contains(&(TestNode(3), TestNode(2))));
assert!(!analysis1
.disconnected()
.contains(&(TestNode(3), TestNode(1))));
assert!(analysis1
.transitive_edges()
.contains(&(TestNode(1), TestNode(3))));
assert!(analysis1.check_for_redundant_edges().is_err());
let mut dag2 = Dag::<TestNode>::new();
dag2.add_edge(TestNode(3), TestNode(4));
let analysis2 = dag2.analyze().unwrap();
assert!(analysis2.check_for_redundant_edges().is_ok());
assert!(analysis1.check_for_cross_dependencies(&analysis2).is_ok());
let mut dag3 = Dag::<TestNode>::new();
dag3.add_edge(TestNode(1), TestNode(2));
let analysis3 = dag3.analyze().unwrap();
assert!(analysis1.check_for_cross_dependencies(&analysis3).is_err());
dag1.remove_redundant_edges(&analysis1);
let analysis1 = dag1.analyze().unwrap();
assert!(analysis1.check_for_redundant_edges().is_ok());
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Node {
Key(Key),
Value(Value),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Key(u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Value(u32);
impl GraphNodeId for Node {
type Adjacent = (Node, Direction);
type Edge = (Node, Node);
fn kind(&self) -> &'static str {
"node"
}
}
impl TryInto<Key> for Node {
type Error = Value;
fn try_into(self) -> Result<Key, Value> {
match self {
Node::Key(k) => Ok(k),
Node::Value(v) => Err(v),
}
}
}
impl TryInto<Value> for Node {
type Error = Key;
fn try_into(self) -> Result<Value, Key> {
match self {
Node::Value(v) => Ok(v),
Node::Key(k) => Err(k),
}
}
}
impl GraphNodeId for Key {
type Adjacent = (Key, Direction);
type Edge = (Key, Key);
fn kind(&self) -> &'static str {
"key"
}
}
impl GraphNodeId for Value {
type Adjacent = (Value, Direction);
type Edge = (Value, Value);
fn kind(&self) -> &'static str {
"value"
}
}
impl From<Key> for Node {
fn from(key: Key) -> Self {
Node::Key(key)
}
}
impl From<Value> for Node {
fn from(value: Value) -> Self {
Node::Value(value)
}
}
#[test]
fn group_by_key() {
let mut dag = Dag::<Node>::new();
dag.add_edge(Node::Key(Key(1)), Node::Value(Value(10)));
dag.add_edge(Node::Key(Key(1)), Node::Value(Value(11)));
dag.add_edge(Node::Key(Key(2)), Node::Value(Value(20)));
dag.add_edge(Node::Key(Key(2)), Node::Key(Key(1)));
dag.add_edge(Node::Value(Value(10)), Node::Value(Value(11)));
let groups = dag.group_by_key::<Key, Value>(2).unwrap();
assert_eq!(groups.len(), 2);
let group_key1 = groups.get(&Key(1)).unwrap();
assert!(group_key1.contains(&Value(10)));
assert!(group_key1.contains(&Value(11)));
let group_key2 = groups.get(&Key(2)).unwrap();
assert!(group_key2.contains(&Value(10)));
assert!(group_key2.contains(&Value(11)));
assert!(group_key2.contains(&Value(20)));
}
#[test]
fn flatten() {
let mut dag = Dag::<Node>::new();
dag.add_edge(Node::Key(Key(1)), Node::Value(Value(10)));
dag.add_edge(Node::Key(Key(1)), Node::Value(Value(11)));
dag.add_edge(Node::Key(Key(2)), Node::Value(Value(20)));
dag.add_edge(Node::Key(Key(2)), Node::Value(Value(21)));
dag.add_edge(Node::Value(Value(30)), Node::Key(Key(1)));
dag.add_edge(Node::Key(Key(1)), Node::Value(Value(40)));
let groups = dag.group_by_key::<Key, Value>(2).unwrap();
let flattened = groups.flatten(dag, |_key, _values, _dag, _temp| {});
assert!(flattened.contains_node(Value(10)));
assert!(flattened.contains_node(Value(11)));
assert!(flattened.contains_node(Value(20)));
assert!(flattened.contains_node(Value(21)));
assert!(flattened.contains_node(Value(30)));
assert!(flattened.contains_node(Value(40)));
assert!(flattened.contains_edge(Value(30), Value(10)));
assert!(flattened.contains_edge(Value(30), Value(11)));
assert!(flattened.contains_edge(Value(10), Value(40)));
assert!(flattened.contains_edge(Value(11), Value(40)));
}
#[test]
fn flatten_undirected() {
let mut dag = Dag::<Node>::new();
dag.add_edge(Node::Key(Key(1)), Node::Value(Value(10)));
dag.add_edge(Node::Key(Key(1)), Node::Value(Value(11)));
dag.add_edge(Node::Key(Key(2)), Node::Value(Value(20)));
dag.add_edge(Node::Key(Key(2)), Node::Value(Value(21)));
let groups = dag.group_by_key::<Key, Value>(2).unwrap();
| 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/schedule/graph/tarjan_scc.rs | crates/bevy_ecs/src/schedule/graph/tarjan_scc.rs | use alloc::vec::Vec;
use core::{hash::BuildHasher, num::NonZeroUsize};
use smallvec::SmallVec;
use crate::schedule::graph::{DiGraph, GraphNodeId};
/// Create an iterator over *strongly connected components* using Algorithm 3 in
/// [A Space-Efficient Algorithm for Finding Strongly Connected Components][1] by David J. Pierce,
/// which is a memory-efficient variation of [Tarjan's algorithm][2].
///
///
/// [1]: https://homepages.ecs.vuw.ac.nz/~djp/files/P05.pdf
/// [2]: https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
///
/// Returns each strongly connected component (scc).
/// The order of node ids within each scc is arbitrary, but the order of
/// the sccs is their postorder (reverse topological sort).
pub(crate) fn new_tarjan_scc<N: GraphNodeId, S: BuildHasher>(
graph: &DiGraph<N, S>,
) -> impl Iterator<Item = SmallVec<[N; 4]>> + '_ {
// Create a list of all nodes we need to visit.
let unchecked_nodes = graph.nodes();
// For each node we need to visit, we also need to visit its neighbors.
// Storing the iterator for each set of neighbors allows this list to be computed without
// an additional allocation.
let nodes = graph
.nodes()
.map(|node| NodeData {
root_index: None,
neighbors: graph.neighbors(node),
})
.collect::<Vec<_>>();
TarjanScc {
graph,
unchecked_nodes,
index: 1, // Invariant: index < component_count at all times.
component_count: usize::MAX, // Will hold if component_count is initialized to number of nodes - 1 or higher.
nodes,
stack: Vec::new(),
visitation_stack: Vec::new(),
start: None,
index_adjustment: None,
}
}
struct NodeData<Neighbors: Iterator<Item: GraphNodeId>> {
root_index: Option<NonZeroUsize>,
neighbors: Neighbors,
}
/// A state for computing the *strongly connected components* using [Tarjan's algorithm][1].
///
/// This is based on [`TarjanScc`] from [`petgraph`].
///
/// [1]: https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
/// [`petgraph`]: https://docs.rs/petgraph/0.6.5/petgraph/
/// [`TarjanScc`]: https://docs.rs/petgraph/0.6.5/petgraph/algo/struct.TarjanScc.html
struct TarjanScc<'graph, N, Hasher, AllNodes, Neighbors>
where
N: GraphNodeId,
Hasher: BuildHasher,
AllNodes: Iterator<Item = N>,
Neighbors: Iterator<Item = N>,
{
/// Source of truth [`DiGraph`]
graph: &'graph DiGraph<N, Hasher>,
/// An [`Iterator`] of [`GraphNodeId`]s from the `graph` which may not have been visited yet.
unchecked_nodes: AllNodes,
/// The index of the next SCC
index: usize,
/// A count of potentially remaining SCCs
component_count: usize,
/// Information about each [`GraphNodeId`], including a possible SCC index and an
/// [`Iterator`] of possibly unvisited neighbors.
nodes: Vec<NodeData<Neighbors>>,
/// A stack of [`GraphNodeId`]s where a SCC will be found starting at the top of the stack.
stack: Vec<N>,
/// A stack of [`GraphNodeId`]s which need to be visited to determine which SCC they belong to.
visitation_stack: Vec<(N, bool)>,
/// An index into the `stack` indicating the starting point of a SCC.
start: Option<usize>,
/// An adjustment to the `index` which will be applied once the current SCC is found.
index_adjustment: Option<usize>,
}
impl<
'graph,
N: GraphNodeId,
S: BuildHasher,
A: Iterator<Item = N>,
Neighbors: Iterator<Item = N>,
> TarjanScc<'graph, N, S, A, Neighbors>
{
/// Compute the next *strongly connected component* using Algorithm 3 in
/// [A Space-Efficient Algorithm for Finding Strongly Connected Components][1] by David J. Pierce,
/// which is a memory-efficient variation of [Tarjan's algorithm][2].
///
///
/// [1]: https://homepages.ecs.vuw.ac.nz/~djp/files/P05.pdf
/// [2]: https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
///
/// Returns `Some` for each strongly connected component (scc).
/// The order of node ids within each scc is arbitrary, but the order of
/// the sccs is their postorder (reverse topological sort).
fn next_scc(&mut self) -> Option<&[N]> {
// Cleanup from possible previous iteration
if let (Some(start), Some(index_adjustment)) =
(self.start.take(), self.index_adjustment.take())
{
self.stack.truncate(start);
self.index -= index_adjustment; // Backtrack index back to where it was before we ever encountered the component.
self.component_count -= 1;
}
loop {
// If there are items on the visitation stack, then we haven't finished visiting
// the node at the bottom of the stack yet.
// Must visit all nodes in the stack from top to bottom before visiting the next node.
while let Some((v, v_is_local_root)) = self.visitation_stack.pop() {
// If this visitation finds a complete SCC, return it immediately.
if let Some(start) = self.visit_once(v, v_is_local_root) {
return Some(&self.stack[start..]);
};
}
// Get the next node to check, otherwise we're done and can return None.
let Some(node) = self.unchecked_nodes.next() else {
break None;
};
let visited = self.nodes[self.graph.to_index(node)].root_index.is_some();
// If this node hasn't already been visited (e.g., it was the neighbor of a previously checked node)
// add it to the visitation stack.
if !visited {
self.visitation_stack.push((node, true));
}
}
}
/// Attempt to find the starting point on the stack for a new SCC without visiting neighbors.
/// If a visitation is required, this will return `None` and mark the required neighbor and the
/// current node as in need of visitation again.
/// If no SCC can be found in the current visitation stack, returns `None`.
fn visit_once(&mut self, v: N, mut v_is_local_root: bool) -> Option<usize> {
let node_v = &mut self.nodes[self.graph.to_index(v)];
if node_v.root_index.is_none() {
let v_index = self.index;
node_v.root_index = NonZeroUsize::new(v_index);
self.index += 1;
}
while let Some(w) = self.nodes[self.graph.to_index(v)].neighbors.next() {
// If a neighbor hasn't been visited yet...
if self.nodes[self.graph.to_index(w)].root_index.is_none() {
// Push the current node and the neighbor back onto the visitation stack.
// On the next execution of `visit_once`, the neighbor will be visited.
self.visitation_stack.push((v, v_is_local_root));
self.visitation_stack.push((w, true));
return None;
}
if self.nodes[self.graph.to_index(w)].root_index
< self.nodes[self.graph.to_index(v)].root_index
{
self.nodes[self.graph.to_index(v)].root_index =
self.nodes[self.graph.to_index(w)].root_index;
v_is_local_root = false;
}
}
if !v_is_local_root {
self.stack.push(v); // Stack is filled up when backtracking, unlike in Tarjans original algorithm.
return None;
}
// Pop the stack and generate an SCC.
let mut index_adjustment = 1;
let c = NonZeroUsize::new(self.component_count);
let nodes = &mut self.nodes;
let start = self
.stack
.iter()
.rposition(|&w| {
if nodes[self.graph.to_index(v)].root_index
> nodes[self.graph.to_index(w)].root_index
{
true
} else {
nodes[self.graph.to_index(w)].root_index = c;
index_adjustment += 1;
false
}
})
.map(|x| x + 1)
.unwrap_or_default();
nodes[self.graph.to_index(v)].root_index = c;
self.stack.push(v); // Pushing the component root to the back right before getting rid of it is somewhat ugly, but it lets it be included in f.
self.start = Some(start);
self.index_adjustment = Some(index_adjustment);
Some(start)
}
}
impl<
'graph,
N: GraphNodeId,
S: BuildHasher,
A: Iterator<Item = N>,
Neighbors: Iterator<Item = N>,
> Iterator for TarjanScc<'graph, N, S, A, Neighbors>
{
// It is expected that the `DiGraph` is sparse, and as such wont have many large SCCs.
// Returning a `SmallVec` allows this iterator to skip allocation in cases where that
// assumption holds.
type Item = SmallVec<[N; 4]>;
fn next(&mut self) -> Option<Self::Item> {
let next = SmallVec::from_slice(self.next_scc()?);
Some(next)
}
fn size_hint(&self) -> (usize, Option<usize>) {
// There can be no more than the number of nodes in a graph worth of SCCs
(0, Some(self.nodes.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/schedule/graph/mod.rs | crates/bevy_ecs/src/schedule/graph/mod.rs | use alloc::{boxed::Box, vec::Vec};
use core::{
any::{Any, TypeId},
fmt::Debug,
};
use bevy_utils::TypeIdMap;
use crate::schedule::InternedSystemSet;
mod dag;
mod graph_map;
mod tarjan_scc;
pub use dag::*;
pub use graph_map::{DiGraph, DiGraphToposortError, Direction, GraphNodeId, UnGraph};
/// Specifies what kind of edge should be added to the dependency graph.
#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash)]
pub(crate) enum DependencyKind {
/// A node that should be preceded.
Before,
/// A node that should be succeeded.
After,
}
/// An edge to be added to the dependency graph.
pub(crate) struct Dependency {
pub(crate) kind: DependencyKind,
pub(crate) set: InternedSystemSet,
pub(crate) options: TypeIdMap<Box<dyn Any>>,
}
impl Dependency {
pub fn new(kind: DependencyKind, set: InternedSystemSet) -> Self {
Self {
kind,
set,
options: Default::default(),
}
}
pub fn add_config<T: 'static>(mut self, option: T) -> Self {
self.options.insert(TypeId::of::<T>(), Box::new(option));
self
}
}
/// Configures ambiguity detection for a single system.
#[derive(Clone, Debug, Default)]
pub(crate) enum Ambiguity {
#[default]
Check,
/// Ignore warnings with systems in any of these system sets. May contain duplicates.
IgnoreWithSet(Vec<InternedSystemSet>),
/// Ignore all warnings.
IgnoreAll,
}
/// Metadata about how the node fits in the schedule graph
#[derive(Default)]
pub struct GraphInfo {
/// the sets that the node belongs to (hierarchy)
pub(crate) hierarchy: Vec<InternedSystemSet>,
/// the sets that the node depends on (must run before or after)
pub(crate) dependencies: Vec<Dependency>,
pub(crate) ambiguous_with: Ambiguity,
}
/// Converts 2D row-major pair of indices into a 1D array index.
pub(crate) fn index(row: usize, col: usize, num_cols: usize) -> usize {
debug_assert!(col < num_cols);
(row * num_cols) + col
}
/// Converts a 1D array index into a 2D row-major pair of indices.
pub(crate) fn row_col(index: usize, num_cols: usize) -> (usize, usize) {
(index / num_cols, index % num_cols)
}
| 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/schedule/executor/multi_threaded.rs | crates/bevy_ecs/src/schedule/executor/multi_threaded.rs | use alloc::{boxed::Box, vec::Vec};
use bevy_platform::cell::SyncUnsafeCell;
use bevy_platform::sync::Arc;
use bevy_tasks::{ComputeTaskPool, Scope, TaskPool, ThreadExecutor};
use concurrent_queue::ConcurrentQueue;
use core::{any::Any, panic::AssertUnwindSafe};
use fixedbitset::FixedBitSet;
#[cfg(feature = "std")]
use std::eprintln;
use std::sync::{Mutex, MutexGuard};
#[cfg(feature = "trace")]
use tracing::{info_span, Span};
use crate::{
error::{ErrorContext, ErrorHandler, Result},
prelude::Resource,
schedule::{
is_apply_deferred, ConditionWithAccess, ExecutorKind, SystemExecutor, SystemSchedule,
SystemWithAccess,
},
system::{RunSystemError, ScheduleSystem},
world::{unsafe_world_cell::UnsafeWorldCell, World},
};
#[cfg(feature = "hotpatching")]
use crate::{prelude::DetectChanges, HotPatchChanges};
use super::__rust_begin_short_backtrace;
/// Borrowed data used by the [`MultiThreadedExecutor`].
struct Environment<'env, 'sys> {
executor: &'env MultiThreadedExecutor,
systems: &'sys [SyncUnsafeCell<SystemWithAccess>],
conditions: SyncUnsafeCell<Conditions<'sys>>,
world_cell: UnsafeWorldCell<'env>,
}
struct Conditions<'a> {
system_conditions: &'a mut [Vec<ConditionWithAccess>],
set_conditions: &'a mut [Vec<ConditionWithAccess>],
sets_with_conditions_of_systems: &'a [FixedBitSet],
systems_in_sets_with_conditions: &'a [FixedBitSet],
}
impl<'env, 'sys> Environment<'env, 'sys> {
fn new(
executor: &'env MultiThreadedExecutor,
schedule: &'sys mut SystemSchedule,
world: &'env mut World,
) -> Self {
Environment {
executor,
systems: SyncUnsafeCell::from_mut(schedule.systems.as_mut_slice()).as_slice_of_cells(),
conditions: SyncUnsafeCell::new(Conditions {
system_conditions: &mut schedule.system_conditions,
set_conditions: &mut schedule.set_conditions,
sets_with_conditions_of_systems: &schedule.sets_with_conditions_of_systems,
systems_in_sets_with_conditions: &schedule.systems_in_sets_with_conditions,
}),
world_cell: world.as_unsafe_world_cell(),
}
}
}
/// Per-system data used by the [`MultiThreadedExecutor`].
// Copied here because it can't be read from the system when it's running.
struct SystemTaskMetadata {
/// The set of systems whose `component_access_set()` conflicts with this one.
conflicting_systems: FixedBitSet,
/// The set of systems whose `component_access_set()` conflicts with this system's conditions.
/// Note that this is separate from `conflicting_systems` to handle the case where
/// a system is skipped by an earlier system set condition or system stepping,
/// and needs access to run its conditions but not for itself.
condition_conflicting_systems: FixedBitSet,
/// Indices of the systems that directly depend on the system.
dependents: Vec<usize>,
/// Is `true` if the system does not access `!Send` data.
is_send: bool,
/// Is `true` if the system is exclusive.
is_exclusive: bool,
}
/// The result of running a system that is sent across a channel.
struct SystemResult {
system_index: usize,
}
/// Runs the schedule using a thread pool. Non-conflicting systems can run in parallel.
pub struct MultiThreadedExecutor {
/// The running state, protected by a mutex so that a reference to the executor can be shared across tasks.
state: Mutex<ExecutorState>,
/// Queue of system completion events.
system_completion: ConcurrentQueue<SystemResult>,
/// Setting when true applies deferred system buffers after all systems have run
apply_final_deferred: bool,
/// When set, tells the executor that a thread has panicked.
panic_payload: Mutex<Option<Box<dyn Any + Send>>>,
starting_systems: FixedBitSet,
/// Cached tracing span
#[cfg(feature = "trace")]
executor_span: Span,
}
/// The state of the executor while running.
pub struct ExecutorState {
/// Metadata for scheduling and running system tasks.
system_task_metadata: Vec<SystemTaskMetadata>,
/// The set of systems whose `component_access_set()` conflicts with this system set's conditions.
set_condition_conflicting_systems: Vec<FixedBitSet>,
/// Returns `true` if a system with non-`Send` access is running.
local_thread_running: bool,
/// Returns `true` if an exclusive system is running.
exclusive_running: bool,
/// The number of systems that are running.
num_running_systems: usize,
/// The number of dependencies each system has that have not completed.
num_dependencies_remaining: Vec<usize>,
/// System sets whose conditions have been evaluated.
evaluated_sets: FixedBitSet,
/// Systems that have no remaining dependencies and are waiting to run.
ready_systems: FixedBitSet,
/// copy of `ready_systems`
ready_systems_copy: FixedBitSet,
/// Systems that are running.
running_systems: FixedBitSet,
/// Systems that got skipped.
skipped_systems: FixedBitSet,
/// Systems whose conditions have been evaluated and were run or skipped.
completed_systems: FixedBitSet,
/// Systems that have run but have not had their buffers applied.
unapplied_systems: FixedBitSet,
}
/// References to data required by the executor.
/// This is copied to each system task so that can invoke the executor when they complete.
// These all need to outlive 'scope in order to be sent to new tasks,
// and keeping them all in a struct means we can use lifetime elision.
#[derive(Copy, Clone)]
struct Context<'scope, 'env, 'sys> {
environment: &'env Environment<'env, 'sys>,
scope: &'scope Scope<'scope, 'env, ()>,
error_handler: ErrorHandler,
}
impl Default for MultiThreadedExecutor {
fn default() -> Self {
Self::new()
}
}
impl SystemExecutor for MultiThreadedExecutor {
fn kind(&self) -> ExecutorKind {
ExecutorKind::MultiThreaded
}
fn init(&mut self, schedule: &SystemSchedule) {
let state = self.state.get_mut().unwrap();
// pre-allocate space
let sys_count = schedule.system_ids.len();
let set_count = schedule.set_ids.len();
self.system_completion = ConcurrentQueue::bounded(sys_count.max(1));
self.starting_systems = FixedBitSet::with_capacity(sys_count);
state.evaluated_sets = FixedBitSet::with_capacity(set_count);
state.ready_systems = FixedBitSet::with_capacity(sys_count);
state.ready_systems_copy = FixedBitSet::with_capacity(sys_count);
state.running_systems = FixedBitSet::with_capacity(sys_count);
state.completed_systems = FixedBitSet::with_capacity(sys_count);
state.skipped_systems = FixedBitSet::with_capacity(sys_count);
state.unapplied_systems = FixedBitSet::with_capacity(sys_count);
state.system_task_metadata = Vec::with_capacity(sys_count);
for index in 0..sys_count {
state.system_task_metadata.push(SystemTaskMetadata {
conflicting_systems: FixedBitSet::with_capacity(sys_count),
condition_conflicting_systems: FixedBitSet::with_capacity(sys_count),
dependents: schedule.system_dependents[index].clone(),
is_send: schedule.systems[index].system.is_send(),
is_exclusive: schedule.systems[index].system.is_exclusive(),
});
if schedule.system_dependencies[index] == 0 {
self.starting_systems.insert(index);
}
}
{
#[cfg(feature = "trace")]
let _span = info_span!("calculate conflicting systems").entered();
for index1 in 0..sys_count {
let system1 = &schedule.systems[index1];
for index2 in 0..index1 {
let system2 = &schedule.systems[index2];
if !system2.access.is_compatible(&system1.access) {
state.system_task_metadata[index1]
.conflicting_systems
.insert(index2);
state.system_task_metadata[index2]
.conflicting_systems
.insert(index1);
}
}
for index2 in 0..sys_count {
let system2 = &schedule.systems[index2];
if schedule.system_conditions[index1]
.iter()
.any(|condition| !system2.access.is_compatible(&condition.access))
{
state.system_task_metadata[index1]
.condition_conflicting_systems
.insert(index2);
}
}
}
state.set_condition_conflicting_systems.clear();
state.set_condition_conflicting_systems.reserve(set_count);
for set_idx in 0..set_count {
let mut conflicting_systems = FixedBitSet::with_capacity(sys_count);
for sys_index in 0..sys_count {
let system = &schedule.systems[sys_index];
if schedule.set_conditions[set_idx]
.iter()
.any(|condition| !system.access.is_compatible(&condition.access))
{
conflicting_systems.insert(sys_index);
}
}
state
.set_condition_conflicting_systems
.push(conflicting_systems);
}
}
state.num_dependencies_remaining = Vec::with_capacity(sys_count);
}
fn run(
&mut self,
schedule: &mut SystemSchedule,
world: &mut World,
_skip_systems: Option<&FixedBitSet>,
error_handler: ErrorHandler,
) {
let state = self.state.get_mut().unwrap();
// reset counts
if schedule.systems.is_empty() {
return;
}
state.num_running_systems = 0;
state
.num_dependencies_remaining
.clone_from(&schedule.system_dependencies);
state.ready_systems.clone_from(&self.starting_systems);
// If stepping is enabled, make sure we skip those systems that should
// not be run.
#[cfg(feature = "bevy_debug_stepping")]
if let Some(skipped_systems) = _skip_systems {
debug_assert_eq!(skipped_systems.len(), state.completed_systems.len());
// mark skipped systems as completed
state.completed_systems |= skipped_systems;
// signal the dependencies for each of the skipped systems, as
// though they had run
for system_index in skipped_systems.ones() {
state.signal_dependents(system_index);
state.ready_systems.remove(system_index);
}
}
let thread_executor = world
.get_resource::<MainThreadExecutor>()
.map(|e| e.0.clone());
let thread_executor = thread_executor.as_deref();
let environment = &Environment::new(self, schedule, world);
ComputeTaskPool::get_or_init(TaskPool::default).scope_with_executor(
false,
thread_executor,
|scope| {
let context = Context {
environment,
scope,
error_handler,
};
// The first tick won't need to process finished systems, but we still need to run the loop in
// tick_executor() in case a system completes while the first tick still holds the mutex.
context.tick_executor();
},
);
// End the borrows of self and world in environment by copying out the reference to systems.
let systems = environment.systems;
let state = self.state.get_mut().unwrap();
if self.apply_final_deferred {
// Do one final apply buffers after all systems have completed
// Commands should be applied while on the scope's thread, not the executor's thread
let res = apply_deferred(&state.unapplied_systems, systems, world);
if let Err(payload) = res {
let panic_payload = self.panic_payload.get_mut().unwrap();
*panic_payload = Some(payload);
}
state.unapplied_systems.clear();
}
// check to see if there was a panic
let payload = self.panic_payload.get_mut().unwrap();
if let Some(payload) = payload.take() {
std::panic::resume_unwind(payload);
}
debug_assert!(state.ready_systems.is_clear());
debug_assert!(state.running_systems.is_clear());
state.evaluated_sets.clear();
state.skipped_systems.clear();
state.completed_systems.clear();
}
fn set_apply_final_deferred(&mut self, value: bool) {
self.apply_final_deferred = value;
}
}
impl<'scope, 'env: 'scope, 'sys> Context<'scope, 'env, 'sys> {
fn system_completed(
&self,
system_index: usize,
res: Result<(), Box<dyn Any + Send>>,
system: &ScheduleSystem,
) {
// tell the executor that the system finished
self.environment
.executor
.system_completion
.push(SystemResult { system_index })
.unwrap_or_else(|error| unreachable!("{}", error));
if let Err(payload) = res {
#[cfg(feature = "std")]
#[expect(clippy::print_stderr, reason = "Allowed behind `std` feature gate.")]
{
eprintln!("Encountered a panic in system `{}`!", system.name());
}
// set the payload to propagate the error
{
let mut panic_payload = self.environment.executor.panic_payload.lock().unwrap();
*panic_payload = Some(payload);
}
}
self.tick_executor();
}
#[expect(
clippy::mut_from_ref,
reason = "Field is only accessed here and is guarded by lock with a documented safety comment"
)]
fn try_lock<'a>(&'a self) -> Option<(&'a mut Conditions<'sys>, MutexGuard<'a, ExecutorState>)> {
let guard = self.environment.executor.state.try_lock().ok()?;
// SAFETY: This is an exclusive access as no other location fetches conditions mutably, and
// is synchronized by the lock on the executor state.
let conditions = unsafe { &mut *self.environment.conditions.get() };
Some((conditions, guard))
}
fn tick_executor(&self) {
// Ensure that the executor handles any events pushed to the system_completion queue by this thread.
// If this thread acquires the lock, the executor runs after the push() and they are processed.
// If this thread does not acquire the lock, then the is_empty() check on the other thread runs
// after the lock is released, which is after try_lock() failed, which is after the push()
// on this thread, so the is_empty() check will see the new events and loop.
loop {
let Some((conditions, mut guard)) = self.try_lock() else {
return;
};
guard.tick(self, conditions);
// Make sure we drop the guard before checking system_completion.is_empty(), or we could lose events.
drop(guard);
if self.environment.executor.system_completion.is_empty() {
return;
}
}
}
}
impl MultiThreadedExecutor {
/// Creates a new `multi_threaded` executor for use with a [`Schedule`].
///
/// [`Schedule`]: crate::schedule::Schedule
pub fn new() -> Self {
Self {
state: Mutex::new(ExecutorState::new()),
system_completion: ConcurrentQueue::unbounded(),
starting_systems: FixedBitSet::new(),
apply_final_deferred: true,
panic_payload: Mutex::new(None),
#[cfg(feature = "trace")]
executor_span: info_span!("multithreaded executor"),
}
}
}
impl ExecutorState {
fn new() -> Self {
Self {
system_task_metadata: Vec::new(),
set_condition_conflicting_systems: Vec::new(),
num_running_systems: 0,
num_dependencies_remaining: Vec::new(),
local_thread_running: false,
exclusive_running: false,
evaluated_sets: FixedBitSet::new(),
ready_systems: FixedBitSet::new(),
ready_systems_copy: FixedBitSet::new(),
running_systems: FixedBitSet::new(),
skipped_systems: FixedBitSet::new(),
completed_systems: FixedBitSet::new(),
unapplied_systems: FixedBitSet::new(),
}
}
fn tick(&mut self, context: &Context, conditions: &mut Conditions) {
#[cfg(feature = "trace")]
let _span = context.environment.executor.executor_span.enter();
for result in context.environment.executor.system_completion.try_iter() {
self.finish_system_and_handle_dependents(result);
}
// SAFETY:
// - `finish_system_and_handle_dependents` has updated the currently running systems.
// - `rebuild_active_access` locks access for all currently running systems.
unsafe {
self.spawn_system_tasks(context, conditions);
}
}
/// # Safety
/// - Caller must ensure that `self.ready_systems` does not contain any systems that
/// have been mutably borrowed (such as the systems currently running).
/// - `world_cell` must have permission to access all world data (not counting
/// any world data that is claimed by systems currently running on this executor).
unsafe fn spawn_system_tasks(&mut self, context: &Context, conditions: &mut Conditions) {
if self.exclusive_running {
return;
}
#[cfg(feature = "hotpatching")]
#[expect(
clippy::undocumented_unsafe_blocks,
reason = "This actually could result in UB if a system tries to mutate
`HotPatchChanges`. We allow this as the resource only exists with the `hotpatching` feature.
and `hotpatching` should never be enabled in release."
)]
#[cfg(feature = "hotpatching")]
let hotpatch_tick = unsafe {
context
.environment
.world_cell
.get_resource_ref::<HotPatchChanges>()
}
.map(|r| r.last_changed())
.unwrap_or_default();
// can't borrow since loop mutably borrows `self`
let mut ready_systems = core::mem::take(&mut self.ready_systems_copy);
// Skipping systems may cause their dependents to become ready immediately.
// If that happens, we need to run again immediately or we may fail to spawn those dependents.
let mut check_for_new_ready_systems = true;
while check_for_new_ready_systems {
check_for_new_ready_systems = false;
ready_systems.clone_from(&self.ready_systems);
for system_index in ready_systems.ones() {
debug_assert!(!self.running_systems.contains(system_index));
// SAFETY: Caller assured that these systems are not running.
// Therefore, no other reference to this system exists and there is no aliasing.
let system =
&mut unsafe { &mut *context.environment.systems[system_index].get() }.system;
#[cfg(feature = "hotpatching")]
if hotpatch_tick.is_newer_than(
system.get_last_run(),
context.environment.world_cell.change_tick(),
) {
system.refresh_hotpatch();
}
if !self.can_run(system_index, conditions) {
// NOTE: exclusive systems with ambiguities are susceptible to
// being significantly displaced here (compared to single-threaded order)
// if systems after them in topological order can run
// if that becomes an issue, `break;` if exclusive system
continue;
}
self.ready_systems.remove(system_index);
// SAFETY: `can_run` returned true, which means that:
// - There can be no systems running whose accesses would conflict with any conditions.
if unsafe {
!self.should_run(
system_index,
system,
conditions,
context.environment.world_cell,
context.error_handler,
)
} {
self.skip_system_and_signal_dependents(system_index);
// signal_dependents may have set more systems to ready.
check_for_new_ready_systems = true;
continue;
}
self.running_systems.insert(system_index);
self.num_running_systems += 1;
if self.system_task_metadata[system_index].is_exclusive {
// SAFETY: `can_run` returned true for this system,
// which means no systems are currently borrowed.
unsafe {
self.spawn_exclusive_system_task(context, system_index);
}
check_for_new_ready_systems = false;
break;
}
// SAFETY:
// - Caller ensured no other reference to this system exists.
// - `system_task_metadata[system_index].is_exclusive` is `false`,
// so `System::is_exclusive` returned `false` when we called it.
// - `can_run` returned true, so no systems with conflicting world access are running.
unsafe {
self.spawn_system_task(context, system_index);
}
}
}
// give back
self.ready_systems_copy = ready_systems;
}
fn can_run(&mut self, system_index: usize, conditions: &mut Conditions) -> bool {
let system_meta = &self.system_task_metadata[system_index];
if system_meta.is_exclusive && self.num_running_systems > 0 {
return false;
}
if !system_meta.is_send && self.local_thread_running {
return false;
}
// TODO: an earlier out if world's archetypes did not change
for set_idx in conditions.sets_with_conditions_of_systems[system_index]
.difference(&self.evaluated_sets)
{
if !self.set_condition_conflicting_systems[set_idx].is_disjoint(&self.running_systems) {
return false;
}
}
if !system_meta
.condition_conflicting_systems
.is_disjoint(&self.running_systems)
{
return false;
}
if !self.skipped_systems.contains(system_index)
&& !system_meta
.conflicting_systems
.is_disjoint(&self.running_systems)
{
return false;
}
true
}
/// # Safety
/// * `world` must have permission to read any world data required by
/// the system's conditions: this includes conditions for the system
/// itself, and conditions for any of the system's sets.
unsafe fn should_run(
&mut self,
system_index: usize,
system: &mut ScheduleSystem,
conditions: &mut Conditions,
world: UnsafeWorldCell,
error_handler: ErrorHandler,
) -> bool {
let mut should_run = !self.skipped_systems.contains(system_index);
for set_idx in conditions.sets_with_conditions_of_systems[system_index].ones() {
if self.evaluated_sets.contains(set_idx) {
continue;
}
// Evaluate the system set's conditions.
// SAFETY:
// - The caller ensures that `world` has permission to read any data
// required by the conditions.
let set_conditions_met = unsafe {
evaluate_and_fold_conditions(
&mut conditions.set_conditions[set_idx],
world,
error_handler,
system,
true,
)
};
if !set_conditions_met {
self.skipped_systems
.union_with(&conditions.systems_in_sets_with_conditions[set_idx]);
}
should_run &= set_conditions_met;
self.evaluated_sets.insert(set_idx);
}
// Evaluate the system's conditions.
// SAFETY:
// - The caller ensures that `world` has permission to read any data
// required by the conditions.
let system_conditions_met = unsafe {
evaluate_and_fold_conditions(
&mut conditions.system_conditions[system_index],
world,
error_handler,
system,
false,
)
};
if !system_conditions_met {
self.skipped_systems.insert(system_index);
}
should_run &= system_conditions_met;
if should_run {
// SAFETY:
// - The caller ensures that `world` has permission to read any data
// required by the system.
let valid_params = match unsafe { system.validate_param_unsafe(world) } {
Ok(()) => true,
Err(e) => {
if !e.skipped {
error_handler(
e.into(),
ErrorContext::System {
name: system.name(),
last_run: system.get_last_run(),
},
);
}
false
}
};
if !valid_params {
self.skipped_systems.insert(system_index);
}
should_run &= valid_params;
}
should_run
}
/// # Safety
/// - Caller must not alias systems that are running.
/// - `is_exclusive` must have returned `false` for the specified system.
/// - `world` must have permission to access the world data
/// used by the specified system.
unsafe fn spawn_system_task(&mut self, context: &Context, system_index: usize) {
// SAFETY: this system is not running, no other reference exists
let system = &mut unsafe { &mut *context.environment.systems[system_index].get() }.system;
// Move the full context object into the new future.
let context = *context;
let system_meta = &self.system_task_metadata[system_index];
let task = async move {
let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
// SAFETY:
// - The caller ensures that we have permission to
// access the world data used by the system.
// - `is_exclusive` returned false
unsafe {
if let Err(RunSystemError::Failed(err)) =
__rust_begin_short_backtrace::run_unsafe(
system,
context.environment.world_cell,
)
{
(context.error_handler)(
err,
ErrorContext::System {
name: system.name(),
last_run: system.get_last_run(),
},
);
}
};
}));
context.system_completed(system_index, res, system);
};
if system_meta.is_send {
context.scope.spawn(task);
} else {
self.local_thread_running = true;
context.scope.spawn_on_external(task);
}
}
/// # Safety
/// Caller must ensure no systems are currently borrowed.
unsafe fn spawn_exclusive_system_task(&mut self, context: &Context, system_index: usize) {
// SAFETY: this system is not running, no other reference exists
let system = &mut unsafe { &mut *context.environment.systems[system_index].get() }.system;
// Move the full context object into the new future.
let context = *context;
if is_apply_deferred(&**system) {
// TODO: avoid allocation
let unapplied_systems = self.unapplied_systems.clone();
self.unapplied_systems.clear();
let task = async move {
// SAFETY: `can_run` returned true for this system, which means
// that no other systems currently have access to the world.
let world = unsafe { context.environment.world_cell.world_mut() };
let res = apply_deferred(&unapplied_systems, context.environment.systems, world);
context.system_completed(system_index, res, system);
};
context.scope.spawn_on_scope(task);
} else {
let task = async move {
// SAFETY: `can_run` returned true for this system, which means
// that no other systems currently have access to the world.
let world = unsafe { context.environment.world_cell.world_mut() };
let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
if let Err(RunSystemError::Failed(err)) =
__rust_begin_short_backtrace::run(system, world)
{
(context.error_handler)(
err,
ErrorContext::System {
name: system.name(),
last_run: system.get_last_run(),
},
);
}
}));
context.system_completed(system_index, res, system);
};
context.scope.spawn_on_scope(task);
}
self.exclusive_running = true;
self.local_thread_running = true;
}
fn finish_system_and_handle_dependents(&mut self, result: SystemResult) {
let SystemResult { system_index, .. } = result;
if self.system_task_metadata[system_index].is_exclusive {
self.exclusive_running = false;
}
if !self.system_task_metadata[system_index].is_send {
self.local_thread_running = false;
}
debug_assert!(self.num_running_systems >= 1);
self.num_running_systems -= 1;
self.running_systems.remove(system_index);
self.completed_systems.insert(system_index);
self.unapplied_systems.insert(system_index);
self.signal_dependents(system_index);
}
fn skip_system_and_signal_dependents(&mut self, system_index: usize) {
self.completed_systems.insert(system_index);
self.signal_dependents(system_index);
}
fn signal_dependents(&mut self, system_index: usize) {
for &dep_idx in &self.system_task_metadata[system_index].dependents {
let remaining = &mut self.num_dependencies_remaining[dep_idx];
debug_assert!(*remaining >= 1);
*remaining -= 1;
if *remaining == 0 && !self.completed_systems.contains(dep_idx) {
self.ready_systems.insert(dep_idx);
}
}
}
}
fn apply_deferred(
unapplied_systems: &FixedBitSet,
systems: &[SyncUnsafeCell<SystemWithAccess>],
world: &mut World,
) -> Result<(), Box<dyn Any + Send>> {
for system_index in unapplied_systems.ones() {
// SAFETY: none of these systems are running, no other references exist
let system = &mut unsafe { &mut *systems[system_index].get() }.system;
let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
system.apply_deferred(world);
}));
if let Err(payload) = res {
#[cfg(feature = "std")]
#[expect(clippy::print_stderr, reason = "Allowed behind `std` feature gate.")]
{
| 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/schedule/executor/single_threaded.rs | crates/bevy_ecs/src/schedule/executor/single_threaded.rs | use core::panic::AssertUnwindSafe;
use fixedbitset::FixedBitSet;
#[cfg(feature = "trace")]
use alloc::string::ToString as _;
#[cfg(feature = "trace")]
use tracing::info_span;
#[cfg(feature = "std")]
use std::eprintln;
use crate::{
error::{ErrorContext, ErrorHandler},
schedule::{
is_apply_deferred, ConditionWithAccess, ExecutorKind, SystemExecutor, SystemSchedule,
},
system::{RunSystemError, ScheduleSystem},
world::World,
};
#[cfg(feature = "hotpatching")]
use crate::{change_detection::DetectChanges, HotPatchChanges};
use super::__rust_begin_short_backtrace;
/// Runs the schedule using a single thread.
///
/// Useful if you're dealing with a single-threaded environment, saving your threads for
/// other things, or just trying minimize overhead.
#[derive(Default)]
pub struct SingleThreadedExecutor {
/// System sets whose conditions have been evaluated.
evaluated_sets: FixedBitSet,
/// Systems that have run or been skipped.
completed_systems: FixedBitSet,
/// Systems that have run but have not had their buffers applied.
unapplied_systems: FixedBitSet,
/// Setting when true applies deferred system buffers after all systems have run
apply_final_deferred: bool,
}
impl SystemExecutor for SingleThreadedExecutor {
fn kind(&self) -> ExecutorKind {
ExecutorKind::SingleThreaded
}
fn init(&mut self, schedule: &SystemSchedule) {
// pre-allocate space
let sys_count = schedule.system_ids.len();
let set_count = schedule.set_ids.len();
self.evaluated_sets = FixedBitSet::with_capacity(set_count);
self.completed_systems = FixedBitSet::with_capacity(sys_count);
self.unapplied_systems = FixedBitSet::with_capacity(sys_count);
}
fn run(
&mut self,
schedule: &mut SystemSchedule,
world: &mut World,
_skip_systems: Option<&FixedBitSet>,
error_handler: ErrorHandler,
) {
// If stepping is enabled, make sure we skip those systems that should
// not be run.
#[cfg(feature = "bevy_debug_stepping")]
if let Some(skipped_systems) = _skip_systems {
// mark skipped systems as completed
self.completed_systems |= skipped_systems;
}
#[cfg(feature = "hotpatching")]
let hotpatch_tick = world
.get_resource_ref::<HotPatchChanges>()
.map(|r| r.last_changed())
.unwrap_or_default();
for system_index in 0..schedule.systems.len() {
let system = &mut schedule.systems[system_index].system;
#[cfg(feature = "trace")]
let name = system.name();
#[cfg(feature = "trace")]
let should_run_span = info_span!("check_conditions", name = name.to_string()).entered();
let mut should_run = !self.completed_systems.contains(system_index);
for set_idx in schedule.sets_with_conditions_of_systems[system_index].ones() {
if self.evaluated_sets.contains(set_idx) {
continue;
}
// evaluate system set's conditions
let set_conditions_met = evaluate_and_fold_conditions(
&mut schedule.set_conditions[set_idx],
world,
error_handler,
system,
true,
);
if !set_conditions_met {
self.completed_systems
.union_with(&schedule.systems_in_sets_with_conditions[set_idx]);
}
should_run &= set_conditions_met;
self.evaluated_sets.insert(set_idx);
}
// evaluate system's conditions
let system_conditions_met = evaluate_and_fold_conditions(
&mut schedule.system_conditions[system_index],
world,
error_handler,
system,
false,
);
should_run &= system_conditions_met;
#[cfg(feature = "trace")]
should_run_span.exit();
#[cfg(feature = "hotpatching")]
if hotpatch_tick.is_newer_than(system.get_last_run(), world.change_tick()) {
system.refresh_hotpatch();
}
// system has either been skipped or will run
self.completed_systems.insert(system_index);
if !should_run {
continue;
}
if is_apply_deferred(&**system) {
self.apply_deferred(schedule, world);
continue;
}
let f = AssertUnwindSafe(|| {
if let Err(RunSystemError::Failed(err)) =
__rust_begin_short_backtrace::run_without_applying_deferred(system, world)
{
error_handler(
err,
ErrorContext::System {
name: system.name(),
last_run: system.get_last_run(),
},
);
}
});
#[cfg(feature = "std")]
#[expect(clippy::print_stderr, reason = "Allowed behind `std` feature gate.")]
{
if let Err(payload) = std::panic::catch_unwind(f) {
eprintln!("Encountered a panic in system `{}`!", system.name());
std::panic::resume_unwind(payload);
}
}
#[cfg(not(feature = "std"))]
{
(f)();
}
self.unapplied_systems.insert(system_index);
}
if self.apply_final_deferred {
self.apply_deferred(schedule, world);
}
self.evaluated_sets.clear();
self.completed_systems.clear();
}
fn set_apply_final_deferred(&mut self, apply_final_deferred: bool) {
self.apply_final_deferred = apply_final_deferred;
}
}
impl SingleThreadedExecutor {
/// Creates a new single-threaded executor for use in a [`Schedule`].
///
/// [`Schedule`]: crate::schedule::Schedule
pub const fn new() -> Self {
Self {
evaluated_sets: FixedBitSet::new(),
completed_systems: FixedBitSet::new(),
unapplied_systems: FixedBitSet::new(),
apply_final_deferred: true,
}
}
fn apply_deferred(&mut self, schedule: &mut SystemSchedule, world: &mut World) {
for system_index in self.unapplied_systems.ones() {
let system = &mut schedule.systems[system_index].system;
system.apply_deferred(world);
}
self.unapplied_systems.clear();
}
}
fn evaluate_and_fold_conditions(
conditions: &mut [ConditionWithAccess],
world: &mut World,
error_handler: ErrorHandler,
for_system: &ScheduleSystem,
on_set: bool,
) -> bool {
#[cfg(feature = "hotpatching")]
let hotpatch_tick = world
.get_resource_ref::<HotPatchChanges>()
.map(|r| r.last_changed())
.unwrap_or_default();
#[expect(
clippy::unnecessary_fold,
reason = "Short-circuiting here would prevent conditions from mutating their own state as needed."
)]
conditions
.iter_mut()
.map(|ConditionWithAccess { condition, .. }| {
#[cfg(feature = "hotpatching")]
if hotpatch_tick.is_newer_than(condition.get_last_run(), world.change_tick()) {
condition.refresh_hotpatch();
}
__rust_begin_short_backtrace::readonly_run(&mut **condition, world).unwrap_or_else(
|err| {
if let RunSystemError::Failed(err) = err {
error_handler(
err,
ErrorContext::RunCondition {
name: condition.name(),
last_run: condition.get_last_run(),
system: for_system.name(),
on_set,
},
);
};
false
},
)
})
.fold(true, |acc, res| acc && res)
}
| 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/schedule/executor/mod.rs | crates/bevy_ecs/src/schedule/executor/mod.rs | #[cfg(feature = "std")]
mod multi_threaded;
mod single_threaded;
use alloc::{vec, vec::Vec};
use bevy_utils::prelude::DebugName;
use core::any::TypeId;
pub use self::single_threaded::SingleThreadedExecutor;
#[cfg(feature = "std")]
pub use self::multi_threaded::{MainThreadExecutor, MultiThreadedExecutor};
use fixedbitset::FixedBitSet;
use crate::{
change_detection::{CheckChangeTicks, Tick},
error::{BevyError, ErrorContext, Result},
prelude::{IntoSystemSet, SystemSet},
query::FilteredAccessSet,
schedule::{
ConditionWithAccess, InternedSystemSet, SystemKey, SystemSetKey, SystemTypeSet,
SystemWithAccess,
},
system::{RunSystemError, System, SystemIn, SystemParamValidationError, SystemStateFlags},
world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, World},
};
/// Types that can run a [`SystemSchedule`] on a [`World`].
pub(super) trait SystemExecutor: Send + Sync {
fn kind(&self) -> ExecutorKind;
fn init(&mut self, schedule: &SystemSchedule);
fn run(
&mut self,
schedule: &mut SystemSchedule,
world: &mut World,
skip_systems: Option<&FixedBitSet>,
error_handler: fn(BevyError, ErrorContext),
);
fn set_apply_final_deferred(&mut self, value: bool);
}
/// Specifies how a [`Schedule`](super::Schedule) will be run.
///
/// The default depends on the target platform:
/// - [`SingleThreaded`](ExecutorKind::SingleThreaded) on Wasm.
/// - [`MultiThreaded`](ExecutorKind::MultiThreaded) everywhere else.
#[derive(PartialEq, Eq, Default, Debug, Copy, Clone)]
pub enum ExecutorKind {
/// Runs the schedule using a single thread.
///
/// Useful if you're dealing with a single-threaded environment, saving your threads for
/// other things, or just trying minimize overhead.
#[cfg_attr(
any(
target_arch = "wasm32",
not(feature = "std"),
not(feature = "multi_threaded")
),
default
)]
SingleThreaded,
/// Runs the schedule using a thread pool. Non-conflicting systems can run in parallel.
#[cfg(feature = "std")]
#[cfg_attr(all(not(target_arch = "wasm32"), feature = "multi_threaded"), default)]
MultiThreaded,
}
/// Holds systems and conditions of a [`Schedule`](super::Schedule) sorted in topological order
/// (along with dependency information for `multi_threaded` execution).
///
/// Since the arrays are sorted in the same order, elements are referenced by their index.
/// [`FixedBitSet`] is used as a smaller, more efficient substitute of `HashSet<usize>`.
#[derive(Default)]
pub struct SystemSchedule {
/// List of system node ids.
pub(super) system_ids: Vec<SystemKey>,
/// Indexed by system node id.
pub(super) systems: Vec<SystemWithAccess>,
/// Indexed by system node id.
pub(super) system_conditions: Vec<Vec<ConditionWithAccess>>,
/// Indexed by system node id.
/// Number of systems that the system immediately depends on.
#[cfg_attr(
not(feature = "std"),
expect(dead_code, reason = "currently only used with the std feature")
)]
pub(super) system_dependencies: Vec<usize>,
/// Indexed by system node id.
/// List of systems that immediately depend on the system.
#[cfg_attr(
not(feature = "std"),
expect(dead_code, reason = "currently only used with the std feature")
)]
pub(super) system_dependents: Vec<Vec<usize>>,
/// Indexed by system node id.
/// List of sets containing the system that have conditions
pub(super) sets_with_conditions_of_systems: Vec<FixedBitSet>,
/// List of system set node ids.
pub(super) set_ids: Vec<SystemSetKey>,
/// Indexed by system set node id.
pub(super) set_conditions: Vec<Vec<ConditionWithAccess>>,
/// Indexed by system set node id.
/// List of systems that are in sets that have conditions.
///
/// If a set doesn't run because of its conditions, this is used to skip all systems in it.
pub(super) systems_in_sets_with_conditions: Vec<FixedBitSet>,
}
impl SystemSchedule {
/// Creates an empty [`SystemSchedule`].
pub const fn new() -> Self {
Self {
systems: Vec::new(),
system_conditions: Vec::new(),
set_conditions: Vec::new(),
system_ids: Vec::new(),
set_ids: Vec::new(),
system_dependencies: Vec::new(),
system_dependents: Vec::new(),
sets_with_conditions_of_systems: Vec::new(),
systems_in_sets_with_conditions: Vec::new(),
}
}
}
/// A special [`System`] that instructs the executor to call
/// [`System::apply_deferred`] on the systems that have run but not applied
/// their [`Deferred`] system parameters (like [`Commands`]) or other system buffers.
///
/// ## Scheduling
///
/// `ApplyDeferred` systems are scheduled *by default*
/// - later in the same schedule run (for example, if a system with `Commands` param
/// is scheduled in `Update`, all the changes will be visible in `PostUpdate`)
/// - between systems with dependencies if the dependency [has deferred buffers]
/// (if system `bar` directly or indirectly depends on `foo`, and `foo` uses
/// `Commands` param, changes to the world in `foo` will be visible in `bar`)
///
/// ## Notes
/// - This system (currently) does nothing if it's called manually or wrapped
/// inside a [`PipeSystem`].
/// - Modifying a [`Schedule`] may change the order buffers are applied.
///
/// [`System::apply_deferred`]: crate::system::System::apply_deferred
/// [`Deferred`]: crate::system::Deferred
/// [`Commands`]: crate::prelude::Commands
/// [has deferred buffers]: crate::system::System::has_deferred
/// [`PipeSystem`]: crate::system::PipeSystem
/// [`Schedule`]: super::Schedule
#[doc(alias = "apply_system_buffers")]
pub struct ApplyDeferred;
/// Returns `true` if the [`System`] is an instance of [`ApplyDeferred`].
pub(super) fn is_apply_deferred(system: &dyn System<In = (), Out = ()>) -> bool {
system.type_id() == TypeId::of::<ApplyDeferred>()
}
impl System for ApplyDeferred {
type In = ();
type Out = ();
fn name(&self) -> DebugName {
DebugName::borrowed("bevy_ecs::apply_deferred")
}
fn flags(&self) -> SystemStateFlags {
// non-send , exclusive , no deferred
SystemStateFlags::NON_SEND | SystemStateFlags::EXCLUSIVE
}
unsafe fn run_unsafe(
&mut self,
_input: SystemIn<'_, Self>,
_world: UnsafeWorldCell,
) -> Result<Self::Out, RunSystemError> {
// This system does nothing on its own. The executor will apply deferred
// commands from other systems instead of running this system.
Ok(())
}
#[cfg(feature = "hotpatching")]
#[inline]
fn refresh_hotpatch(&mut self) {}
fn run(
&mut self,
_input: SystemIn<'_, Self>,
_world: &mut World,
) -> Result<Self::Out, RunSystemError> {
// This system does nothing on its own. The executor will apply deferred
// commands from other systems instead of running this system.
Ok(())
}
fn apply_deferred(&mut self, _world: &mut World) {}
fn queue_deferred(&mut self, _world: DeferredWorld) {}
unsafe fn validate_param_unsafe(
&mut self,
_world: UnsafeWorldCell,
) -> Result<(), SystemParamValidationError> {
// This system is always valid to run because it doesn't do anything,
// and only used as a marker for the executor.
Ok(())
}
fn initialize(&mut self, _world: &mut World) -> FilteredAccessSet {
FilteredAccessSet::new()
}
fn check_change_tick(&mut self, _check: CheckChangeTicks) {}
fn default_system_sets(&self) -> Vec<InternedSystemSet> {
vec![SystemTypeSet::<Self>::new().intern()]
}
fn get_last_run(&self) -> Tick {
// This system is never run, so it has no last run tick.
Tick::MAX
}
fn set_last_run(&mut self, _last_run: Tick) {}
}
impl IntoSystemSet<()> for ApplyDeferred {
type Set = SystemTypeSet<Self>;
fn into_system_set(self) -> Self::Set {
SystemTypeSet::<Self>::new()
}
}
/// These functions hide the bottom of the callstack from `RUST_BACKTRACE=1` (assuming the default panic handler is used).
///
/// The full callstack will still be visible with `RUST_BACKTRACE=full`.
/// They are specialized for `System::run` & co instead of being generic over closures because this avoids an
/// extra frame in the backtrace.
///
/// This is reliant on undocumented behavior in Rust's default panic handler, which checks the call stack for symbols
/// containing the string `__rust_begin_short_backtrace` in their mangled name.
mod __rust_begin_short_backtrace {
use core::hint::black_box;
#[cfg(feature = "std")]
use crate::world::unsafe_world_cell::UnsafeWorldCell;
use crate::{
error::Result,
system::{ReadOnlySystem, RunSystemError, ScheduleSystem},
world::World,
};
/// # Safety
/// See `System::run_unsafe`.
// This is only used by `MultiThreadedExecutor`, and would be dead code without `std`.
#[cfg(feature = "std")]
#[inline(never)]
pub(super) unsafe fn run_unsafe(
system: &mut ScheduleSystem,
world: UnsafeWorldCell,
) -> Result<(), RunSystemError> {
// SAFETY: Upheld by caller
let result = unsafe { system.run_unsafe((), world) };
// Call `black_box` to prevent this frame from being tail-call optimized away
black_box(());
result
}
/// # Safety
/// See `ReadOnlySystem::run_unsafe`.
// This is only used by `MultiThreadedExecutor`, and would be dead code without `std`.
#[cfg(feature = "std")]
#[inline(never)]
pub(super) unsafe fn readonly_run_unsafe<O: 'static>(
system: &mut dyn ReadOnlySystem<In = (), Out = O>,
world: UnsafeWorldCell,
) -> Result<O, RunSystemError> {
// Call `black_box` to prevent this frame from being tail-call optimized away
// SAFETY: Upheld by caller
black_box(unsafe { system.run_unsafe((), world) })
}
#[cfg(feature = "std")]
#[inline(never)]
pub(super) fn run(
system: &mut ScheduleSystem,
world: &mut World,
) -> Result<(), RunSystemError> {
let result = system.run((), world);
// Call `black_box` to prevent this frame from being tail-call optimized away
black_box(());
result
}
#[inline(never)]
pub(super) fn run_without_applying_deferred(
system: &mut ScheduleSystem,
world: &mut World,
) -> Result<(), RunSystemError> {
let result = system.run_without_applying_deferred((), world);
// Call `black_box` to prevent this frame from being tail-call optimized away
black_box(());
result
}
#[inline(never)]
pub(super) fn readonly_run<O: 'static>(
system: &mut dyn ReadOnlySystem<In = (), Out = O>,
world: &mut World,
) -> Result<O, RunSystemError> {
// Call `black_box` to prevent this frame from being tail-call optimized away
black_box(system.run((), world))
}
}
#[cfg(test)]
mod tests {
use crate::{
prelude::{Component, In, IntoSystem, Resource, Schedule},
schedule::ExecutorKind,
system::{Populated, Res, ResMut, Single},
world::World,
};
#[derive(Component)]
struct TestComponent;
const EXECUTORS: [ExecutorKind; 2] =
[ExecutorKind::SingleThreaded, ExecutorKind::MultiThreaded];
#[derive(Resource, Default)]
struct TestState {
populated_ran: bool,
single_ran: bool,
}
#[derive(Resource, Default)]
struct Counter(u8);
fn set_single_state(mut _single: Single<&TestComponent>, mut state: ResMut<TestState>) {
state.single_ran = true;
}
fn set_populated_state(
mut _populated: Populated<&TestComponent>,
mut state: ResMut<TestState>,
) {
state.populated_ran = true;
}
#[test]
#[expect(clippy::print_stdout, reason = "std and println are allowed in tests")]
fn single_and_populated_skipped_and_run() {
for executor in EXECUTORS {
std::println!("Testing executor: {executor:?}");
let mut world = World::new();
world.init_resource::<TestState>();
let mut schedule = Schedule::default();
schedule.set_executor_kind(executor);
schedule.add_systems((set_single_state, set_populated_state));
schedule.run(&mut world);
let state = world.get_resource::<TestState>().unwrap();
assert!(!state.single_ran);
assert!(!state.populated_ran);
world.spawn(TestComponent);
schedule.run(&mut world);
let state = world.get_resource::<TestState>().unwrap();
assert!(state.single_ran);
assert!(state.populated_ran);
}
}
fn look_for_missing_resource(_res: Res<TestState>) {}
#[test]
#[should_panic]
fn missing_resource_panics_single_threaded() {
let mut world = World::new();
let mut schedule = Schedule::default();
schedule.set_executor_kind(ExecutorKind::SingleThreaded);
schedule.add_systems(look_for_missing_resource);
schedule.run(&mut world);
}
#[test]
#[should_panic]
fn missing_resource_panics_multi_threaded() {
let mut world = World::new();
let mut schedule = Schedule::default();
schedule.set_executor_kind(ExecutorKind::MultiThreaded);
schedule.add_systems(look_for_missing_resource);
schedule.run(&mut world);
}
#[test]
fn piped_systems_first_system_skipped() {
// This system should be skipped when run due to no matching entity
fn pipe_out(_single: Single<&TestComponent>) -> u8 {
42
}
fn pipe_in(_input: In<u8>, mut counter: ResMut<Counter>) {
counter.0 += 1;
}
let mut world = World::new();
world.init_resource::<Counter>();
let mut schedule = Schedule::default();
schedule.add_systems(pipe_out.pipe(pipe_in));
schedule.run(&mut world);
let counter = world.resource::<Counter>();
assert_eq!(counter.0, 0);
}
#[test]
fn piped_system_second_system_skipped() {
// This system will be run before the second system is validated
fn pipe_out(mut counter: ResMut<Counter>) -> u8 {
counter.0 += 1;
42
}
// This system should be skipped when run due to no matching entity
fn pipe_in(_input: In<u8>, _single: Single<&TestComponent>, mut counter: ResMut<Counter>) {
counter.0 += 1;
}
let mut world = World::new();
world.init_resource::<Counter>();
let mut schedule = Schedule::default();
schedule.add_systems(pipe_out.pipe(pipe_in));
schedule.run(&mut world);
let counter = world.resource::<Counter>();
assert_eq!(counter.0, 1);
}
#[test]
#[should_panic]
fn piped_system_first_system_panics() {
// This system should panic when run because the resource is missing
fn pipe_out(_res: Res<TestState>) -> u8 {
42
}
fn pipe_in(_input: In<u8>) {}
let mut world = World::new();
let mut schedule = Schedule::default();
schedule.add_systems(pipe_out.pipe(pipe_in));
schedule.run(&mut world);
}
#[test]
#[should_panic]
fn piped_system_second_system_panics() {
fn pipe_out() -> u8 {
42
}
// This system should panic when run because the resource is missing
fn pipe_in(_input: In<u8>, _res: Res<TestState>) {}
let mut world = World::new();
let mut schedule = Schedule::default();
schedule.add_systems(pipe_out.pipe(pipe_in));
schedule.run(&mut world);
}
// This test runs without panicking because we've
// decided to use early-out behavior for piped systems
#[test]
fn piped_system_skip_and_panic() {
// This system should be skipped when run due to no matching entity
fn pipe_out(_single: Single<&TestComponent>) -> u8 {
42
}
// This system should panic when run because the resource is missing
fn pipe_in(_input: In<u8>, _res: Res<TestState>) {}
let mut world = World::new();
let mut schedule = Schedule::default();
schedule.add_systems(pipe_out.pipe(pipe_in));
schedule.run(&mut world);
}
#[test]
#[should_panic]
fn piped_system_panic_and_skip() {
// This system should panic when run because the resource is missing
fn pipe_out(_res: Res<TestState>) -> u8 {
42
}
// This system should be skipped when run due to no matching entity
fn pipe_in(_input: In<u8>, _single: Single<&TestComponent>) {}
let mut world = World::new();
let mut schedule = Schedule::default();
schedule.add_systems(pipe_out.pipe(pipe_in));
schedule.run(&mut world);
}
#[test]
#[should_panic]
fn piped_system_panic_and_panic() {
// This system should panic when run because the resource is missing
fn pipe_out(_res: Res<TestState>) -> u8 {
42
}
// This system should panic when run because the resource is missing
fn pipe_in(_input: In<u8>, _res: Res<TestState>) {}
let mut world = World::new();
let mut schedule = Schedule::default();
schedule.add_systems(pipe_out.pipe(pipe_in));
schedule.run(&mut world);
}
#[test]
fn piped_system_skip_and_skip() {
// This system should be skipped when run due to no matching entity
fn pipe_out(_single: Single<&TestComponent>, mut counter: ResMut<Counter>) -> u8 {
counter.0 += 1;
42
}
// This system should be skipped when run due to no matching entity
fn pipe_in(_input: In<u8>, _single: Single<&TestComponent>, mut counter: ResMut<Counter>) {
counter.0 += 1;
}
let mut world = World::new();
world.init_resource::<Counter>();
let mut schedule = Schedule::default();
schedule.add_systems(pipe_out.pipe(pipe_in));
schedule.run(&mut world);
let counter = world.resource::<Counter>();
assert_eq!(counter.0, 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/src/reflect/resource.rs | crates/bevy_ecs/src/reflect/resource.rs | //! Definitions for [`Resource`] reflection.
//!
//! # Architecture
//!
//! See the module doc for [`reflect::component`](`crate::reflect::component`).
use crate::{
change_detection::Mut,
component::ComponentId,
resource::Resource,
world::{
error::ResourceFetchError, unsafe_world_cell::UnsafeWorldCell, FilteredResources,
FilteredResourcesMut, World,
},
};
use bevy_reflect::{FromReflect, FromType, PartialReflect, Reflect, TypePath, TypeRegistry};
use super::from_reflect_with_fallback;
/// A struct used to operate on reflected [`Resource`] of a type.
///
/// A [`ReflectResource`] for type `T` can be obtained via
/// [`bevy_reflect::TypeRegistration::data`].
#[derive(Clone)]
pub struct ReflectResource(ReflectResourceFns);
/// The raw function pointers needed to make up a [`ReflectResource`].
///
/// This is used when creating custom implementations of [`ReflectResource`] with
/// [`ReflectResource::new()`].
///
/// > **Note:**
/// > Creating custom implementations of [`ReflectResource`] is an advanced feature that most users
/// > will not need.
/// > Usually a [`ReflectResource`] is created for a type by deriving [`Reflect`]
/// > and adding the `#[reflect(Resource)]` attribute.
/// > After adding the component to the [`TypeRegistry`],
/// > its [`ReflectResource`] can then be retrieved when needed.
///
/// Creating a custom [`ReflectResource`] may be useful if you need to create new resource types at
/// runtime, for example, for scripting implementations.
///
/// By creating a custom [`ReflectResource`] and inserting it into a type's
/// [`TypeRegistration`][bevy_reflect::TypeRegistration],
/// you can modify the way that reflected resources of that type will be inserted into the bevy
/// world.
#[derive(Clone)]
pub struct ReflectResourceFns {
/// Function pointer implementing [`ReflectResource::insert()`].
pub insert: fn(&mut World, &dyn PartialReflect, &TypeRegistry),
/// Function pointer implementing [`ReflectResource::apply()`].
pub apply: fn(&mut World, &dyn PartialReflect),
/// Function pointer implementing [`ReflectResource::apply_or_insert()`].
pub apply_or_insert: fn(&mut World, &dyn PartialReflect, &TypeRegistry),
/// Function pointer implementing [`ReflectResource::remove()`].
pub remove: fn(&mut World),
/// Function pointer implementing [`ReflectResource::reflect()`].
pub reflect:
for<'w> fn(FilteredResources<'w, '_>) -> Result<&'w dyn Reflect, ResourceFetchError>,
/// Function pointer implementing [`ReflectResource::reflect_mut()`].
pub reflect_mut: for<'w> fn(
FilteredResourcesMut<'w, '_>,
) -> Result<Mut<'w, dyn Reflect>, ResourceFetchError>,
/// Function pointer implementing [`ReflectResource::reflect_unchecked_mut()`].
///
/// # Safety
/// The function may only be called with an [`UnsafeWorldCell`] that can be used to mutably access the relevant resource.
pub reflect_unchecked_mut: unsafe fn(UnsafeWorldCell<'_>) -> Option<Mut<'_, dyn Reflect>>,
/// Function pointer implementing [`ReflectResource::copy()`].
pub copy: fn(&World, &mut World, &TypeRegistry),
/// Function pointer implementing [`ReflectResource::register_resource()`].
pub register_resource: fn(&mut World) -> ComponentId,
}
impl ReflectResourceFns {
/// Get the default set of [`ReflectResourceFns`] for a specific resource type using its
/// [`FromType`] implementation.
///
/// This is useful if you want to start with the default implementation before overriding some
/// of the functions to create a custom implementation.
pub fn new<T: Resource + FromReflect + TypePath>() -> Self {
<ReflectResource as FromType<T>>::from_type().0
}
}
impl ReflectResource {
/// Insert a reflected [`Resource`] into the world like [`insert()`](World::insert_resource).
pub fn insert(
&self,
world: &mut World,
resource: &dyn PartialReflect,
registry: &TypeRegistry,
) {
(self.0.insert)(world, resource, registry);
}
/// Uses reflection to set the value of this [`Resource`] type in the world to the given value.
///
/// # Panics
///
/// Panics if there is no [`Resource`] of the given type.
pub fn apply(&self, world: &mut World, resource: &dyn PartialReflect) {
(self.0.apply)(world, resource);
}
/// Uses reflection to set the value of this [`Resource`] type in the world to the given value or insert a new one if it does not exist.
pub fn apply_or_insert(
&self,
world: &mut World,
resource: &dyn PartialReflect,
registry: &TypeRegistry,
) {
(self.0.apply_or_insert)(world, resource, registry);
}
/// Removes this [`Resource`] type from the world. Does nothing if it doesn't exist.
pub fn remove(&self, world: &mut World) {
(self.0.remove)(world);
}
/// Gets the value of this [`Resource`] type from the world as a reflected reference.
///
/// Note that [`&World`](World) is a valid type for `resources`.
pub fn reflect<'w, 's>(
&self,
resources: impl Into<FilteredResources<'w, 's>>,
) -> Result<&'w dyn Reflect, ResourceFetchError> {
(self.0.reflect)(resources.into())
}
/// Gets the value of this [`Resource`] type from the world as a mutable reflected reference.
///
/// Note that [`&mut World`](World) is a valid type for `resources`.
pub fn reflect_mut<'w, 's>(
&self,
resources: impl Into<FilteredResourcesMut<'w, 's>>,
) -> Result<Mut<'w, dyn Reflect>, ResourceFetchError> {
(self.0.reflect_mut)(resources.into())
}
/// # Safety
/// This method does not prevent you from having two mutable pointers to the same data,
/// violating Rust's aliasing rules. To avoid this:
/// * Only call this method with an [`UnsafeWorldCell`] which can be used to mutably access the resource.
/// * Don't call this method more than once in the same scope for a given [`Resource`].
pub unsafe fn reflect_unchecked_mut<'w>(
&self,
world: UnsafeWorldCell<'w>,
) -> Option<Mut<'w, dyn Reflect>> {
// SAFETY: caller promises to uphold uniqueness guarantees
unsafe { (self.0.reflect_unchecked_mut)(world) }
}
/// Gets the value of this [`Resource`] type from `source_world` and [applies](Self::apply()) it to the value of this [`Resource`] type in `destination_world`.
///
/// # Panics
///
/// Panics if there is no [`Resource`] of the given type.
pub fn copy(
&self,
source_world: &World,
destination_world: &mut World,
registry: &TypeRegistry,
) {
(self.0.copy)(source_world, destination_world, registry);
}
/// Register the type of this [`Resource`] in [`World`], returning the [`ComponentId`]
pub fn register_resource(&self, world: &mut World) -> ComponentId {
(self.0.register_resource)(world)
}
/// Create a custom implementation of [`ReflectResource`].
///
/// This is an advanced feature,
/// useful for scripting implementations,
/// that should not be used by most users
/// unless you know what you are doing.
///
/// Usually you should derive [`Reflect`] and add the `#[reflect(Resource)]` component
/// to generate a [`ReflectResource`] implementation automatically.
///
/// See [`ReflectResourceFns`] for more information.
pub fn new(&self, fns: ReflectResourceFns) -> Self {
Self(fns)
}
/// The underlying function pointers implementing methods on `ReflectResource`.
///
/// This is useful when you want to keep track locally of an individual
/// function pointer.
///
/// Calling [`TypeRegistry::get`] followed by
/// [`TypeRegistration::data::<ReflectResource>`] can be costly if done several
/// times per frame. Consider cloning [`ReflectResource`] and keeping it
/// between frames, cloning a `ReflectResource` is very cheap.
///
/// If you only need a subset of the methods on `ReflectResource`,
/// use `fn_pointers` to get the underlying [`ReflectResourceFns`]
/// and copy the subset of function pointers you care about.
///
/// [`TypeRegistration::data::<ReflectResource>`]: bevy_reflect::TypeRegistration::data
/// [`TypeRegistry::get`]: bevy_reflect::TypeRegistry::get
pub fn fn_pointers(&self) -> &ReflectResourceFns {
&self.0
}
}
impl<R: Resource + FromReflect + TypePath> FromType<R> for ReflectResource {
fn from_type() -> Self {
ReflectResource(ReflectResourceFns {
insert: |world, reflected_resource, registry| {
let resource = from_reflect_with_fallback::<R>(reflected_resource, world, registry);
world.insert_resource(resource);
},
apply: |world, reflected_resource| {
let mut resource = world.resource_mut::<R>();
resource.apply(reflected_resource);
},
apply_or_insert: |world, reflected_resource, registry| {
if let Some(mut resource) = world.get_resource_mut::<R>() {
resource.apply(reflected_resource);
} else {
let resource =
from_reflect_with_fallback::<R>(reflected_resource, world, registry);
world.insert_resource(resource);
}
},
remove: |world| {
world.remove_resource::<R>();
},
reflect: |world| world.get::<R>().map(|res| res.into_inner() as &dyn Reflect),
reflect_mut: |world| {
world
.into_mut::<R>()
.map(|res| res.map_unchanged(|value| value as &mut dyn Reflect))
},
reflect_unchecked_mut: |world| {
// SAFETY: all usages of `reflect_unchecked_mut` guarantee that there is either a single mutable
// reference or multiple immutable ones alive at any given point
let res = unsafe { world.get_resource_mut::<R>() };
res.map(|res| res.map_unchanged(|value| value as &mut dyn Reflect))
},
copy: |source_world, destination_world, registry| {
let source_resource = source_world.resource::<R>();
let destination_resource =
from_reflect_with_fallback::<R>(source_resource, destination_world, registry);
destination_world.insert_resource(destination_resource);
},
register_resource: |world: &mut World| -> ComponentId {
world.register_resource::<R>()
},
})
}
}
| 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/reflect/event.rs | crates/bevy_ecs/src/reflect/event.rs | //! Definitions for [`Event`] reflection.
//! This allows triggering events whose type is only known at runtime.
//!
//! This module exports two types: [`ReflectEventFns`] and [`ReflectEvent`].
//!
//! Same as [`component`](`super::component`), but for events.
use crate::{event::Event, reflect::from_reflect_with_fallback, world::World};
use bevy_reflect::{FromReflect, FromType, PartialReflect, Reflect, TypePath, TypeRegistry};
/// A struct used to operate on reflected [`Event`] trait of a type.
///
/// A [`ReflectEvent`] for type `T` can be obtained via
/// [`bevy_reflect::TypeRegistration::data`].
#[derive(Clone)]
pub struct ReflectEvent(ReflectEventFns);
/// The raw function pointers needed to make up a [`ReflectEvent`].
///
/// This is used when creating custom implementations of [`ReflectEvent`] with
/// [`ReflectEventFns::new()`].
///
/// > **Note:**
/// > Creating custom implementations of [`ReflectEvent`] is an advanced feature that most users
/// > will not need.
/// > Usually a [`ReflectEvent`] is created for a type by deriving [`Reflect`]
/// > and adding the `#[reflect(Event)]` attribute.
/// > After adding the component to the [`TypeRegistry`],
/// > its [`ReflectEvent`] can then be retrieved when needed.
///
/// Creating a custom [`ReflectEvent`] may be useful if you need to create new component types
/// at runtime, for example, for scripting implementations.
///
/// By creating a custom [`ReflectEvent`] and inserting it into a type's
/// [`TypeRegistration`][bevy_reflect::TypeRegistration],
/// you can modify the way that reflected event of that type will be triggered in the Bevy
/// world.
#[derive(Clone)]
pub struct ReflectEventFns {
trigger: fn(&mut World, &dyn PartialReflect, &TypeRegistry),
}
impl ReflectEventFns {
/// Get the default set of [`ReflectEventFns`] for a specific event type using its
/// [`FromType`] implementation.
///
/// This is useful if you want to start with the default implementation before overriding some
/// of the functions to create a custom implementation.
pub fn new<'a, T: Event + FromReflect + TypePath>() -> Self
where
T::Trigger<'a>: Default,
{
<ReflectEvent as FromType<T>>::from_type().0
}
}
impl ReflectEvent {
/// Triggers a reflected [`Event`] like [`trigger()`](World::trigger).
pub fn trigger(&self, world: &mut World, event: &dyn PartialReflect, registry: &TypeRegistry) {
(self.0.trigger)(world, event, registry);
}
}
impl<'a, E: Event + Reflect + TypePath> FromType<E> for ReflectEvent
where
<E as Event>::Trigger<'a>: Default,
{
fn from_type() -> Self {
ReflectEvent(ReflectEventFns {
trigger: |world, reflected_event, registry| {
let event = from_reflect_with_fallback::<E>(reflected_event, world, registry);
world.trigger(event);
},
})
}
}
| 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/reflect/bundle.rs | crates/bevy_ecs/src/reflect/bundle.rs | //! Definitions for [`Bundle`] reflection.
//! This allows inserting, updating and/or removing bundles whose type is only known at runtime.
//!
//! This module exports two types: [`ReflectBundleFns`] and [`ReflectBundle`].
//!
//! Same as [`component`](`super::component`), but for bundles.
use alloc::boxed::Box;
use bevy_utils::prelude::DebugName;
use core::any::{Any, TypeId};
use crate::{
bundle::BundleFromComponents,
entity::EntityMapper,
prelude::Bundle,
relationship::RelationshipHookMode,
world::{EntityMut, EntityWorldMut},
};
use bevy_reflect::{
FromReflect, FromType, PartialReflect, Reflect, ReflectRef, TypePath, TypeRegistry,
};
use super::{from_reflect_with_fallback, ReflectComponent};
/// A struct used to operate on reflected [`Bundle`] trait of a type.
///
/// A [`ReflectBundle`] for type `T` can be obtained via
/// [`bevy_reflect::TypeRegistration::data`].
#[derive(Clone)]
pub struct ReflectBundle(ReflectBundleFns);
/// The raw function pointers needed to make up a [`ReflectBundle`].
///
/// The also [`ReflectComponentFns`](`super::component::ReflectComponentFns`).
#[derive(Clone)]
pub struct ReflectBundleFns {
/// Function pointer implementing [`ReflectBundle::insert`].
pub insert: fn(&mut EntityWorldMut, &dyn PartialReflect, &TypeRegistry),
/// Function pointer implementing [`ReflectBundle::apply`].
pub apply: fn(EntityMut, &dyn PartialReflect, &TypeRegistry),
/// Function pointer implementing [`ReflectBundle::apply_or_insert_mapped`].
pub apply_or_insert_mapped: fn(
&mut EntityWorldMut,
&dyn PartialReflect,
&TypeRegistry,
&mut dyn EntityMapper,
RelationshipHookMode,
),
/// Function pointer implementing [`ReflectBundle::remove`].
pub remove: fn(&mut EntityWorldMut),
/// Function pointer implementing [`ReflectBundle::take`].
pub take: fn(&mut EntityWorldMut) -> Option<Box<dyn Reflect>>,
}
impl ReflectBundleFns {
/// Get the default set of [`ReflectBundleFns`] for a specific bundle type using its
/// [`FromType`] implementation.
///
/// This is useful if you want to start with the default implementation before overriding some
/// of the functions to create a custom implementation.
pub fn new<T: Bundle + FromReflect + TypePath + BundleFromComponents>() -> Self {
<ReflectBundle as FromType<T>>::from_type().0
}
}
impl ReflectBundle {
/// Insert a reflected [`Bundle`] into the entity like [`insert()`](EntityWorldMut::insert).
pub fn insert(
&self,
entity: &mut EntityWorldMut,
bundle: &dyn PartialReflect,
registry: &TypeRegistry,
) {
(self.0.insert)(entity, bundle, registry);
}
/// Uses reflection to set the value of this [`Bundle`] type in the entity to the given value.
///
/// # Panics
///
/// Panics if there is no [`Bundle`] of the given type.
pub fn apply<'a>(
&self,
entity: impl Into<EntityMut<'a>>,
bundle: &dyn PartialReflect,
registry: &TypeRegistry,
) {
(self.0.apply)(entity.into(), bundle, registry);
}
/// Uses reflection to set the value of this [`Bundle`] type in the entity to the given value or insert a new one if it does not exist.
pub fn apply_or_insert_mapped(
&self,
entity: &mut EntityWorldMut,
bundle: &dyn PartialReflect,
registry: &TypeRegistry,
mapper: &mut dyn EntityMapper,
relationship_hook_mode: RelationshipHookMode,
) {
(self.0.apply_or_insert_mapped)(entity, bundle, registry, mapper, relationship_hook_mode);
}
/// Removes this [`Bundle`] type from the entity. Does nothing if it doesn't exist.
pub fn remove(&self, entity: &mut EntityWorldMut) -> &ReflectBundle {
(self.0.remove)(entity);
self
}
/// Removes all components in the [`Bundle`] from the entity and returns their previous values.
///
/// **Note:** If the entity does not have every component in the bundle, this method will not remove any of them.
#[must_use]
pub fn take(&self, entity: &mut EntityWorldMut) -> Option<Box<dyn Reflect>> {
(self.0.take)(entity)
}
/// Create a custom implementation of [`ReflectBundle`].
///
/// This is an advanced feature,
/// useful for scripting implementations,
/// that should not be used by most users
/// unless you know what you are doing.
///
/// Usually you should derive [`Reflect`] and add the `#[reflect(Bundle)]` bundle
/// to generate a [`ReflectBundle`] implementation automatically.
///
/// See [`ReflectBundleFns`] for more information.
pub fn new(fns: ReflectBundleFns) -> Self {
Self(fns)
}
/// The underlying function pointers implementing methods on `ReflectBundle`.
///
/// This is useful when you want to keep track locally of an individual
/// function pointer.
///
/// Calling [`TypeRegistry::get`] followed by
/// [`TypeRegistration::data::<ReflectBundle>`] can be costly if done several
/// times per frame. Consider cloning [`ReflectBundle`] and keeping it
/// between frames, cloning a `ReflectBundle` is very cheap.
///
/// If you only need a subset of the methods on `ReflectBundle`,
/// use `fn_pointers` to get the underlying [`ReflectBundleFns`]
/// and copy the subset of function pointers you care about.
///
/// [`TypeRegistration::data::<ReflectBundle>`]: bevy_reflect::TypeRegistration::data
pub fn fn_pointers(&self) -> &ReflectBundleFns {
&self.0
}
}
impl<B: Bundle + Reflect + TypePath + BundleFromComponents> FromType<B> for ReflectBundle {
fn from_type() -> Self {
ReflectBundle(ReflectBundleFns {
insert: |entity, reflected_bundle, registry| {
let bundle = entity.world_scope(|world| {
from_reflect_with_fallback::<B>(reflected_bundle, world, registry)
});
entity.insert(bundle);
},
apply: |mut entity, reflected_bundle, registry| {
if let Some(reflect_component) =
registry.get_type_data::<ReflectComponent>(TypeId::of::<B>())
{
reflect_component.apply(entity, reflected_bundle);
} else {
match reflected_bundle.reflect_ref() {
ReflectRef::Struct(bundle) => bundle
.iter_fields()
.for_each(|field| apply_field(&mut entity, field, registry)),
ReflectRef::Tuple(bundle) => bundle
.iter_fields()
.for_each(|field| apply_field(&mut entity, field, registry)),
_ => panic!(
"expected bundle `{}` to be named struct or tuple",
// FIXME: once we have unique reflect, use `TypePath`.
DebugName::type_name::<B>(),
),
}
}
},
apply_or_insert_mapped: |entity,
reflected_bundle,
registry,
mapper,
relationship_hook_mode| {
if let Some(reflect_component) =
registry.get_type_data::<ReflectComponent>(TypeId::of::<B>())
{
reflect_component.apply_or_insert_mapped(
entity,
reflected_bundle,
registry,
mapper,
relationship_hook_mode,
);
} else {
match reflected_bundle.reflect_ref() {
ReflectRef::Struct(bundle) => bundle.iter_fields().for_each(|field| {
apply_or_insert_field_mapped(
entity,
field,
registry,
mapper,
relationship_hook_mode,
);
}),
ReflectRef::Tuple(bundle) => bundle.iter_fields().for_each(|field| {
apply_or_insert_field_mapped(
entity,
field,
registry,
mapper,
relationship_hook_mode,
);
}),
_ => panic!(
"expected bundle `{}` to be a named struct or tuple",
// FIXME: once we have unique reflect, use `TypePath`.
DebugName::type_name::<B>(),
),
}
}
},
remove: |entity| {
entity.remove::<B>();
},
take: |entity| {
entity
.take::<B>()
.map(|bundle| Box::new(bundle).into_reflect())
},
})
}
}
fn apply_field(entity: &mut EntityMut, field: &dyn PartialReflect, registry: &TypeRegistry) {
let Some(type_id) = field.try_as_reflect().map(Any::type_id) else {
panic!(
"`{}` did not implement `Reflect`",
field.reflect_type_path()
);
};
if let Some(reflect_component) = registry.get_type_data::<ReflectComponent>(type_id) {
reflect_component.apply(entity.reborrow(), field);
} else if let Some(reflect_bundle) = registry.get_type_data::<ReflectBundle>(type_id) {
reflect_bundle.apply(entity.reborrow(), field, registry);
} else {
panic!(
"no `ReflectComponent` nor `ReflectBundle` registration found for `{}`",
field.reflect_type_path()
);
}
}
fn apply_or_insert_field_mapped(
entity: &mut EntityWorldMut,
field: &dyn PartialReflect,
registry: &TypeRegistry,
mapper: &mut dyn EntityMapper,
relationship_hook_mode: RelationshipHookMode,
) {
let Some(type_id) = field.try_as_reflect().map(Any::type_id) else {
panic!(
"`{}` did not implement `Reflect`",
field.reflect_type_path()
);
};
if let Some(reflect_component) = registry.get_type_data::<ReflectComponent>(type_id) {
reflect_component.apply_or_insert_mapped(
entity,
field,
registry,
mapper,
relationship_hook_mode,
);
} else if let Some(reflect_bundle) = registry.get_type_data::<ReflectBundle>(type_id) {
reflect_bundle.apply_or_insert_mapped(
entity,
field,
registry,
mapper,
relationship_hook_mode,
);
} else {
let is_component = entity.world().components().get_id(type_id).is_some();
if is_component {
panic!(
"no `ReflectComponent` registration found for `{}`",
field.reflect_type_path(),
);
} else {
panic!(
"no `ReflectBundle` registration found for `{}`",
field.reflect_type_path(),
)
}
}
}
| 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/reflect/entity_commands.rs | crates/bevy_ecs/src/reflect/entity_commands.rs | use crate::{
prelude::Mut,
reflect::{AppTypeRegistry, ReflectBundle, ReflectComponent},
resource::Resource,
system::EntityCommands,
world::EntityWorldMut,
};
use alloc::{borrow::Cow, boxed::Box};
use bevy_reflect::{PartialReflect, TypeRegistry};
/// An extension trait for [`EntityCommands`] for reflection related functions
pub trait ReflectCommandExt {
/// Adds the given boxed reflect component or bundle to the entity using the reflection data in
/// [`AppTypeRegistry`].
///
/// This will overwrite any previous component(s) of the same type.
///
/// # Panics
///
/// - If the entity doesn't exist.
/// - If [`AppTypeRegistry`] does not have the reflection data for the given
/// [`Component`](crate::component::Component) or [`Bundle`](crate::bundle::Bundle).
/// - If the component or bundle data is invalid. See [`PartialReflect::apply`] for further details.
/// - If [`AppTypeRegistry`] is not present in the [`World`](crate::world::World).
///
/// # Note
///
/// Prefer to use the typed [`EntityCommands::insert`] if possible. Adding a reflected component
/// is much slower.
///
/// # Example
///
/// ```
/// // Note that you need to register the component type in the AppTypeRegistry prior to using
/// // reflection. You can use the helpers on the App with `app.register_type::<ComponentA>()`
/// // or write to the TypeRegistry directly to register all your components
///
/// # use bevy_ecs::prelude::*;
/// # use bevy_ecs::reflect::{ReflectCommandExt, ReflectBundle};
/// # use bevy_reflect::{FromReflect, FromType, Reflect, TypeRegistry};
/// // A resource that can hold any component that implements reflect as a boxed reflect component
/// #[derive(Resource)]
/// struct Prefab {
/// data: Box<dyn Reflect>,
/// }
/// #[derive(Component, Reflect, Default)]
/// #[reflect(Component)]
/// struct ComponentA(u32);
///
/// #[derive(Component, Reflect, Default)]
/// #[reflect(Component)]
/// struct ComponentB(String);
///
/// #[derive(Bundle, Reflect, Default)]
/// #[reflect(Bundle)]
/// struct BundleA {
/// a: ComponentA,
/// b: ComponentB,
/// }
///
/// fn insert_reflect_component(
/// mut commands: Commands,
/// mut prefab: ResMut<Prefab>
/// ) {
/// // Create a set of new boxed reflect components to use
/// let boxed_reflect_component_a: Box<dyn Reflect> = Box::new(ComponentA(916));
/// let boxed_reflect_component_b: Box<dyn Reflect> = Box::new(ComponentB("NineSixteen".to_string()));
/// let boxed_reflect_bundle_a: Box<dyn Reflect> = Box::new(BundleA {
/// a: ComponentA(24),
/// b: ComponentB("Twenty-Four".to_string()),
/// });
///
/// // You can overwrite the component in the resource with either ComponentA or ComponentB
/// prefab.data = boxed_reflect_component_a;
/// prefab.data = boxed_reflect_component_b;
///
/// // Or even with BundleA
/// prefab.data = boxed_reflect_bundle_a;
///
/// // No matter which component or bundle is in the resource and without knowing the exact type, you can
/// // use the insert_reflect entity command to insert that component/bundle into an entity.
/// commands
/// .spawn_empty()
/// .insert_reflect(prefab.data.reflect_clone().unwrap().into_partial_reflect());
/// }
/// ```
fn insert_reflect(&mut self, component: Box<dyn PartialReflect>) -> &mut Self;
/// Same as [`insert_reflect`](ReflectCommandExt::insert_reflect), but using the `T` resource as type registry instead of
/// `AppTypeRegistry`.
///
/// # Panics
///
/// - If the given [`Resource`] is not present in the [`World`](crate::world::World).
///
/// # Note
///
/// - The given [`Resource`] is removed from the [`World`](crate::world::World) before the command is applied.
fn insert_reflect_with_registry<T: Resource + AsRef<TypeRegistry>>(
&mut self,
component: Box<dyn PartialReflect>,
) -> &mut Self;
/// Removes from the entity the component or bundle with the given type path registered in [`AppTypeRegistry`].
///
/// If the type is a bundle, it will remove any components in that bundle regardless if the entity
/// contains all the components.
///
/// Does nothing if the type is a component and the entity does not have a component of the same type,
/// if the type is a bundle and the entity does not contain any of the components in the bundle,
/// if [`AppTypeRegistry`] does not contain the reflection data for the given component,
/// or if the entity does not exist.
///
/// # Note
///
/// Prefer to use the typed [`EntityCommands::remove`] if possible. Removing a reflected component
/// is much slower.
///
/// # Example
///
/// ```
/// // Note that you need to register the component/bundle type in the AppTypeRegistry prior to using
/// // reflection. You can use the helpers on the App with `app.register_type::<ComponentA>()`
/// // or write to the TypeRegistry directly to register all your components and bundles
///
/// # use bevy_ecs::prelude::*;
/// # use bevy_ecs::reflect::{ReflectCommandExt, ReflectBundle};
/// # use bevy_reflect::{FromReflect, FromType, Reflect, TypeRegistry};
///
/// // A resource that can hold any component or bundle that implements reflect as a boxed reflect
/// #[derive(Resource)]
/// struct Prefab{
/// entity: Entity,
/// data: Box<dyn Reflect>,
/// }
/// #[derive(Component, Reflect, Default)]
/// #[reflect(Component)]
/// struct ComponentA(u32);
/// #[derive(Component, Reflect, Default)]
/// #[reflect(Component)]
/// struct ComponentB(String);
/// #[derive(Bundle, Reflect, Default)]
/// #[reflect(Bundle)]
/// struct BundleA {
/// a: ComponentA,
/// b: ComponentB,
/// }
///
/// fn remove_reflect_component(
/// mut commands: Commands,
/// prefab: Res<Prefab>
/// ) {
/// // Prefab can hold any boxed reflect component or bundle. In this case either
/// // ComponentA, ComponentB, or BundleA. No matter which component or bundle is in the resource though,
/// // we can attempt to remove any component (or set of components in the case of a bundle)
/// // of that same type from an entity.
/// commands.entity(prefab.entity)
/// .remove_reflect(prefab.data.reflect_type_path().to_owned());
/// }
/// ```
fn remove_reflect(&mut self, component_type_path: impl Into<Cow<'static, str>>) -> &mut Self;
/// Same as [`remove_reflect`](ReflectCommandExt::remove_reflect), but using the `T` resource as type registry instead of
/// `AppTypeRegistry`.
fn remove_reflect_with_registry<T: Resource + AsRef<TypeRegistry>>(
&mut self,
component_type_path: impl Into<Cow<'static, str>>,
) -> &mut Self;
}
impl ReflectCommandExt for EntityCommands<'_> {
fn insert_reflect(&mut self, component: Box<dyn PartialReflect>) -> &mut Self {
self.queue(move |mut entity: EntityWorldMut| {
entity.insert_reflect(component);
})
}
fn insert_reflect_with_registry<T: Resource + AsRef<TypeRegistry>>(
&mut self,
component: Box<dyn PartialReflect>,
) -> &mut Self {
self.queue(move |mut entity: EntityWorldMut| {
entity.insert_reflect_with_registry::<T>(component);
})
}
fn remove_reflect(&mut self, component_type_path: impl Into<Cow<'static, str>>) -> &mut Self {
let component_type_path: Cow<'static, str> = component_type_path.into();
self.queue(move |mut entity: EntityWorldMut| {
entity.remove_reflect(component_type_path);
})
}
fn remove_reflect_with_registry<T: Resource + AsRef<TypeRegistry>>(
&mut self,
component_type_path: impl Into<Cow<'static, str>>,
) -> &mut Self {
let component_type_path: Cow<'static, str> = component_type_path.into();
self.queue(move |mut entity: EntityWorldMut| {
entity.remove_reflect_with_registry::<T>(component_type_path);
})
}
}
impl<'w> EntityWorldMut<'w> {
/// Adds the given boxed reflect component or bundle to the entity using the reflection data in
/// [`AppTypeRegistry`].
///
/// This will overwrite any previous component(s) of the same type.
///
/// # Panics
///
/// - If the entity has been despawned while this `EntityWorldMut` is still alive.
/// - If [`AppTypeRegistry`] does not have the reflection data for the given
/// [`Component`](crate::component::Component) or [`Bundle`](crate::bundle::Bundle).
/// - If the component or bundle data is invalid. See [`PartialReflect::apply`] for further details.
/// - If [`AppTypeRegistry`] is not present in the [`World`](crate::world::World).
///
/// # Note
///
/// Prefer to use the typed [`EntityWorldMut::insert`] if possible. Adding a reflected component
/// is much slower.
pub fn insert_reflect(&mut self, component: Box<dyn PartialReflect>) -> &mut Self {
self.assert_not_despawned();
self.resource_scope(|entity, registry: Mut<AppTypeRegistry>| {
let type_registry = ®istry.as_ref().read();
insert_reflect_with_registry_ref(entity, type_registry, component);
});
self
}
/// Same as [`insert_reflect`](EntityWorldMut::insert_reflect), but using
/// the `T` resource as type registry instead of [`AppTypeRegistry`].
///
/// This will overwrite any previous component(s) of the same type.
///
/// # Panics
///
/// - If the entity has been despawned while this `EntityWorldMut` is still alive.
/// - If the given [`Resource`] does not have the reflection data for the given
/// [`Component`](crate::component::Component) or [`Bundle`](crate::bundle::Bundle).
/// - If the component or bundle data is invalid. See [`PartialReflect::apply`] for further details.
/// - If the given [`Resource`] is not present in the [`World`](crate::world::World).
pub fn insert_reflect_with_registry<T: Resource + AsRef<TypeRegistry>>(
&mut self,
component: Box<dyn PartialReflect>,
) -> &mut Self {
self.assert_not_despawned();
self.resource_scope(|entity, registry: Mut<T>| {
let type_registry = registry.as_ref().as_ref();
insert_reflect_with_registry_ref(entity, type_registry, component);
});
self
}
/// Removes from the entity the component or bundle with the given type path registered in [`AppTypeRegistry`].
///
/// If the type is a bundle, it will remove any components in that bundle regardless if the entity
/// contains all the components.
///
/// Does nothing if the type is a component and the entity does not have a component of the same type,
/// if the type is a bundle and the entity does not contain any of the components in the bundle,
/// or if [`AppTypeRegistry`] does not contain the reflection data for the given component.
///
/// # Panics
///
/// - If the entity has been despawned while this `EntityWorldMut` is still alive.
/// - If [`AppTypeRegistry`] is not present in the [`World`](crate::world::World).
///
/// # Note
///
/// Prefer to use the typed [`EntityCommands::remove`] if possible. Removing a reflected component
/// is much slower.
pub fn remove_reflect(&mut self, component_type_path: Cow<'static, str>) -> &mut Self {
self.assert_not_despawned();
self.resource_scope(|entity, registry: Mut<AppTypeRegistry>| {
let type_registry = ®istry.as_ref().read();
remove_reflect_with_registry_ref(entity, type_registry, component_type_path);
});
self
}
/// Same as [`remove_reflect`](EntityWorldMut::remove_reflect), but using
/// the `T` resource as type registry instead of `AppTypeRegistry`.
///
/// If the given type is a bundle, it will remove any components in that bundle regardless if the entity
/// contains all the components.
///
/// Does nothing if the type is a component and the entity does not have a component of the same type,
/// if the type is a bundle and the entity does not contain any of the components in the bundle,
/// or if [`AppTypeRegistry`] does not contain the reflection data for the given component.
///
/// # Panics
///
/// - If the entity has been despawned while this `EntityWorldMut` is still alive.
/// - If [`AppTypeRegistry`] is not present in the [`World`](crate::world::World).
pub fn remove_reflect_with_registry<T: Resource + AsRef<TypeRegistry>>(
&mut self,
component_type_path: Cow<'static, str>,
) -> &mut Self {
self.assert_not_despawned();
self.resource_scope(|entity, registry: Mut<T>| {
let type_registry = registry.as_ref().as_ref();
remove_reflect_with_registry_ref(entity, type_registry, component_type_path);
});
self
}
}
/// Helper function to add a reflect component or bundle to a given entity
fn insert_reflect_with_registry_ref(
entity: &mut EntityWorldMut,
type_registry: &TypeRegistry,
component: Box<dyn PartialReflect>,
) {
let type_info = component
.get_represented_type_info()
.expect("component should represent a type.");
let type_path = type_info.type_path();
let Some(type_registration) = type_registry.get(type_info.type_id()) else {
panic!("`{type_path}` should be registered in type registry via `App::register_type<{type_path}>`");
};
if let Some(reflect_component) = type_registration.data::<ReflectComponent>() {
reflect_component.insert(entity, component.as_partial_reflect(), type_registry);
} else if let Some(reflect_bundle) = type_registration.data::<ReflectBundle>() {
reflect_bundle.insert(entity, component.as_partial_reflect(), type_registry);
} else {
panic!("`{type_path}` should have #[reflect(Component)] or #[reflect(Bundle)]");
}
}
/// Helper function to remove a reflect component or bundle from a given entity
fn remove_reflect_with_registry_ref(
entity: &mut EntityWorldMut,
type_registry: &TypeRegistry,
component_type_path: Cow<'static, str>,
) {
let Some(type_registration) = type_registry.get_with_type_path(&component_type_path) else {
return;
};
if let Some(reflect_component) = type_registration.data::<ReflectComponent>() {
reflect_component.remove(entity);
} else if let Some(reflect_bundle) = type_registration.data::<ReflectBundle>() {
reflect_bundle.remove(entity);
}
}
#[cfg(test)]
mod tests {
use crate::{
bundle::Bundle,
component::Component,
prelude::{AppTypeRegistry, ReflectComponent},
reflect::{ReflectBundle, ReflectCommandExt},
system::{Commands, SystemState},
world::World,
};
use alloc::{borrow::ToOwned, boxed::Box};
use bevy_ecs_macros::Resource;
use bevy_reflect::{PartialReflect, Reflect, TypeRegistry};
#[derive(Resource)]
struct TypeRegistryResource {
type_registry: TypeRegistry,
}
impl AsRef<TypeRegistry> for TypeRegistryResource {
fn as_ref(&self) -> &TypeRegistry {
&self.type_registry
}
}
#[derive(Component, Reflect, Default, PartialEq, Eq, Debug)]
#[reflect(Component)]
struct ComponentA(u32);
#[derive(Component, Reflect, Default, PartialEq, Eq, Debug)]
#[reflect(Component)]
struct ComponentB(u32);
#[derive(Bundle, Reflect, Default, Debug, PartialEq)]
#[reflect(Bundle)]
struct BundleA {
a: ComponentA,
b: ComponentB,
}
#[test]
fn insert_reflected() {
let mut world = World::new();
let type_registry = AppTypeRegistry::default();
{
let mut registry = type_registry.write();
registry.register::<ComponentA>();
registry.register_type_data::<ComponentA, ReflectComponent>();
}
world.insert_resource(type_registry);
let mut system_state: SystemState<Commands> = SystemState::new(&mut world);
let mut commands = system_state.get_mut(&mut world);
let entity = commands.spawn_empty().id();
let entity2 = commands.spawn_empty().id();
let entity3 = commands.spawn_empty().id();
let boxed_reflect_component_a = Box::new(ComponentA(916)) as Box<dyn PartialReflect>;
let boxed_reflect_component_a_clone = boxed_reflect_component_a.reflect_clone().unwrap();
let boxed_reflect_component_a_dynamic = boxed_reflect_component_a.to_dynamic();
commands
.entity(entity)
.insert_reflect(boxed_reflect_component_a);
commands
.entity(entity2)
.insert_reflect(boxed_reflect_component_a_clone.into_partial_reflect());
commands
.entity(entity3)
.insert_reflect(boxed_reflect_component_a_dynamic);
system_state.apply(&mut world);
assert_eq!(
world.entity(entity).get::<ComponentA>(),
world.entity(entity2).get::<ComponentA>(),
);
assert_eq!(
world.entity(entity).get::<ComponentA>(),
world.entity(entity3).get::<ComponentA>(),
);
}
#[test]
fn insert_reflected_with_registry() {
let mut world = World::new();
let mut type_registry = TypeRegistryResource {
type_registry: TypeRegistry::new(),
};
type_registry.type_registry.register::<ComponentA>();
type_registry
.type_registry
.register_type_data::<ComponentA, ReflectComponent>();
world.insert_resource(type_registry);
let mut system_state: SystemState<Commands> = SystemState::new(&mut world);
let mut commands = system_state.get_mut(&mut world);
let entity = commands.spawn_empty().id();
let boxed_reflect_component_a = Box::new(ComponentA(916)) as Box<dyn PartialReflect>;
commands
.entity(entity)
.insert_reflect_with_registry::<TypeRegistryResource>(boxed_reflect_component_a);
system_state.apply(&mut world);
assert_eq!(
world.entity(entity).get::<ComponentA>(),
Some(&ComponentA(916))
);
}
#[test]
fn remove_reflected() {
let mut world = World::new();
let type_registry = AppTypeRegistry::default();
{
let mut registry = type_registry.write();
registry.register::<ComponentA>();
registry.register_type_data::<ComponentA, ReflectComponent>();
}
world.insert_resource(type_registry);
let mut system_state: SystemState<Commands> = SystemState::new(&mut world);
let mut commands = system_state.get_mut(&mut world);
let entity = commands.spawn(ComponentA(0)).id();
let boxed_reflect_component_a = Box::new(ComponentA(916)) as Box<dyn Reflect>;
commands
.entity(entity)
.remove_reflect(boxed_reflect_component_a.reflect_type_path().to_owned());
system_state.apply(&mut world);
assert_eq!(world.entity(entity).get::<ComponentA>(), None);
}
#[test]
fn remove_reflected_with_registry() {
let mut world = World::new();
let mut type_registry = TypeRegistryResource {
type_registry: TypeRegistry::new(),
};
type_registry.type_registry.register::<ComponentA>();
type_registry
.type_registry
.register_type_data::<ComponentA, ReflectComponent>();
world.insert_resource(type_registry);
let mut system_state: SystemState<Commands> = SystemState::new(&mut world);
let mut commands = system_state.get_mut(&mut world);
let entity = commands.spawn(ComponentA(0)).id();
let boxed_reflect_component_a = Box::new(ComponentA(916)) as Box<dyn Reflect>;
commands
.entity(entity)
.remove_reflect_with_registry::<TypeRegistryResource>(
boxed_reflect_component_a.reflect_type_path().to_owned(),
);
system_state.apply(&mut world);
assert_eq!(world.entity(entity).get::<ComponentA>(), None);
}
#[test]
fn insert_reflect_bundle() {
let mut world = World::new();
let type_registry = AppTypeRegistry::default();
{
let mut registry = type_registry.write();
registry.register::<BundleA>();
registry.register_type_data::<BundleA, ReflectBundle>();
}
world.insert_resource(type_registry);
let mut system_state: SystemState<Commands> = SystemState::new(&mut world);
let mut commands = system_state.get_mut(&mut world);
let entity = commands.spawn_empty().id();
let bundle = Box::new(BundleA {
a: ComponentA(31),
b: ComponentB(20),
}) as Box<dyn PartialReflect>;
commands.entity(entity).insert_reflect(bundle);
system_state.apply(&mut world);
assert_eq!(world.get::<ComponentA>(entity), Some(&ComponentA(31)));
assert_eq!(world.get::<ComponentB>(entity), Some(&ComponentB(20)));
}
#[test]
fn insert_reflect_bundle_with_registry() {
let mut world = World::new();
let mut type_registry = TypeRegistryResource {
type_registry: TypeRegistry::new(),
};
type_registry.type_registry.register::<BundleA>();
type_registry
.type_registry
.register_type_data::<BundleA, ReflectBundle>();
world.insert_resource(type_registry);
let mut system_state: SystemState<Commands> = SystemState::new(&mut world);
let mut commands = system_state.get_mut(&mut world);
let entity = commands.spawn_empty().id();
let bundle = Box::new(BundleA {
a: ComponentA(31),
b: ComponentB(20),
}) as Box<dyn PartialReflect>;
commands
.entity(entity)
.insert_reflect_with_registry::<TypeRegistryResource>(bundle);
system_state.apply(&mut world);
assert_eq!(world.get::<ComponentA>(entity), Some(&ComponentA(31)));
assert_eq!(world.get::<ComponentB>(entity), Some(&ComponentB(20)));
}
#[test]
fn remove_reflected_bundle() {
let mut world = World::new();
let type_registry = AppTypeRegistry::default();
{
let mut registry = type_registry.write();
registry.register::<BundleA>();
registry.register_type_data::<BundleA, ReflectBundle>();
}
world.insert_resource(type_registry);
let mut system_state: SystemState<Commands> = SystemState::new(&mut world);
let mut commands = system_state.get_mut(&mut world);
let entity = commands
.spawn(BundleA {
a: ComponentA(31),
b: ComponentB(20),
})
.id();
let boxed_reflect_bundle_a = Box::new(BundleA {
a: ComponentA(1),
b: ComponentB(23),
}) as Box<dyn Reflect>;
commands
.entity(entity)
.remove_reflect(boxed_reflect_bundle_a.reflect_type_path().to_owned());
system_state.apply(&mut world);
assert_eq!(world.entity(entity).get::<ComponentA>(), None);
assert_eq!(world.entity(entity).get::<ComponentB>(), None);
}
#[test]
fn remove_reflected_bundle_with_registry() {
let mut world = World::new();
let mut type_registry = TypeRegistryResource {
type_registry: TypeRegistry::new(),
};
type_registry.type_registry.register::<BundleA>();
type_registry
.type_registry
.register_type_data::<BundleA, ReflectBundle>();
world.insert_resource(type_registry);
let mut system_state: SystemState<Commands> = SystemState::new(&mut world);
let mut commands = system_state.get_mut(&mut world);
let entity = commands
.spawn(BundleA {
a: ComponentA(31),
b: ComponentB(20),
})
.id();
let boxed_reflect_bundle_a = Box::new(BundleA {
a: ComponentA(1),
b: ComponentB(23),
}) as Box<dyn Reflect>;
commands
.entity(entity)
.remove_reflect_with_registry::<TypeRegistryResource>(
boxed_reflect_bundle_a.reflect_type_path().to_owned(),
);
system_state.apply(&mut world);
assert_eq!(world.entity(entity).get::<ComponentA>(), None);
assert_eq!(world.entity(entity).get::<ComponentB>(), None);
}
}
| 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/reflect/from_world.rs | crates/bevy_ecs/src/reflect/from_world.rs | //! Definitions for [`FromWorld`] reflection.
//! This allows creating instances of types that are known only at runtime and
//! require an `&mut World` to be initialized.
//!
//! This module exports two types: [`ReflectFromWorldFns`] and [`ReflectFromWorld`].
//!
//! Same as [`component`](`super::component`), but for [`FromWorld`].
use alloc::boxed::Box;
use bevy_reflect::{FromType, Reflect};
use crate::world::{FromWorld, World};
/// A struct used to operate on the reflected [`FromWorld`] trait of a type.
///
/// A [`ReflectFromWorld`] for type `T` can be obtained via
/// [`bevy_reflect::TypeRegistration::data`].
#[derive(Clone)]
pub struct ReflectFromWorld(ReflectFromWorldFns);
/// The raw function pointers needed to make up a [`ReflectFromWorld`].
#[derive(Clone)]
pub struct ReflectFromWorldFns {
/// Function pointer implementing [`ReflectFromWorld::from_world()`].
pub from_world: fn(&mut World) -> Box<dyn Reflect>,
}
impl ReflectFromWorldFns {
/// Get the default set of [`ReflectFromWorldFns`] for a specific type using its
/// [`FromType`] implementation.
///
/// This is useful if you want to start with the default implementation before overriding some
/// of the functions to create a custom implementation.
pub fn new<T: Reflect + FromWorld>() -> Self {
<ReflectFromWorld as FromType<T>>::from_type().0
}
}
impl ReflectFromWorld {
/// Constructs default reflected [`FromWorld`] from world using [`from_world()`](FromWorld::from_world).
pub fn from_world(&self, world: &mut World) -> Box<dyn Reflect> {
(self.0.from_world)(world)
}
/// Create a custom implementation of [`ReflectFromWorld`].
///
/// This is an advanced feature,
/// useful for scripting implementations,
/// that should not be used by most users
/// unless you know what you are doing.
///
/// Usually you should derive [`Reflect`] and add the `#[reflect(FromWorld)]` bundle
/// to generate a [`ReflectFromWorld`] implementation automatically.
///
/// See [`ReflectFromWorldFns`] for more information.
pub fn new(fns: ReflectFromWorldFns) -> Self {
Self(fns)
}
/// The underlying function pointers implementing methods on `ReflectFromWorld`.
///
/// This is useful when you want to keep track locally of an individual
/// function pointer.
///
/// Calling [`TypeRegistry::get`] followed by
/// [`TypeRegistration::data::<ReflectFromWorld>`] can be costly if done several
/// times per frame. Consider cloning [`ReflectFromWorld`] and keeping it
/// between frames, cloning a `ReflectFromWorld` is very cheap.
///
/// If you only need a subset of the methods on `ReflectFromWorld`,
/// use `fn_pointers` to get the underlying [`ReflectFromWorldFns`]
/// and copy the subset of function pointers you care about.
///
/// [`TypeRegistration::data::<ReflectFromWorld>`]: bevy_reflect::TypeRegistration::data
/// [`TypeRegistry::get`]: bevy_reflect::TypeRegistry::get
pub fn fn_pointers(&self) -> &ReflectFromWorldFns {
&self.0
}
}
impl<B: Reflect + FromWorld> FromType<B> for ReflectFromWorld {
fn from_type() -> Self {
ReflectFromWorld(ReflectFromWorldFns {
from_world: |world| Box::new(B::from_world(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/reflect/mod.rs | crates/bevy_ecs/src/reflect/mod.rs | //! Types that enable reflection support.
use core::{
any::TypeId,
ops::{Deref, DerefMut},
};
use crate::{resource::Resource, world::World};
use bevy_reflect::{
std_traits::ReflectDefault, PartialReflect, Reflect, ReflectFromReflect, TypePath,
TypeRegistry, TypeRegistryArc,
};
mod bundle;
mod component;
mod entity_commands;
mod event;
mod from_world;
mod map_entities;
mod resource;
use bevy_utils::prelude::DebugName;
pub use bundle::{ReflectBundle, ReflectBundleFns};
pub use component::{ReflectComponent, ReflectComponentFns};
pub use entity_commands::ReflectCommandExt;
pub use event::{ReflectEvent, ReflectEventFns};
pub use from_world::{ReflectFromWorld, ReflectFromWorldFns};
pub use map_entities::ReflectMapEntities;
pub use resource::{ReflectResource, ReflectResourceFns};
/// A [`Resource`] storing [`TypeRegistry`] for
/// type registrations relevant to a whole app.
#[derive(Resource, Clone, Default)]
pub struct AppTypeRegistry(pub TypeRegistryArc);
impl Deref for AppTypeRegistry {
type Target = TypeRegistryArc;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for AppTypeRegistry {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl AppTypeRegistry {
/// Creates [`AppTypeRegistry`] and automatically registers all types deriving [`Reflect`].
///
/// See [`TypeRegistry::register_derived_types`] for more details.
#[cfg(feature = "reflect_auto_register")]
pub fn new_with_derived_types() -> Self {
let app_registry = AppTypeRegistry::default();
app_registry.write().register_derived_types();
app_registry
}
}
/// A [`Resource`] storing [`FunctionRegistry`] for
/// function registrations relevant to a whole app.
///
/// [`FunctionRegistry`]: bevy_reflect::func::FunctionRegistry
#[cfg(feature = "reflect_functions")]
#[derive(Resource, Clone, Default)]
pub struct AppFunctionRegistry(pub bevy_reflect::func::FunctionRegistryArc);
#[cfg(feature = "reflect_functions")]
impl Deref for AppFunctionRegistry {
type Target = bevy_reflect::func::FunctionRegistryArc;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "reflect_functions")]
impl DerefMut for AppFunctionRegistry {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
/// Creates a `T` from a `&dyn PartialReflect`.
///
/// This will try the following strategies, in this order:
///
/// - use the reflected `FromReflect`, if it's present and doesn't fail;
/// - use the reflected `Default`, if it's present, and then call `apply` on the result;
/// - use the reflected `FromWorld`, just like the `Default`.
///
/// The first one that is present and doesn't fail will be used.
///
/// # Panics
///
/// If any strategy produces a `Box<dyn Reflect>` that doesn't store a value of type `T`
/// this method will panic.
///
/// If none of the strategies succeed, this method will panic.
pub fn from_reflect_with_fallback<T: Reflect + TypePath>(
reflected: &dyn PartialReflect,
world: &mut World,
registry: &TypeRegistry,
) -> T {
#[inline(never)]
fn type_erased(
reflected: &dyn PartialReflect,
world: &mut World,
registry: &TypeRegistry,
id: TypeId,
name: DebugName,
) -> alloc::boxed::Box<dyn core::any::Any> {
// First, try `FromReflect`. This is handled differently from the others because
// it doesn't need a subsequent `apply` and may fail.
// If it fails it's ok, we can continue checking `Default` and `FromWorld`.
let (value, source) = if let Some(value) = registry
.get_type_data::<ReflectFromReflect>(id)
.and_then(|reflect_from_reflect| reflect_from_reflect.from_reflect(reflected))
{
(value, "FromReflect")
}
// Create an instance of `T` using either the reflected `Default` or `FromWorld`.
else if let Some(reflect_default) = registry.get_type_data::<ReflectDefault>(id) {
let mut value = reflect_default.default();
value.apply(reflected);
(value, "Default")
} else if let Some(reflect_from_world) = registry.get_type_data::<ReflectFromWorld>(id) {
let mut value = reflect_from_world.from_world(world);
value.apply(reflected);
(value, "FromWorld")
} else {
panic!(
"Couldn't create an instance of `{name}` using the reflected `FromReflect`, \
`Default` or `FromWorld` traits. Are you perhaps missing a `#[reflect(Default)]` \
or `#[reflect(FromWorld)]`?",
);
};
assert_eq!(
value.as_any().type_id(),
id,
"The registration for the reflected `{source}` trait for the type `{name}` produced \
a value of a different type",
);
value
}
*type_erased(
reflected,
world,
registry,
TypeId::of::<T>(),
// FIXME: once we have unique reflect, use `TypePath`.
DebugName::type_name::<T>(),
)
.downcast::<T>()
.unwrap()
}
| 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/reflect/map_entities.rs | crates/bevy_ecs/src/reflect/map_entities.rs | use crate::entity::{EntityMapper, MapEntities};
use bevy_reflect::{FromReflect, FromType, PartialReflect};
/// For a specific type of value, this maps any fields with values of type [`Entity`] to a new world.
///
/// Since a given `Entity` ID is only valid for the world it came from, when performing deserialization
/// any stored IDs need to be re-allocated in the destination world.
///
/// See [`EntityMapper`] and [`MapEntities`] for more information.
///
/// [`Entity`]: crate::entity::Entity
/// [`EntityMapper`]: crate::entity::EntityMapper
#[derive(Clone)]
pub struct ReflectMapEntities {
map_entities: fn(&mut dyn PartialReflect, &mut dyn EntityMapper),
}
impl ReflectMapEntities {
/// A general method for remapping entities in a reflected value via an [`EntityMapper`].
///
/// # Panics
/// Panics if the type of the reflected value doesn't match.
pub fn map_entities(&self, reflected: &mut dyn PartialReflect, mapper: &mut dyn EntityMapper) {
(self.map_entities)(reflected, mapper);
}
}
impl<C: FromReflect + MapEntities> FromType<C> for ReflectMapEntities {
fn from_type() -> Self {
ReflectMapEntities {
map_entities: |reflected, mut mapper| {
let mut concrete = C::from_reflect(reflected).expect("reflected type should match");
concrete.map_entities(&mut mapper);
reflected.apply(&concrete);
},
}
}
}
| 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/reflect/component.rs | crates/bevy_ecs/src/reflect/component.rs | //! Definitions for [`Component`] reflection.
//! This allows inserting, updating, removing and generally interacting with components
//! whose types are only known at runtime.
//!
//! This module exports two types: [`ReflectComponentFns`] and [`ReflectComponent`].
//!
//! # Architecture
//!
//! [`ReflectComponent`] wraps a [`ReflectComponentFns`]. In fact, each method on
//! [`ReflectComponent`] wraps a call to a function pointer field in `ReflectComponentFns`.
//!
//! ## Who creates `ReflectComponent`s?
//!
//! When a user adds the `#[reflect(Component)]` attribute to their `#[derive(Reflect)]`
//! type, it tells the derive macro for `Reflect` to add the following single line to its
//! [`get_type_registration`] method (see the relevant code[^1]).
//!
//! ```
//! # use bevy_reflect::{FromType, Reflect};
//! # use bevy_ecs::prelude::{ReflectComponent, Component};
//! # #[derive(Default, Reflect, Component)]
//! # struct A;
//! # impl A {
//! # fn foo() {
//! # let mut registration = bevy_reflect::TypeRegistration::of::<A>();
//! registration.insert::<ReflectComponent>(FromType::<Self>::from_type());
//! # }
//! # }
//! ```
//!
//! This line adds a `ReflectComponent` to the registration data for the type in question.
//! The user can access the `ReflectComponent` for type `T` through the type registry,
//! as per the `trait_reflection.rs` example.
//!
//! The `FromType::<Self>::from_type()` in the previous line calls the `FromType<C>`
//! implementation of `ReflectComponent`.
//!
//! The `FromType<C>` impl creates a function per field of [`ReflectComponentFns`].
//! In those functions, we call generic methods on [`World`] and [`EntityWorldMut`].
//!
//! The result is a `ReflectComponent` completely independent of `C`, yet capable
//! of using generic ECS methods such as `entity.get::<C>()` to get `&dyn Reflect`
//! with underlying type `C`, without the `C` appearing in the type signature.
//!
//! ## A note on code generation
//!
//! A downside of this approach is that monomorphized code (ie: concrete code
//! for generics) is generated **unconditionally**, regardless of whether it ends
//! up used or not.
//!
//! Adding `N` fields on `ReflectComponentFns` will generate `N Γ M` additional
//! functions, where `M` is how many types derive `#[reflect(Component)]`.
//!
//! Those functions will increase the size of the final app binary.
//!
//! [^1]: `crates/bevy_reflect/bevy_reflect_derive/src/registration.rs`
//!
//! [`get_type_registration`]: bevy_reflect::GetTypeRegistration::get_type_registration
use super::from_reflect_with_fallback;
use crate::{
change_detection::Mut,
component::{ComponentId, ComponentMutability},
entity::{Entity, EntityMapper},
prelude::Component,
relationship::RelationshipHookMode,
world::{
unsafe_world_cell::UnsafeEntityCell, EntityMut, EntityWorldMut, FilteredEntityMut,
FilteredEntityRef, World,
},
};
use bevy_reflect::{FromReflect, FromType, PartialReflect, Reflect, TypePath, TypeRegistry};
use bevy_utils::prelude::DebugName;
/// A struct used to operate on reflected [`Component`] trait of a type.
///
/// A [`ReflectComponent`] for type `T` can be obtained via
/// [`bevy_reflect::TypeRegistration::data`].
#[derive(Clone)]
pub struct ReflectComponent(ReflectComponentFns);
/// The raw function pointers needed to make up a [`ReflectComponent`].
///
/// This is used when creating custom implementations of [`ReflectComponent`] with
/// [`ReflectComponent::new()`].
///
/// > **Note:**
/// > Creating custom implementations of [`ReflectComponent`] is an advanced feature that most users
/// > will not need.
/// > Usually a [`ReflectComponent`] is created for a type by deriving [`Reflect`]
/// > and adding the `#[reflect(Component)]` attribute.
/// > After adding the component to the [`TypeRegistry`],
/// > its [`ReflectComponent`] can then be retrieved when needed.
///
/// Creating a custom [`ReflectComponent`] may be useful if you need to create new component types
/// at runtime, for example, for scripting implementations.
///
/// By creating a custom [`ReflectComponent`] and inserting it into a type's
/// [`TypeRegistration`][bevy_reflect::TypeRegistration],
/// you can modify the way that reflected components of that type will be inserted into the Bevy
/// world.
#[derive(Clone)]
pub struct ReflectComponentFns {
/// Function pointer implementing [`ReflectComponent::insert()`].
pub insert: fn(&mut EntityWorldMut, &dyn PartialReflect, &TypeRegistry),
/// Function pointer implementing [`ReflectComponent::apply()`].
pub apply: fn(EntityMut, &dyn PartialReflect),
/// Function pointer implementing [`ReflectComponent::apply_or_insert_mapped()`].
pub apply_or_insert_mapped: fn(
&mut EntityWorldMut,
&dyn PartialReflect,
&TypeRegistry,
&mut dyn EntityMapper,
RelationshipHookMode,
),
/// Function pointer implementing [`ReflectComponent::remove()`].
pub remove: fn(&mut EntityWorldMut),
/// Function pointer implementing [`ReflectComponent::contains()`].
pub contains: fn(FilteredEntityRef) -> bool,
/// Function pointer implementing [`ReflectComponent::reflect()`].
pub reflect: for<'w> fn(FilteredEntityRef<'w, '_>) -> Option<&'w dyn Reflect>,
/// Function pointer implementing [`ReflectComponent::reflect_mut()`].
pub reflect_mut: for<'w> fn(FilteredEntityMut<'w, '_>) -> Option<Mut<'w, dyn Reflect>>,
/// Function pointer implementing [`ReflectComponent::map_entities()`].
pub map_entities: fn(&mut dyn Reflect, &mut dyn EntityMapper),
/// Function pointer implementing [`ReflectComponent::reflect_unchecked_mut()`].
///
/// # Safety
/// The function may only be called with an [`UnsafeEntityCell`] that can be used to mutably access the relevant component on the given entity.
pub reflect_unchecked_mut: unsafe fn(UnsafeEntityCell<'_>) -> Option<Mut<'_, dyn Reflect>>,
/// Function pointer implementing [`ReflectComponent::copy()`].
pub copy: fn(&World, &mut World, Entity, Entity, &TypeRegistry),
/// Function pointer implementing [`ReflectComponent::register_component()`].
pub register_component: fn(&mut World) -> ComponentId,
}
impl ReflectComponentFns {
/// Get the default set of [`ReflectComponentFns`] for a specific component type using its
/// [`FromType`] implementation.
///
/// This is useful if you want to start with the default implementation before overriding some
/// of the functions to create a custom implementation.
pub fn new<T: Component + FromReflect + TypePath>() -> Self {
<ReflectComponent as FromType<T>>::from_type().0
}
}
impl ReflectComponent {
/// Insert a reflected [`Component`] into the entity like [`insert()`](EntityWorldMut::insert).
pub fn insert(
&self,
entity: &mut EntityWorldMut,
component: &dyn PartialReflect,
registry: &TypeRegistry,
) {
(self.0.insert)(entity, component, registry);
}
/// Uses reflection to set the value of this [`Component`] type in the entity to the given value.
///
/// # Panics
///
/// Panics if there is no [`Component`] of the given type.
///
/// Will also panic if [`Component`] is immutable.
pub fn apply<'a>(&self, entity: impl Into<EntityMut<'a>>, component: &dyn PartialReflect) {
(self.0.apply)(entity.into(), component);
}
/// Uses reflection to set the value of this [`Component`] type in the entity to the given value or insert a new one if it does not exist.
///
/// # Panics
///
/// Panics if [`Component`] is immutable.
pub fn apply_or_insert_mapped(
&self,
entity: &mut EntityWorldMut,
component: &dyn PartialReflect,
registry: &TypeRegistry,
map: &mut dyn EntityMapper,
relationship_hook_mode: RelationshipHookMode,
) {
(self.0.apply_or_insert_mapped)(entity, component, registry, map, relationship_hook_mode);
}
/// Removes this [`Component`] type from the entity. Does nothing if it doesn't exist.
pub fn remove(&self, entity: &mut EntityWorldMut) {
(self.0.remove)(entity);
}
/// Returns whether entity contains this [`Component`]
pub fn contains<'w, 's>(&self, entity: impl Into<FilteredEntityRef<'w, 's>>) -> bool {
(self.0.contains)(entity.into())
}
/// Gets the value of this [`Component`] type from the entity as a reflected reference.
pub fn reflect<'w, 's>(
&self,
entity: impl Into<FilteredEntityRef<'w, 's>>,
) -> Option<&'w dyn Reflect> {
(self.0.reflect)(entity.into())
}
/// Gets the value of this [`Component`] type from the entity as a mutable reflected reference.
///
/// # Panics
///
/// Panics if [`Component`] is immutable.
pub fn reflect_mut<'w, 's>(
&self,
entity: impl Into<FilteredEntityMut<'w, 's>>,
) -> Option<Mut<'w, dyn Reflect>> {
(self.0.reflect_mut)(entity.into())
}
/// # Safety
/// This method does not prevent you from having two mutable pointers to the same data,
/// violating Rust's aliasing rules. To avoid this:
/// * Only call this method with a [`UnsafeEntityCell`] that may be used to mutably access the component on the entity `entity`
/// * Don't call this method more than once in the same scope for a given [`Component`].
///
/// # Panics
///
/// Panics if [`Component`] is immutable.
pub unsafe fn reflect_unchecked_mut<'a>(
&self,
entity: UnsafeEntityCell<'a>,
) -> Option<Mut<'a, dyn Reflect>> {
// SAFETY: safety requirements deferred to caller
unsafe { (self.0.reflect_unchecked_mut)(entity) }
}
/// Gets the value of this [`Component`] type from entity from `source_world` and [applies](Self::apply()) it to the value of this [`Component`] type in entity in `destination_world`.
///
/// # Panics
///
/// Panics if there is no [`Component`] of the given type or either entity does not exist.
pub fn copy(
&self,
source_world: &World,
destination_world: &mut World,
source_entity: Entity,
destination_entity: Entity,
registry: &TypeRegistry,
) {
(self.0.copy)(
source_world,
destination_world,
source_entity,
destination_entity,
registry,
);
}
/// Register the type of this [`Component`] in [`World`], returning its [`ComponentId`].
pub fn register_component(&self, world: &mut World) -> ComponentId {
(self.0.register_component)(world)
}
/// Create a custom implementation of [`ReflectComponent`].
///
/// This is an advanced feature,
/// useful for scripting implementations,
/// that should not be used by most users
/// unless you know what you are doing.
///
/// Usually you should derive [`Reflect`] and add the `#[reflect(Component)]` component
/// to generate a [`ReflectComponent`] implementation automatically.
///
/// See [`ReflectComponentFns`] for more information.
pub fn new(fns: ReflectComponentFns) -> Self {
Self(fns)
}
/// The underlying function pointers implementing methods on `ReflectComponent`.
///
/// This is useful when you want to keep track locally of an individual
/// function pointer.
///
/// Calling [`TypeRegistry::get`] followed by
/// [`TypeRegistration::data::<ReflectComponent>`] can be costly if done several
/// times per frame. Consider cloning [`ReflectComponent`] and keeping it
/// between frames, cloning a `ReflectComponent` is very cheap.
///
/// If you only need a subset of the methods on `ReflectComponent`,
/// use `fn_pointers` to get the underlying [`ReflectComponentFns`]
/// and copy the subset of function pointers you care about.
///
/// [`TypeRegistration::data::<ReflectComponent>`]: bevy_reflect::TypeRegistration::data
/// [`TypeRegistry::get`]: bevy_reflect::TypeRegistry::get
pub fn fn_pointers(&self) -> &ReflectComponentFns {
&self.0
}
/// Calls a dynamic version of [`Component::map_entities`].
pub fn map_entities(&self, component: &mut dyn Reflect, func: &mut dyn EntityMapper) {
(self.0.map_entities)(component, func);
}
}
impl<C: Component + Reflect + TypePath> FromType<C> for ReflectComponent {
fn from_type() -> Self {
// TODO: Currently we panic if a component is immutable and you use
// reflection to mutate it. Perhaps the mutation methods should be fallible?
ReflectComponent(ReflectComponentFns {
insert: |entity, reflected_component, registry| {
let component = entity.world_scope(|world| {
from_reflect_with_fallback::<C>(reflected_component, world, registry)
});
entity.insert(component);
},
apply: |mut entity, reflected_component| {
if !C::Mutability::MUTABLE {
let name = DebugName::type_name::<C>();
let name = name.shortname();
panic!("Cannot call `ReflectComponent::apply` on component {name}. It is immutable, and cannot modified through reflection");
}
// SAFETY: guard ensures `C` is a mutable component
let mut component = unsafe { entity.get_mut_assume_mutable::<C>() }.unwrap();
component.apply(reflected_component);
},
apply_or_insert_mapped: |entity,
reflected_component,
registry,
mut mapper,
relationship_hook_mode| {
if C::Mutability::MUTABLE {
// SAFETY: guard ensures `C` is a mutable component
if let Some(mut component) = unsafe { entity.get_mut_assume_mutable::<C>() } {
component.apply(reflected_component.as_partial_reflect());
C::map_entities(&mut component, &mut mapper);
} else {
let mut component = entity.world_scope(|world| {
from_reflect_with_fallback::<C>(reflected_component, world, registry)
});
C::map_entities(&mut component, &mut mapper);
entity
.insert_with_relationship_hook_mode(component, relationship_hook_mode);
}
} else {
let mut component = entity.world_scope(|world| {
from_reflect_with_fallback::<C>(reflected_component, world, registry)
});
C::map_entities(&mut component, &mut mapper);
entity.insert_with_relationship_hook_mode(component, relationship_hook_mode);
}
},
remove: |entity| {
entity.remove::<C>();
},
contains: |entity| entity.contains::<C>(),
copy: |source_world, destination_world, source_entity, destination_entity, registry| {
let source_component = source_world.get::<C>(source_entity).unwrap();
let destination_component =
from_reflect_with_fallback::<C>(source_component, destination_world, registry);
destination_world
.entity_mut(destination_entity)
.insert(destination_component);
},
reflect: |entity| entity.get::<C>().map(|c| c as &dyn Reflect),
reflect_mut: |entity| {
if !C::Mutability::MUTABLE {
let name = DebugName::type_name::<C>();
let name = name.shortname();
panic!("Cannot call `ReflectComponent::reflect_mut` on component {name}. It is immutable, and cannot modified through reflection");
}
// SAFETY: guard ensures `C` is a mutable component
unsafe {
entity
.into_mut_assume_mutable::<C>()
.map(|c| c.map_unchanged(|value| value as &mut dyn Reflect))
}
},
reflect_unchecked_mut: |entity| {
if !C::Mutability::MUTABLE {
let name = DebugName::type_name::<C>();
let name = name.shortname();
panic!("Cannot call `ReflectComponent::reflect_unchecked_mut` on component {name}. It is immutable, and cannot modified through reflection");
}
// SAFETY: reflect_unchecked_mut is an unsafe function pointer used by
// `reflect_unchecked_mut` which must be called with an UnsafeEntityCell with access to the component `C` on the `entity`
// guard ensures `C` is a mutable component
let c = unsafe { entity.get_mut_assume_mutable::<C>() };
c.map(|c| c.map_unchanged(|value| value as &mut dyn Reflect))
},
register_component: |world: &mut World| -> ComponentId {
world.register_component::<C>()
},
map_entities: |reflect: &mut dyn Reflect, mut mapper: &mut dyn EntityMapper| {
let component = reflect.downcast_mut::<C>().unwrap();
Component::map_entities(component, &mut mapper);
},
})
}
}
| 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/bundle/spawner.rs | crates/bevy_ecs/src/bundle/spawner.rs | use core::ptr::NonNull;
use bevy_ptr::{ConstNonNull, MovingPtr};
use crate::{
archetype::{Archetype, ArchetypeCreated, ArchetypeId, SpawnBundleStatus},
bundle::{Bundle, BundleId, BundleInfo, DynamicBundle, InsertMode},
change_detection::{MaybeLocation, Tick},
entity::{Entity, EntityAllocator, EntityLocation},
event::EntityComponentsTrigger,
lifecycle::{Add, Insert, ADD, INSERT},
relationship::RelationshipHookMode,
storage::Table,
world::{unsafe_world_cell::UnsafeWorldCell, World},
};
// SAFETY: We have exclusive world access so our pointers can't be invalidated externally
pub(crate) struct BundleSpawner<'w> {
world: UnsafeWorldCell<'w>,
bundle_info: ConstNonNull<BundleInfo>,
table: NonNull<Table>,
archetype: NonNull<Archetype>,
change_tick: Tick,
}
impl<'w> BundleSpawner<'w> {
#[inline]
pub fn new<T: Bundle>(world: &'w mut World, change_tick: Tick) -> Self {
let bundle_id = world.register_bundle_info::<T>();
// SAFETY: we initialized this bundle_id in `init_info`
unsafe { Self::new_with_id(world, bundle_id, change_tick) }
}
/// Creates a new [`BundleSpawner`].
///
/// # Safety
/// Caller must ensure that `bundle_id` exists in `world.bundles`
#[inline]
pub(crate) unsafe fn new_with_id(
world: &'w mut World,
bundle_id: BundleId,
change_tick: Tick,
) -> Self {
let bundle_info = world.bundles.get_unchecked(bundle_id);
let (new_archetype_id, is_new_created) = bundle_info.insert_bundle_into_archetype(
&mut world.archetypes,
&mut world.storages,
&world.components,
&world.observers,
ArchetypeId::EMPTY,
);
let archetype = &mut world.archetypes[new_archetype_id];
let table = &mut world.storages.tables[archetype.table_id()];
let spawner = Self {
bundle_info: bundle_info.into(),
table: table.into(),
archetype: archetype.into(),
change_tick,
world: world.as_unsafe_world_cell(),
};
if is_new_created {
spawner
.world
.into_deferred()
.trigger(ArchetypeCreated(new_archetype_id));
}
spawner
}
#[inline]
pub fn reserve_storage(&mut self, additional: usize) {
// SAFETY: There are no outstanding world references
let (archetype, table) = unsafe { (self.archetype.as_mut(), self.table.as_mut()) };
archetype.reserve(additional);
table.reserve(additional);
}
/// # Safety
/// - `entity` must be allocated (but non-existent),
/// - `T` must match this [`BundleSpawner`]'s type
/// - If `T::Effect: !NoBundleEffect.`, then [`apply_effect`] must be called exactly once on `bundle`
/// after this function returns before returning to safe code.
/// - The value pointed to by `bundle` must not be accessed for anything other than [`apply_effect`]
/// or dropped.
///
/// [`apply_effect`]: crate::bundle::DynamicBundle::apply_effect
#[inline]
#[track_caller]
pub unsafe fn spawn_at<T: DynamicBundle>(
&mut self,
entity: Entity,
bundle: MovingPtr<'_, T>,
caller: MaybeLocation,
) -> EntityLocation {
// SAFETY: We do not make any structural changes to the archetype graph through self.world so these pointers always remain valid
let bundle_info = self.bundle_info.as_ref();
let location = {
let table = self.table.as_mut();
let archetype = self.archetype.as_mut();
// SAFETY: Mutable references do not alias and will be dropped after this block
let (sparse_sets, entities) = {
let world = self.world.world_mut();
(&mut world.storages.sparse_sets, &mut world.entities)
};
let table_row = table.allocate(entity);
let location = archetype.allocate(entity, table_row);
bundle_info.write_components(
table,
sparse_sets,
&SpawnBundleStatus,
bundle_info.required_component_constructors.iter(),
entity,
table_row,
self.change_tick,
bundle,
InsertMode::Replace,
caller,
);
entities.set_location(entity.index(), Some(location));
entities.mark_spawned_or_despawned(entity.index(), caller, self.change_tick);
location
};
// SAFETY: We have no outstanding mutable references to world as they were dropped
let mut deferred_world = unsafe { self.world.into_deferred() };
// SAFETY: `DeferredWorld` cannot provide mutable access to `Archetypes`.
let archetype = self.archetype.as_ref();
// SAFETY: All components in the bundle are guaranteed to exist in the World
// as they must be initialized before creating the BundleInfo.
unsafe {
deferred_world.trigger_on_add(
archetype,
entity,
bundle_info.iter_contributed_components(),
caller,
);
if archetype.has_add_observer() {
// SAFETY: the ADD event_key corresponds to the Add event's type
deferred_world.trigger_raw(
ADD,
&mut Add { entity },
&mut EntityComponentsTrigger {
components: bundle_info.contributed_components(),
},
caller,
);
}
deferred_world.trigger_on_insert(
archetype,
entity,
bundle_info.iter_contributed_components(),
caller,
RelationshipHookMode::Run,
);
if archetype.has_insert_observer() {
// SAFETY: the INSERT event_key corresponds to the Insert event's type
deferred_world.trigger_raw(
INSERT,
&mut Insert { entity },
&mut EntityComponentsTrigger {
components: bundle_info.contributed_components(),
},
caller,
);
}
};
location
}
/// # Safety
/// - `T` must match this [`BundleSpawner`]'s type
/// - If `T::Effect: !NoBundleEffect.`, then [`apply_effect`] must be called exactly once on `bundle`
/// after this function returns before returning to safe code.
/// - The value pointed to by `bundle` must not be accessed for anything other than [`apply_effect`]
/// or dropped.
///
/// [`apply_effect`]: crate::bundle::DynamicBundle::apply_effect
#[inline]
pub unsafe fn spawn<T: Bundle>(
&mut self,
bundle: MovingPtr<'_, T>,
caller: MaybeLocation,
) -> Entity {
let entity = self.allocator().alloc();
// SAFETY: entity is allocated (but non-existent), `T` matches this BundleInfo's type
let _ = unsafe { self.spawn_at(entity, bundle, caller) };
entity
}
#[inline]
pub(crate) fn allocator(&mut self) -> &'w mut EntityAllocator {
// SAFETY: No outstanding references to self.world, changes to entities cannot invalidate our internal pointers
unsafe { &mut self.world.world_mut().allocator }
}
/// # Safety
/// - `Self` must be dropped after running this function as it may invalidate internal pointers.
#[inline]
pub(crate) unsafe fn flush_commands(&mut self) {
// SAFETY: pointers on self can be invalidated,
self.world.world_mut().flush();
}
}
| 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/bundle/tests.rs | crates/bevy_ecs/src/bundle/tests.rs | use crate::{
archetype::ArchetypeCreated, lifecycle::HookContext, prelude::*, world::DeferredWorld,
};
#[derive(Component)]
struct A;
#[derive(Component)]
#[component(on_add = a_on_add, on_insert = a_on_insert, on_replace = a_on_replace, on_remove = a_on_remove)]
struct AMacroHooks;
fn a_on_add(mut world: DeferredWorld, _: HookContext) {
world.resource_mut::<R>().assert_order(0);
}
fn a_on_insert(mut world: DeferredWorld, _: HookContext) {
world.resource_mut::<R>().assert_order(1);
}
fn a_on_replace(mut world: DeferredWorld, _: HookContext) {
world.resource_mut::<R>().assert_order(2);
}
fn a_on_remove(mut world: DeferredWorld, _: HookContext) {
world.resource_mut::<R>().assert_order(3);
}
#[derive(Component)]
struct B;
#[derive(Component)]
struct C;
#[derive(Component)]
struct D;
#[derive(Component, Eq, PartialEq, Debug)]
struct V(&'static str); // component with a value
#[derive(Resource, Default)]
struct R(usize);
impl R {
#[track_caller]
fn assert_order(&mut self, count: usize) {
assert_eq!(count, self.0);
self.0 += 1;
}
}
#[derive(Bundle)]
#[bundle(ignore_from_components)]
struct BundleNoExtract {
b: B,
no_from_comp: crate::spawn::SpawnRelatedBundle<ChildOf, Spawn<C>>,
}
#[test]
fn can_spawn_bundle_without_extract() {
let mut world = World::new();
let id = world
.spawn(BundleNoExtract {
b: B,
no_from_comp: Children::spawn(Spawn(C)),
})
.id();
assert!(world.entity(id).get::<Children>().is_some());
}
#[test]
fn component_hook_order_spawn_despawn() {
let mut world = World::new();
world.init_resource::<R>();
world
.register_component_hooks::<A>()
.on_add(|mut world, _| world.resource_mut::<R>().assert_order(0))
.on_insert(|mut world, _| world.resource_mut::<R>().assert_order(1))
.on_replace(|mut world, _| world.resource_mut::<R>().assert_order(2))
.on_remove(|mut world, _| world.resource_mut::<R>().assert_order(3));
let entity = world.spawn(A).id();
world.despawn(entity);
assert_eq!(4, world.resource::<R>().0);
}
#[test]
fn component_hook_order_spawn_despawn_with_macro_hooks() {
let mut world = World::new();
world.init_resource::<R>();
let entity = world.spawn(AMacroHooks).id();
world.despawn(entity);
assert_eq!(4, world.resource::<R>().0);
}
#[test]
fn component_hook_order_insert_remove() {
let mut world = World::new();
world.init_resource::<R>();
world
.register_component_hooks::<A>()
.on_add(|mut world, _| world.resource_mut::<R>().assert_order(0))
.on_insert(|mut world, _| world.resource_mut::<R>().assert_order(1))
.on_replace(|mut world, _| world.resource_mut::<R>().assert_order(2))
.on_remove(|mut world, _| world.resource_mut::<R>().assert_order(3));
let mut entity = world.spawn_empty();
entity.insert(A);
entity.remove::<A>();
entity.flush();
assert_eq!(4, world.resource::<R>().0);
}
#[test]
fn component_hook_order_replace() {
let mut world = World::new();
world
.register_component_hooks::<A>()
.on_replace(|mut world, _| world.resource_mut::<R>().assert_order(0))
.on_insert(|mut world, _| {
if let Some(mut r) = world.get_resource_mut::<R>() {
r.assert_order(1);
}
});
let entity = world.spawn(A).id();
world.init_resource::<R>();
let mut entity = world.entity_mut(entity);
entity.insert(A);
entity.insert_if_new(A); // this will not trigger on_replace or on_insert
entity.flush();
assert_eq!(2, world.resource::<R>().0);
}
#[test]
fn component_hook_order_recursive() {
let mut world = World::new();
world.init_resource::<R>();
world
.register_component_hooks::<A>()
.on_add(|mut world, context| {
world.resource_mut::<R>().assert_order(0);
world.commands().entity(context.entity).insert(B);
})
.on_remove(|mut world, context| {
world.resource_mut::<R>().assert_order(2);
world.commands().entity(context.entity).remove::<B>();
});
world
.register_component_hooks::<B>()
.on_add(|mut world, context| {
world.resource_mut::<R>().assert_order(1);
world.commands().entity(context.entity).remove::<A>();
})
.on_remove(|mut world, _| {
world.resource_mut::<R>().assert_order(3);
});
let entity = world.spawn(A).flush();
let entity = world.get_entity(entity).unwrap();
assert!(!entity.contains::<A>());
assert!(!entity.contains::<B>());
assert_eq!(4, world.resource::<R>().0);
}
#[test]
fn component_hook_order_recursive_multiple() {
let mut world = World::new();
world.init_resource::<R>();
world
.register_component_hooks::<A>()
.on_add(|mut world, context| {
world.resource_mut::<R>().assert_order(0);
world.commands().entity(context.entity).insert(B).insert(C);
});
world
.register_component_hooks::<B>()
.on_add(|mut world, context| {
world.resource_mut::<R>().assert_order(1);
world.commands().entity(context.entity).insert(D);
});
world
.register_component_hooks::<C>()
.on_add(|mut world, _| {
world.resource_mut::<R>().assert_order(3);
});
world
.register_component_hooks::<D>()
.on_add(|mut world, _| {
world.resource_mut::<R>().assert_order(2);
});
world.spawn(A).flush();
assert_eq!(4, world.resource::<R>().0);
}
#[test]
fn insert_if_new() {
let mut world = World::new();
let id = world.spawn(V("one")).id();
let mut entity = world.entity_mut(id);
entity.insert_if_new(V("two"));
entity.insert_if_new((A, V("three")));
entity.flush();
// should still contain "one"
let entity = world.entity(id);
assert!(entity.contains::<A>());
assert_eq!(entity.get(), Some(&V("one")));
}
#[derive(Component, Debug, Eq, PartialEq)]
#[component(storage = "SparseSet")]
pub struct SparseV(&'static str);
#[derive(Component, Debug, Eq, PartialEq)]
#[component(storage = "SparseSet")]
pub struct SparseA;
#[test]
fn sparse_set_insert_if_new() {
let mut world = World::new();
let id = world.spawn(SparseV("one")).id();
let mut entity = world.entity_mut(id);
entity.insert_if_new(SparseV("two"));
entity.insert_if_new((SparseA, SparseV("three")));
entity.flush();
// should still contain "one"
let entity = world.entity(id);
assert!(entity.contains::<SparseA>());
assert_eq!(entity.get(), Some(&SparseV("one")));
}
#[test]
fn new_archetype_created() {
let mut world = World::new();
#[derive(Resource, Default)]
struct Count(u32);
world.init_resource::<Count>();
world.add_observer(|_t: On<ArchetypeCreated>, mut count: ResMut<Count>| {
count.0 += 1;
});
let mut e = world.spawn((A, B));
e.insert(C);
e.remove::<A>();
e.insert(A);
e.insert(A);
assert_eq!(world.resource::<Count>().0, 3);
}
#[derive(Bundle)]
#[expect(unused, reason = "tests the output of the derive macro is valid")]
struct Ignore {
#[bundle(ignore)]
foo: i32,
#[bundle(ignore)]
bar: i32,
}
| 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/bundle/insert.rs | crates/bevy_ecs/src/bundle/insert.rs | use alloc::vec::Vec;
use bevy_ptr::{ConstNonNull, MovingPtr};
use core::ptr::NonNull;
use crate::{
archetype::{
Archetype, ArchetypeAfterBundleInsert, ArchetypeCreated, ArchetypeId, Archetypes,
ComponentStatus,
},
bundle::{ArchetypeMoveType, Bundle, BundleId, BundleInfo, DynamicBundle, InsertMode},
change_detection::{MaybeLocation, Tick},
component::{Components, StorageType},
entity::{Entities, Entity, EntityLocation},
event::EntityComponentsTrigger,
lifecycle::{Add, Insert, Replace, ADD, INSERT, REPLACE},
observer::Observers,
query::DebugCheckedUnwrap as _,
relationship::RelationshipHookMode,
storage::{SparseSets, Storages, Table, TableRow},
world::{unsafe_world_cell::UnsafeWorldCell, World},
};
// SAFETY: We have exclusive world access so our pointers can't be invalidated externally
pub(crate) struct BundleInserter<'w> {
world: UnsafeWorldCell<'w>,
bundle_info: ConstNonNull<BundleInfo>,
archetype_after_insert: ConstNonNull<ArchetypeAfterBundleInsert>,
table: NonNull<Table>,
archetype: NonNull<Archetype>,
archetype_move_type: ArchetypeMoveType,
change_tick: Tick,
}
impl<'w> BundleInserter<'w> {
#[inline]
pub(crate) fn new<T: Bundle>(
world: &'w mut World,
archetype_id: ArchetypeId,
change_tick: Tick,
) -> Self {
let bundle_id = world.register_bundle_info::<T>();
// SAFETY: We just ensured this bundle exists
unsafe { Self::new_with_id(world, archetype_id, bundle_id, change_tick) }
}
/// Creates a new [`BundleInserter`].
///
/// # Safety
/// - Caller must ensure that `bundle_id` exists in `world.bundles`.
#[inline]
pub(crate) unsafe fn new_with_id(
world: &'w mut World,
archetype_id: ArchetypeId,
bundle_id: BundleId,
change_tick: Tick,
) -> Self {
// SAFETY: We will not make any accesses to the command queue, component or resource data of this world
let bundle_info = world.bundles.get_unchecked(bundle_id);
let bundle_id = bundle_info.id();
let (new_archetype_id, is_new_created) = bundle_info.insert_bundle_into_archetype(
&mut world.archetypes,
&mut world.storages,
&world.components,
&world.observers,
archetype_id,
);
let inserter = if new_archetype_id == archetype_id {
let archetype = &mut world.archetypes[archetype_id];
// SAFETY: The edge is assured to be initialized when we called insert_bundle_into_archetype
let archetype_after_insert = unsafe {
archetype
.edges()
.get_archetype_after_bundle_insert_internal(bundle_id)
.debug_checked_unwrap()
};
let table_id = archetype.table_id();
let table = &mut world.storages.tables[table_id];
Self {
archetype_after_insert: archetype_after_insert.into(),
archetype: archetype.into(),
bundle_info: bundle_info.into(),
table: table.into(),
archetype_move_type: ArchetypeMoveType::SameArchetype,
change_tick,
world: world.as_unsafe_world_cell(),
}
} else {
let (archetype, new_archetype) =
world.archetypes.get_2_mut(archetype_id, new_archetype_id);
// SAFETY: The edge is assured to be initialized when we called insert_bundle_into_archetype
let archetype_after_insert = unsafe {
archetype
.edges()
.get_archetype_after_bundle_insert_internal(bundle_id)
.debug_checked_unwrap()
};
let table_id = archetype.table_id();
let new_table_id = new_archetype.table_id();
if table_id == new_table_id {
let table = &mut world.storages.tables[table_id];
Self {
archetype_after_insert: archetype_after_insert.into(),
archetype: archetype.into(),
bundle_info: bundle_info.into(),
table: table.into(),
archetype_move_type: ArchetypeMoveType::NewArchetypeSameTable {
new_archetype: new_archetype.into(),
},
change_tick,
world: world.as_unsafe_world_cell(),
}
} else {
let (table, new_table) = world.storages.tables.get_2_mut(table_id, new_table_id);
Self {
archetype_after_insert: archetype_after_insert.into(),
archetype: archetype.into(),
bundle_info: bundle_info.into(),
table: table.into(),
archetype_move_type: ArchetypeMoveType::NewArchetypeNewTable {
new_archetype: new_archetype.into(),
new_table: new_table.into(),
},
change_tick,
world: world.as_unsafe_world_cell(),
}
}
};
if is_new_created {
inserter
.world
.into_deferred()
.trigger(ArchetypeCreated(new_archetype_id));
}
inserter
}
// A non-generic prelude to insert used to minimize duplicated monomorphized code.
// In combination with after_insert, this can reduce compile time of bevy by 10%.
// We inline in release to avoid a minor perf loss.
#[cfg_attr(not(debug_assertions), inline(always))]
unsafe fn before_insert<'a>(
entity: Entity,
location: EntityLocation,
insert_mode: InsertMode,
caller: MaybeLocation,
relationship_hook_mode: RelationshipHookMode,
mut table: NonNull<Table>,
mut archetype: NonNull<Archetype>,
archetype_after_insert: &ArchetypeAfterBundleInsert,
world: &'a UnsafeWorldCell<'w>,
archetype_move_type: &'a mut ArchetypeMoveType,
) -> (
&'a Archetype,
EntityLocation,
&'a mut SparseSets,
&'a mut Table,
TableRow,
) {
// SAFETY: All components in the bundle are guaranteed to exist in the World
// as they must be initialized before creating the BundleInfo.
unsafe {
// SAFETY: Mutable references do not alias and will be dropped after this block
let mut deferred_world = world.into_deferred();
if insert_mode == InsertMode::Replace {
let archetype = archetype.as_ref();
if archetype.has_replace_observer() {
// SAFETY: the REPLACE event_key corresponds to the Replace event's type
deferred_world.trigger_raw(
REPLACE,
&mut Replace { entity },
&mut EntityComponentsTrigger {
components: archetype_after_insert.existing(),
},
caller,
);
}
deferred_world.trigger_on_replace(
archetype,
entity,
archetype_after_insert.existing().iter().copied(),
caller,
relationship_hook_mode,
);
}
}
let table = table.as_mut();
// SAFETY: Archetype gets borrowed when running the on_replace observers above,
// so this reference can only be promoted from shared to &mut down here, after they have been ran
let archetype = archetype.as_mut();
match archetype_move_type {
ArchetypeMoveType::SameArchetype => {
// SAFETY: Mutable references do not alias and will be dropped after this block
let sparse_sets = {
let world = world.world_mut();
&mut world.storages.sparse_sets
};
(
&*archetype,
location,
sparse_sets,
table,
location.table_row,
)
}
ArchetypeMoveType::NewArchetypeSameTable { new_archetype } => {
let new_archetype = new_archetype.as_mut();
// SAFETY: Mutable references do not alias and will be dropped after this block
let (sparse_sets, entities) = {
let world = world.world_mut();
(&mut world.storages.sparse_sets, &mut world.entities)
};
let result = archetype.swap_remove(location.archetype_row);
if let Some(swapped_entity) = result.swapped_entity {
let swapped_location =
// SAFETY: If the swap was successful, swapped_entity must be valid.
unsafe { entities.get_spawned(swapped_entity).debug_checked_unwrap() };
entities.update_existing_location(
swapped_entity.index(),
Some(EntityLocation {
archetype_id: swapped_location.archetype_id,
archetype_row: location.archetype_row,
table_id: swapped_location.table_id,
table_row: swapped_location.table_row,
}),
);
}
let new_location = new_archetype.allocate(entity, result.table_row);
entities.update_existing_location(entity.index(), Some(new_location));
(
&*new_archetype,
new_location,
sparse_sets,
table,
result.table_row,
)
}
ArchetypeMoveType::NewArchetypeNewTable {
new_archetype,
new_table,
} => {
let new_table = new_table.as_mut();
let new_archetype = new_archetype.as_mut();
// SAFETY: Mutable references do not alias and will be dropped after this block
let (archetypes_ptr, sparse_sets, entities) = {
let world = world.world_mut();
let archetype_ptr: *mut Archetype = world.archetypes.archetypes.as_mut_ptr();
(
archetype_ptr,
&mut world.storages.sparse_sets,
&mut world.entities,
)
};
let result = archetype.swap_remove(location.archetype_row);
if let Some(swapped_entity) = result.swapped_entity {
let swapped_location =
// SAFETY: If the swap was successful, swapped_entity must be valid.
unsafe { entities.get_spawned(swapped_entity).debug_checked_unwrap() };
entities.update_existing_location(
swapped_entity.index(),
Some(EntityLocation {
archetype_id: swapped_location.archetype_id,
archetype_row: location.archetype_row,
table_id: swapped_location.table_id,
table_row: swapped_location.table_row,
}),
);
}
// PERF: store "non bundle" components in edge, then just move those to avoid
// redundant copies
let move_result = table.move_to_superset_unchecked(result.table_row, new_table);
let new_location = new_archetype.allocate(entity, move_result.new_row);
entities.update_existing_location(entity.index(), Some(new_location));
// If an entity was moved into this entity's table spot, update its table row.
if let Some(swapped_entity) = move_result.swapped_entity {
let swapped_location =
// SAFETY: If the swap was successful, swapped_entity must be valid.
unsafe { entities.get_spawned(swapped_entity).debug_checked_unwrap() };
entities.update_existing_location(
swapped_entity.index(),
Some(EntityLocation {
archetype_id: swapped_location.archetype_id,
archetype_row: swapped_location.archetype_row,
table_id: swapped_location.table_id,
table_row: result.table_row,
}),
);
if archetype.id() == swapped_location.archetype_id {
archetype
.set_entity_table_row(swapped_location.archetype_row, result.table_row);
} else if new_archetype.id() == swapped_location.archetype_id {
new_archetype
.set_entity_table_row(swapped_location.archetype_row, result.table_row);
} else {
// SAFETY: the only two borrowed archetypes are above and we just did collision checks
(*archetypes_ptr.add(swapped_location.archetype_id.index()))
.set_entity_table_row(swapped_location.archetype_row, result.table_row);
}
}
(
&*new_archetype,
new_location,
sparse_sets,
new_table,
move_result.new_row,
)
}
}
}
/// # Safety
/// - `entity` must currently exist in the source archetype for this inserter.
/// - `location` must be `entity`'s location in the archetype.
/// - `T` must match this [`BundleInserter`] type used to create
/// - If `T::Effect: !NoBundleEffect.`, then [`apply_effect`] must be called at most once on
/// `bundle` after this function before returning to user-space safe code.
/// - The value pointed to by `bundle` must not be accessed for anything other than [`apply_effect`]
/// or dropped.
///
/// [`apply_effect`]: crate::bundle::DynamicBundle::apply_effect
#[inline]
pub(crate) unsafe fn insert<T: DynamicBundle>(
&mut self,
entity: Entity,
location: EntityLocation,
bundle: MovingPtr<'_, T>,
insert_mode: InsertMode,
caller: MaybeLocation,
relationship_hook_mode: RelationshipHookMode,
) -> EntityLocation {
let archetype_after_insert = self.archetype_after_insert.as_ref();
let (new_archetype, new_location) = {
// Non-generic prelude extracted to improve compile time by minimizing monomorphized code.
let (new_archetype, new_location, sparse_sets, table, table_row) = Self::before_insert(
entity,
location,
insert_mode,
caller,
relationship_hook_mode,
self.table,
self.archetype,
archetype_after_insert,
&self.world,
&mut self.archetype_move_type,
);
self.bundle_info.as_ref().write_components(
table,
sparse_sets,
archetype_after_insert,
archetype_after_insert.required_components.iter(),
entity,
table_row,
self.change_tick,
bundle,
insert_mode,
caller,
);
(new_archetype, new_location)
};
// SAFETY: We have no outstanding mutable references to world as they were dropped
let deferred_world = unsafe { self.world.into_deferred() };
// Non-generic postlude extracted to improve compile time by minimizing monomorphized code.
Self::after_insert(
entity,
insert_mode,
caller,
relationship_hook_mode,
archetype_after_insert,
new_archetype,
deferred_world,
);
new_location
}
// A non-generic postlude to insert used to minimize duplicated monomorphized code.
// In combination with before_insert, this can reduce compile time of bevy by 10%.
// We inline in release to avoid a minor perf loss.
#[cfg_attr(not(debug_assertions), inline(always))]
fn after_insert(
entity: Entity,
insert_mode: InsertMode,
caller: MaybeLocation,
relationship_hook_mode: RelationshipHookMode,
archetype_after_insert: &ArchetypeAfterBundleInsert,
new_archetype: &Archetype,
mut deferred_world: crate::world::DeferredWorld<'_>,
) {
// SAFETY: All components in the bundle are guaranteed to exist in the World
// as they must be initialized before creating the BundleInfo.
unsafe {
deferred_world.trigger_on_add(
new_archetype,
entity,
archetype_after_insert.added().iter().copied(),
caller,
);
if new_archetype.has_add_observer() {
// SAFETY: the ADD event_key corresponds to the Add event's type
deferred_world.trigger_raw(
ADD,
&mut Add { entity },
&mut EntityComponentsTrigger {
components: archetype_after_insert.added(),
},
caller,
);
}
match insert_mode {
InsertMode::Replace => {
// Insert triggers for both new and existing components if we're replacing them.
deferred_world.trigger_on_insert(
new_archetype,
entity,
archetype_after_insert.inserted().iter().copied(),
caller,
relationship_hook_mode,
);
if new_archetype.has_insert_observer() {
// SAFETY: the INSERT event_key corresponds to the Insert event's type
deferred_world.trigger_raw(
INSERT,
&mut Insert { entity },
&mut EntityComponentsTrigger {
components: archetype_after_insert.inserted(),
},
caller,
);
}
}
InsertMode::Keep => {
// Insert triggers only for new components if we're not replacing them (since
// nothing is actually inserted).
deferred_world.trigger_on_insert(
new_archetype,
entity,
archetype_after_insert.added().iter().copied(),
caller,
relationship_hook_mode,
);
if new_archetype.has_insert_observer() {
// SAFETY: the INSERT event_key corresponds to the Insert event's type
deferred_world.trigger_raw(
INSERT,
&mut Insert { entity },
&mut EntityComponentsTrigger {
components: archetype_after_insert.added(),
},
caller,
);
}
}
}
}
}
#[inline]
pub(crate) fn entities(&mut self) -> &mut Entities {
// SAFETY: No outstanding references to self.world, changes to entities cannot invalidate our internal pointers
unsafe { &mut self.world.world_mut().entities }
}
}
impl BundleInfo {
/// Inserts a bundle into the given archetype and returns the resulting archetype and whether a new archetype was created.
/// This could be the same [`ArchetypeId`], in the event that inserting the given bundle
/// does not result in an [`Archetype`] change.
///
/// Results are cached in the [`Archetype`] graph to avoid redundant work.
///
/// # Safety
/// `components` must be the same components as passed in [`Self::new`]
pub(crate) unsafe fn insert_bundle_into_archetype(
&self,
archetypes: &mut Archetypes,
storages: &mut Storages,
components: &Components,
observers: &Observers,
archetype_id: ArchetypeId,
) -> (ArchetypeId, bool) {
if let Some(archetype_after_insert_id) = archetypes[archetype_id]
.edges()
.get_archetype_after_bundle_insert(self.id)
{
return (archetype_after_insert_id, false);
}
let mut new_table_components = Vec::new();
let mut new_sparse_set_components = Vec::new();
let mut bundle_status = Vec::with_capacity(self.explicit_components_len());
let mut added_required_components = Vec::new();
let mut added = Vec::new();
let mut existing = Vec::new();
let current_archetype = &mut archetypes[archetype_id];
for component_id in self.iter_explicit_components() {
if current_archetype.contains(component_id) {
bundle_status.push(ComponentStatus::Existing);
existing.push(component_id);
} else {
bundle_status.push(ComponentStatus::Added);
added.push(component_id);
// SAFETY: component_id exists
let component_info = unsafe { components.get_info_unchecked(component_id) };
match component_info.storage_type() {
StorageType::Table => new_table_components.push(component_id),
StorageType::SparseSet => new_sparse_set_components.push(component_id),
}
}
}
for (index, component_id) in self.iter_required_components().enumerate() {
if !current_archetype.contains(component_id) {
added_required_components.push(self.required_component_constructors[index].clone());
added.push(component_id);
// SAFETY: component_id exists
let component_info = unsafe { components.get_info_unchecked(component_id) };
match component_info.storage_type() {
StorageType::Table => {
new_table_components.push(component_id);
}
StorageType::SparseSet => {
new_sparse_set_components.push(component_id);
}
}
}
}
if new_table_components.is_empty() && new_sparse_set_components.is_empty() {
let edges = current_archetype.edges_mut();
// The archetype does not change when we insert this bundle.
edges.cache_archetype_after_bundle_insert(
self.id,
archetype_id,
bundle_status,
added_required_components,
added,
existing,
);
(archetype_id, false)
} else {
let table_id;
let table_components;
let sparse_set_components;
// The archetype changes when we insert this bundle. Prepare the new archetype and storages.
{
let current_archetype = &archetypes[archetype_id];
table_components = if new_table_components.is_empty() {
// If there are no new table components, we can keep using this table.
table_id = current_archetype.table_id();
current_archetype.table_components().collect()
} else {
new_table_components.extend(current_archetype.table_components());
// Sort to ignore order while hashing.
new_table_components.sort_unstable();
// SAFETY: all component ids in `new_table_components` exist
table_id = unsafe {
storages
.tables
.get_id_or_insert(&new_table_components, components)
};
new_table_components
};
sparse_set_components = if new_sparse_set_components.is_empty() {
current_archetype.sparse_set_components().collect()
} else {
new_sparse_set_components.extend(current_archetype.sparse_set_components());
// Sort to ignore order while hashing.
new_sparse_set_components.sort_unstable();
new_sparse_set_components
};
};
// SAFETY: ids in self must be valid
let (new_archetype_id, is_new_created) = unsafe {
archetypes.get_id_or_insert(
components,
observers,
table_id,
table_components,
sparse_set_components,
)
};
// Add an edge from the old archetype to the new archetype.
archetypes[archetype_id]
.edges_mut()
.cache_archetype_after_bundle_insert(
self.id,
new_archetype_id,
bundle_status,
added_required_components,
added,
existing,
);
(new_archetype_id, is_new_created)
}
}
}
| 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/bundle/info.rs | crates/bevy_ecs/src/bundle/info.rs | use alloc::{boxed::Box, vec, vec::Vec};
use bevy_platform::{
collections::{HashMap, HashSet},
hash::FixedHasher,
};
use bevy_ptr::{MovingPtr, OwningPtr};
use bevy_utils::TypeIdMap;
use core::{any::TypeId, ptr::NonNull};
use indexmap::{IndexMap, IndexSet};
use crate::{
archetype::{Archetype, BundleComponentStatus, ComponentStatus},
bundle::{Bundle, DynamicBundle},
change_detection::{MaybeLocation, Tick},
component::{
ComponentId, Components, ComponentsRegistrator, RequiredComponentConstructor, StorageType,
},
entity::Entity,
query::DebugCheckedUnwrap as _,
storage::{SparseSetIndex, SparseSets, Storages, Table, TableRow},
};
/// For a specific [`World`], this stores a unique value identifying a type of a registered [`Bundle`].
///
/// [`World`]: crate::world::World
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct BundleId(usize);
impl BundleId {
/// Returns the index of the associated [`Bundle`] type.
///
/// Note that this is unique per-world, and should not be reused across them.
#[inline]
pub fn index(self) -> usize {
self.0
}
}
impl SparseSetIndex for BundleId {
#[inline]
fn sparse_set_index(&self) -> usize {
self.index()
}
#[inline]
fn get_sparse_set_index(value: usize) -> Self {
Self(value)
}
}
/// What to do on insertion if a component already exists.
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum InsertMode {
/// Any existing components of a matching type will be overwritten.
Replace,
/// Any existing components of a matching type will be left unchanged.
Keep,
}
/// Stores metadata associated with a specific type of [`Bundle`] for a given [`World`].
///
/// [`World`]: crate::world::World
pub struct BundleInfo {
pub(super) id: BundleId,
/// The list of all components contributed by the bundle (including Required Components). This is in
/// the order `[EXPLICIT_COMPONENTS][REQUIRED_COMPONENTS]`
///
/// # Safety
/// Every ID in this list must be valid within the World that owns the [`BundleInfo`],
/// must have its storage initialized (i.e. columns created in tables, sparse set created),
/// and the range (0..`explicit_components_len`) must be in the same order as the source bundle
/// type writes its components in.
pub(super) contributed_component_ids: Box<[ComponentId]>,
/// The list of constructors for all required components indirectly contributed by this bundle.
pub(super) required_component_constructors: Box<[RequiredComponentConstructor]>,
}
impl BundleInfo {
/// Create a new [`BundleInfo`].
///
/// # Safety
///
/// Every ID in `component_ids` must be valid within the World that owns the `BundleInfo`
/// and must be in the same order as the source bundle type writes its components in.
unsafe fn new(
bundle_type_name: &'static str,
storages: &mut Storages,
components: &Components,
mut component_ids: Vec<ComponentId>,
id: BundleId,
) -> BundleInfo {
let explicit_component_ids = component_ids
.iter()
.copied()
.collect::<IndexSet<_, FixedHasher>>();
// check for duplicates
if explicit_component_ids.len() != component_ids.len() {
// TODO: Replace with `Vec::partition_dedup` once https://github.com/rust-lang/rust/issues/54279 is stabilized
let mut seen = <HashSet<_>>::default();
let mut dups = Vec::new();
for id in component_ids {
if !seen.insert(id) {
dups.push(id);
}
}
let names = dups
.into_iter()
.map(|id| {
// SAFETY: the caller ensures component_id is valid.
unsafe { components.get_info_unchecked(id).name() }
})
.collect::<Vec<_>>();
panic!("Bundle {bundle_type_name} has duplicate components: {names:?}");
}
let mut depth_first_components = IndexMap::<_, _, FixedHasher>::default();
for &component_id in &component_ids {
// SAFETY: caller has verified that all ids are valid
let info = unsafe { components.get_info_unchecked(component_id) };
for (&required_id, required_component) in &info.required_components().all {
depth_first_components
.entry(required_id)
.or_insert_with(|| required_component.clone());
}
storages.prepare_component(info);
}
let required_components = depth_first_components
.into_iter()
.filter(|&(required_id, _)| !explicit_component_ids.contains(&required_id))
.inspect(|&(required_id, _)| {
// SAFETY: These ids came out of the passed `components`, so they must be valid.
storages.prepare_component(unsafe { components.get_info_unchecked(required_id) });
component_ids.push(required_id);
})
.map(|(_, required_component)| required_component.constructor)
.collect::<Box<_>>();
// SAFETY: The caller ensures that component_ids:
// - is valid for the associated world
// - has had its storage initialized
// - is in the same order as the source bundle type
BundleInfo {
id,
contributed_component_ids: component_ids.into(),
required_component_constructors: required_components,
}
}
/// Returns a value identifying the associated [`Bundle`] type.
#[inline]
pub const fn id(&self) -> BundleId {
self.id
}
/// Returns the length of the explicit components part of the [`contributed_components`](Self::contributed_components) list.
#[inline]
pub(super) fn explicit_components_len(&self) -> usize {
self.contributed_component_ids.len() - self.required_component_constructors.len()
}
/// Returns the [ID](ComponentId) of each component explicitly defined in this bundle (ex: Required Components are excluded).
///
/// For all components contributed by this bundle (including Required Components), see [`BundleInfo::contributed_components`]
#[inline]
pub fn explicit_components(&self) -> &[ComponentId] {
&self.contributed_component_ids[0..self.explicit_components_len()]
}
/// Returns the [ID](ComponentId) of each Required Component needed by this bundle. This _does not include_ Required Components that are
/// explicitly provided by the bundle.
#[inline]
pub fn required_components(&self) -> &[ComponentId] {
&self.contributed_component_ids[self.explicit_components_len()..]
}
/// Returns the [ID](ComponentId) of each component contributed by this bundle. This includes Required Components.
///
/// For only components explicitly defined in this bundle, see [`BundleInfo::explicit_components`]
#[inline]
pub fn contributed_components(&self) -> &[ComponentId] {
&self.contributed_component_ids
}
/// Returns an iterator over the [ID](ComponentId) of each component explicitly defined in this bundle (ex: this excludes Required Components).
/// To iterate all components contributed by this bundle (including Required Components), see [`BundleInfo::iter_contributed_components`]
#[inline]
pub fn iter_explicit_components(&self) -> impl Iterator<Item = ComponentId> + Clone + '_ {
self.explicit_components().iter().copied()
}
/// Returns an iterator over the [ID](ComponentId) of each component contributed by this bundle. This includes Required Components.
///
/// To iterate only components explicitly defined in this bundle, see [`BundleInfo::iter_explicit_components`]
#[inline]
pub fn iter_contributed_components(&self) -> impl Iterator<Item = ComponentId> + Clone + '_ {
self.contributed_components().iter().copied()
}
/// Returns an iterator over the [ID](ComponentId) of each Required Component needed by this bundle. This _does not include_ Required Components that are
/// explicitly provided by the bundle.
pub fn iter_required_components(&self) -> impl Iterator<Item = ComponentId> + '_ {
self.required_components().iter().copied()
}
/// This writes components from a given [`Bundle`] to the given entity.
///
/// # Safety
///
/// `bundle_component_status` must return the "correct" [`ComponentStatus`] for each component
/// in the [`Bundle`], with respect to the entity's original archetype (prior to the bundle being added).
///
/// For example, if the original archetype already has `ComponentA` and `T` also has `ComponentA`, the status
/// should be `Existing`. If the original archetype does not have `ComponentA`, the status should be `Added`.
///
/// When "inserting" a bundle into an existing entity, [`ArchetypeAfterBundleInsert`](crate::archetype::SpawnBundleStatus)
/// should be used, which will report `Added` vs `Existing` status based on the current archetype's structure.
///
/// When spawning a bundle, [`SpawnBundleStatus`](crate::archetype::SpawnBundleStatus) can be used instead,
/// which removes the need to look up the [`ArchetypeAfterBundleInsert`](crate::archetype::ArchetypeAfterBundleInsert)
/// in the archetype graph, which requires ownership of the entity's current archetype.
///
/// Regardless of how this is used, [`apply_effect`] must be called at most once on `bundle` after this function is
/// called if `T::Effect: !NoBundleEffect` before returning to user-space safe code before returning to user-space safe code.
/// This is currently only doable via use of [`MovingPtr::partial_move`].
///
/// `table` must be the "new" table for `entity`. `table_row` must have space allocated for the
/// `entity`, `bundle` must match this [`BundleInfo`]'s type
///
/// [`apply_effect`]: crate::bundle::DynamicBundle::apply_effect
#[inline]
pub(super) unsafe fn write_components<'a, T: DynamicBundle, S: BundleComponentStatus>(
&self,
table: &mut Table,
sparse_sets: &mut SparseSets,
bundle_component_status: &S,
required_components: impl Iterator<Item = &'a RequiredComponentConstructor>,
entity: Entity,
table_row: TableRow,
change_tick: Tick,
bundle: MovingPtr<'_, T>,
insert_mode: InsertMode,
caller: MaybeLocation,
) {
// NOTE: get_components calls this closure on each component in "bundle order".
// bundle_info.component_ids are also in "bundle order"
let mut bundle_component = 0;
T::get_components(bundle, &mut |storage_type, component_ptr| {
let component_id = *self
.contributed_component_ids
.get_unchecked(bundle_component);
// SAFETY: bundle_component is a valid index for this bundle
let status = unsafe { bundle_component_status.get_status(bundle_component) };
match storage_type {
StorageType::Table => {
let column =
// SAFETY: If component_id is in self.component_ids, BundleInfo::new ensures that
// the target table contains the component.
unsafe { table.get_column_mut(component_id).debug_checked_unwrap() };
match (status, insert_mode) {
(ComponentStatus::Added, _) => {
column.initialize(table_row, component_ptr, change_tick, caller);
}
(ComponentStatus::Existing, InsertMode::Replace) => {
column.replace(table_row, component_ptr, change_tick, caller);
}
(ComponentStatus::Existing, InsertMode::Keep) => {
if let Some(drop_fn) = table.get_drop_for(component_id) {
drop_fn(component_ptr);
}
}
}
}
StorageType::SparseSet => {
let sparse_set =
// SAFETY: If component_id is in self.component_ids, BundleInfo::new ensures that
// a sparse set exists for the component.
unsafe { sparse_sets.get_mut(component_id).debug_checked_unwrap() };
match (status, insert_mode) {
(ComponentStatus::Added, _) | (_, InsertMode::Replace) => {
sparse_set.insert(entity, component_ptr, change_tick, caller);
}
(ComponentStatus::Existing, InsertMode::Keep) => {
if let Some(drop_fn) = sparse_set.get_drop() {
drop_fn(component_ptr);
}
}
}
}
}
bundle_component += 1;
});
for required_component in required_components {
required_component.initialize(
table,
sparse_sets,
change_tick,
table_row,
entity,
caller,
);
}
}
/// Internal method to initialize a required component from an [`OwningPtr`]. This should ultimately be called
/// in the context of [`BundleInfo::write_components`], via [`RequiredComponentConstructor::initialize`].
///
/// # Safety
///
/// `component_ptr` must point to a required component value that matches the given `component_id`. The `storage_type` must match
/// the type associated with `component_id`. The `entity` and `table_row` must correspond to an entity with an uninitialized
/// component matching `component_id`.
///
/// This method _should not_ be called outside of [`BundleInfo::write_components`].
/// For more information, read the [`BundleInfo::write_components`] safety docs.
/// This function inherits the safety requirements defined there.
pub(crate) unsafe fn initialize_required_component(
table: &mut Table,
sparse_sets: &mut SparseSets,
change_tick: Tick,
table_row: TableRow,
entity: Entity,
component_id: ComponentId,
storage_type: StorageType,
component_ptr: OwningPtr,
caller: MaybeLocation,
) {
{
match storage_type {
StorageType::Table => {
let column =
// SAFETY: If component_id is in required_components, BundleInfo::new requires that
// the target table contains the component.
unsafe { table.get_column_mut(component_id).debug_checked_unwrap() };
column.initialize(table_row, component_ptr, change_tick, caller);
}
StorageType::SparseSet => {
let sparse_set =
// SAFETY: If component_id is in required_components, BundleInfo::new requires that
// a sparse set exists for the component.
unsafe { sparse_sets.get_mut(component_id).debug_checked_unwrap() };
sparse_set.insert(entity, component_ptr, change_tick, caller);
}
}
}
}
}
/// The type of archetype move (or lack thereof) that will result from a bundle
/// being inserted into an entity.
pub(crate) enum ArchetypeMoveType {
/// If the entity already has all of the components that are being inserted,
/// its archetype won't change.
SameArchetype,
/// If only [`sparse set`](StorageType::SparseSet) components are being added,
/// the entity's archetype will change while keeping the same table.
NewArchetypeSameTable { new_archetype: NonNull<Archetype> },
/// If any [`table-stored`](StorageType::Table) components are being added,
/// both the entity's archetype and table will change.
NewArchetypeNewTable {
new_archetype: NonNull<Archetype>,
new_table: NonNull<Table>,
},
}
/// Metadata for bundles. Stores a [`BundleInfo`] for each type of [`Bundle`] in a given world.
#[derive(Default)]
pub struct Bundles {
bundle_infos: Vec<BundleInfo>,
/// Cache static [`BundleId`]
bundle_ids: TypeIdMap<BundleId>,
/// Cache bundles, which contains both explicit and required components of [`Bundle`]
contributed_bundle_ids: TypeIdMap<BundleId>,
/// Cache dynamic [`BundleId`] with multiple components
dynamic_bundle_ids: HashMap<Box<[ComponentId]>, BundleId>,
dynamic_bundle_storages: HashMap<BundleId, Vec<StorageType>>,
/// Cache optimized dynamic [`BundleId`] with single component
dynamic_component_bundle_ids: HashMap<ComponentId, BundleId>,
dynamic_component_storages: HashMap<BundleId, StorageType>,
}
impl Bundles {
/// The total number of [`Bundle`] registered in [`Storages`].
pub fn len(&self) -> usize {
self.bundle_infos.len()
}
/// Returns true if no [`Bundle`] registered in [`Storages`].
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Iterate over [`BundleInfo`].
pub fn iter(&self) -> impl Iterator<Item = &BundleInfo> {
self.bundle_infos.iter()
}
/// Gets the metadata associated with a specific type of bundle.
/// Returns `None` if the bundle is not registered with the world.
#[inline]
pub fn get(&self, bundle_id: BundleId) -> Option<&BundleInfo> {
self.bundle_infos.get(bundle_id.index())
}
/// Gets the value identifying a specific type of bundle.
/// Returns `None` if the bundle does not exist in the world,
/// or if `type_id` does not correspond to a type of bundle.
#[inline]
pub fn get_id(&self, type_id: TypeId) -> Option<BundleId> {
self.bundle_ids.get(&type_id).cloned()
}
/// Registers a new [`BundleInfo`] for a statically known type.
///
/// Also registers all the components in the bundle.
///
/// # Safety
///
/// `components` and `storages` must be from the same [`World`] as `self`.
///
/// [`World`]: crate::world::World
#[deny(unsafe_op_in_unsafe_fn)]
pub(crate) unsafe fn register_info<T: Bundle>(
&mut self,
components: &mut ComponentsRegistrator,
storages: &mut Storages,
) -> BundleId {
let bundle_infos = &mut self.bundle_infos;
*self.bundle_ids.entry(TypeId::of::<T>()).or_insert_with(|| {
let component_ids = T::component_ids(components).collect::<Vec<_>>();
let id = BundleId(bundle_infos.len());
let bundle_info =
// SAFETY: T::component_id ensures:
// - its info was created
// - appropriate storage for it has been initialized.
// - it was created in the same order as the components in T
unsafe { BundleInfo::new(core::any::type_name::<T>(), storages, components, component_ids, id) };
bundle_infos.push(bundle_info);
id
})
}
/// Registers a new [`BundleInfo`], which contains both explicit and required components for a statically known type.
///
/// Also registers all the components in the bundle.
///
/// # Safety
///
/// `components` and `storages` must be from the same [`World`] as `self`.
///
/// [`World`]: crate::world::World
#[deny(unsafe_op_in_unsafe_fn)]
pub(crate) unsafe fn register_contributed_bundle_info<T: Bundle>(
&mut self,
components: &mut ComponentsRegistrator,
storages: &mut Storages,
) -> BundleId {
if let Some(id) = self.contributed_bundle_ids.get(&TypeId::of::<T>()).cloned() {
id
} else {
// SAFETY: as per the guarantees of this function, components and
// storages are from the same world as self
let explicit_bundle_id = unsafe { self.register_info::<T>(components, storages) };
// SAFETY: reading from `explicit_bundle_id` and creating new bundle in same time. Its valid because bundle hashmap allow this
let id = unsafe {
let (ptr, len) = {
// SAFETY: `explicit_bundle_id` is valid and defined above
let contributed = self
.get_unchecked(explicit_bundle_id)
.contributed_components();
(contributed.as_ptr(), contributed.len())
};
// SAFETY: this is sound because the contributed_components Vec for explicit_bundle_id will not be accessed mutably as
// part of init_dynamic_info. No mutable references will be created and the allocation will remain valid.
self.init_dynamic_info(storages, components, core::slice::from_raw_parts(ptr, len))
};
self.contributed_bundle_ids.insert(TypeId::of::<T>(), id);
id
}
}
/// # Safety
/// A [`BundleInfo`] with the given [`BundleId`] must have been initialized for this instance of `Bundles`.
pub(crate) unsafe fn get_unchecked(&self, id: BundleId) -> &BundleInfo {
self.bundle_infos.get_unchecked(id.0)
}
/// # Safety
/// This [`BundleId`] must have been initialized with a single [`Component`](crate::component::Component)
/// (via [`init_component_info`](Self::init_dynamic_info))
pub(crate) unsafe fn get_storage_unchecked(&self, id: BundleId) -> StorageType {
*self
.dynamic_component_storages
.get(&id)
.debug_checked_unwrap()
}
/// # Safety
/// This [`BundleId`] must have been initialized with multiple [`Component`](crate::component::Component)s
/// (via [`init_dynamic_info`](Self::init_dynamic_info))
pub(crate) unsafe fn get_storages_unchecked(&mut self, id: BundleId) -> &mut Vec<StorageType> {
self.dynamic_bundle_storages
.get_mut(&id)
.debug_checked_unwrap()
}
/// Initializes a new [`BundleInfo`] for a dynamic [`Bundle`].
///
/// # Panics
///
/// Panics if any of the provided [`ComponentId`]s do not exist in the
/// provided [`Components`].
pub(crate) fn init_dynamic_info(
&mut self,
storages: &mut Storages,
components: &Components,
component_ids: &[ComponentId],
) -> BundleId {
let bundle_infos = &mut self.bundle_infos;
// Use `raw_entry_mut` to avoid cloning `component_ids` to access `Entry`
let (_, bundle_id) = self
.dynamic_bundle_ids
.raw_entry_mut()
.from_key(component_ids)
.or_insert_with(|| {
let (id, storages) = initialize_dynamic_bundle(
bundle_infos,
storages,
components,
Vec::from(component_ids),
);
// SAFETY: The ID always increases when new bundles are added, and so, the ID is unique.
unsafe {
self.dynamic_bundle_storages
.insert_unique_unchecked(id, storages);
}
(component_ids.into(), id)
});
*bundle_id
}
/// Initializes a new [`BundleInfo`] for a dynamic [`Bundle`] with single component.
///
/// # Panics
///
/// Panics if the provided [`ComponentId`] does not exist in the provided [`Components`].
pub(crate) fn init_component_info(
&mut self,
storages: &mut Storages,
components: &Components,
component_id: ComponentId,
) -> BundleId {
let bundle_infos = &mut self.bundle_infos;
let bundle_id = self
.dynamic_component_bundle_ids
.entry(component_id)
.or_insert_with(|| {
let (id, storage_type) = initialize_dynamic_bundle(
bundle_infos,
storages,
components,
vec![component_id],
);
self.dynamic_component_storages.insert(id, storage_type[0]);
id
});
*bundle_id
}
}
/// Asserts that all components are part of [`Components`]
/// and initializes a [`BundleInfo`].
fn initialize_dynamic_bundle(
bundle_infos: &mut Vec<BundleInfo>,
storages: &mut Storages,
components: &Components,
component_ids: Vec<ComponentId>,
) -> (BundleId, Vec<StorageType>) {
// Assert component existence
let storage_types = component_ids.iter().map(|&id| {
components.get_info(id).unwrap_or_else(|| {
panic!(
"init_dynamic_info called with component id {id:?} which doesn't exist in this world"
)
}).storage_type()
}).collect();
let id = BundleId(bundle_infos.len());
let bundle_info =
// SAFETY: `component_ids` are valid as they were just checked
unsafe { BundleInfo::new("<dynamic bundle>", storages, components, component_ids, id) };
bundle_infos.push(bundle_info);
(id, storage_types)
}
| 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/bundle/mod.rs | crates/bevy_ecs/src/bundle/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."
)]
//! Types for handling [`Bundle`]s.
//!
//! This module contains the [`Bundle`] trait and some other helper types.
mod impls;
mod info;
mod insert;
mod remove;
mod spawner;
#[cfg(test)]
mod tests;
pub(crate) use insert::BundleInserter;
pub(crate) use remove::BundleRemover;
pub(crate) use spawner::BundleSpawner;
use bevy_ptr::MovingPtr;
use core::mem::MaybeUninit;
pub use info::*;
/// Derive the [`Bundle`] trait
///
/// You can apply this derive macro to structs that are
/// composed of [`Component`](crate::component::Component)s or
/// other [`Bundle`]s.
///
/// ## Attributes
///
/// Sometimes parts of the Bundle should not be inserted.
/// Those can be marked with `#[bundle(ignore)]`, and they will be skipped.
/// In that case, the field needs to implement [`Default`] unless you also ignore
/// the [`BundleFromComponents`] implementation.
///
/// ```rust
/// # use bevy_ecs::prelude::{Component, Bundle};
/// # #[derive(Component)]
/// # struct Hitpoint;
/// #
/// #[derive(Bundle)]
/// struct HitpointMarker {
/// hitpoints: Hitpoint,
///
/// #[bundle(ignore)]
/// creator: Option<String>
/// }
/// ```
///
/// Some fields may be bundles that do not implement
/// [`BundleFromComponents`]. This happens for bundles that cannot be extracted.
/// For example with [`SpawnRelatedBundle`](bevy_ecs::spawn::SpawnRelatedBundle), see below for an
/// example usage.
/// In those cases you can either ignore it as above,
/// or you can opt out the whole Struct by marking it as ignored with
/// `#[bundle(ignore_from_components)]`.
///
/// ```rust
/// # use bevy_ecs::prelude::{Component, Bundle, ChildOf, Spawn};
/// # #[derive(Component)]
/// # struct Hitpoint;
/// # #[derive(Component)]
/// # struct Marker;
/// #
/// use bevy_ecs::spawn::SpawnRelatedBundle;
///
/// #[derive(Bundle)]
/// #[bundle(ignore_from_components)]
/// struct HitpointMarker {
/// hitpoints: Hitpoint,
/// related_spawner: SpawnRelatedBundle<ChildOf, Spawn<Marker>>,
/// }
/// ```
pub use bevy_ecs_macros::Bundle;
use crate::{
component::{ComponentId, Components, ComponentsRegistrator, StorageType},
world::EntityWorldMut,
};
use bevy_ptr::OwningPtr;
/// The `Bundle` trait enables insertion and removal of [`Component`]s from an entity.
///
/// Implementers of the `Bundle` trait are called 'bundles'.
///
/// Each bundle represents a static set of [`Component`] types.
/// Currently, bundles can only contain one of each [`Component`], and will
/// panic once initialized if this is not met.
///
/// ## Insertion
///
/// The primary use for bundles is to add a useful collection of components to an entity.
///
/// Adding a value of bundle to an entity will add the components from the set it
/// represents to the entity.
/// The values of these components are taken from the bundle.
/// If an entity already had one of these components, the entity's original component value
/// will be overwritten.
///
/// Importantly, bundles are only their constituent set of components.
/// You **should not** use bundles as a unit of behavior.
/// The behavior of your app can only be considered in terms of components, as systems,
/// which drive the behavior of a `bevy` application, operate on combinations of
/// components.
///
/// This rule is also important because multiple bundles may contain the same component type,
/// calculated in different ways — adding both of these bundles to one entity
/// would create incoherent behavior.
/// This would be unexpected if bundles were treated as an abstraction boundary, as
/// the abstraction would be unmaintainable for these cases.
///
/// For this reason, there is intentionally no [`Query`] to match whether an entity
/// contains the components of a bundle.
/// Queries should instead only select the components they logically operate on.
///
/// ## Removal
///
/// Bundles are also used when removing components from an entity.
///
/// Removing a bundle from an entity will remove any of its components attached
/// to the entity from the entity.
/// That is, if the entity does not have all the components of the bundle, those
/// which are present will be removed.
///
/// # Implementers
///
/// Every type which implements [`Component`] also implements `Bundle`, since
/// [`Component`] types can be added to or removed from an entity.
///
/// Additionally, [Tuples](`tuple`) of bundles are also [`Bundle`] (with up to 15 bundles).
/// These bundles contain the items of the 'inner' bundles.
/// This is a convenient shorthand which is primarily used when spawning entities.
///
/// [`unit`], otherwise known as [`()`](`unit`), is a [`Bundle`] containing no components (since it
/// can also be considered as the empty tuple).
/// This can be useful for spawning large numbers of empty entities using
/// [`World::spawn_batch`](crate::world::World::spawn_batch).
///
/// Tuple bundles can be nested, which can be used to create an anonymous bundle with more than
/// 15 items.
/// However, in most cases where this is required, the derive macro [`derive@Bundle`] should be
/// used instead.
/// The derived `Bundle` implementation contains the items of its fields, which all must
/// implement `Bundle`.
/// As explained above, this includes any [`Component`] type, and other derived bundles.
///
/// If you want to add `PhantomData` to your `Bundle` you have to mark it with `#[bundle(ignore)]`.
/// ```
/// # use std::marker::PhantomData;
/// use bevy_ecs::{component::Component, bundle::Bundle};
///
/// #[derive(Component)]
/// struct XPosition(i32);
/// #[derive(Component)]
/// struct YPosition(i32);
///
/// #[derive(Bundle)]
/// struct PositionBundle {
/// // A bundle can contain components
/// x: XPosition,
/// y: YPosition,
/// }
///
/// // You have to implement `Default` for ignored field types in bundle structs.
/// #[derive(Default)]
/// struct Other(f32);
///
/// #[derive(Bundle)]
/// struct NamedPointBundle<T: Send + Sync + 'static> {
/// // Or other bundles
/// a: PositionBundle,
/// // In addition to more components
/// z: PointName,
///
/// // when you need to use `PhantomData` you have to mark it as ignored
/// #[bundle(ignore)]
/// _phantom_data: PhantomData<T>
/// }
///
/// #[derive(Component)]
/// struct PointName(String);
/// ```
///
/// # Safety
///
/// Manual implementations of this trait are unsupported.
/// That is, there is no safe way to implement this trait, and you must not do so.
/// If you want a type to implement [`Bundle`], you must use [`derive@Bundle`](derive@Bundle).
///
/// [`Component`]: crate::component::Component
/// [`Query`]: crate::system::Query
// Some safety points:
// - [`Bundle::component_ids`] must return the [`ComponentId`] for each component type in the
// bundle, in the _exact_ order that [`DynamicBundle::get_components`] is called.
// - [`Bundle::from_components`] must call `func` exactly once for each [`ComponentId`] returned by
// [`Bundle::component_ids`].
#[diagnostic::on_unimplemented(
message = "`{Self}` is not a `Bundle`",
label = "invalid `Bundle`",
note = "consider annotating `{Self}` with `#[derive(Component)]` or `#[derive(Bundle)]`"
)]
pub unsafe trait Bundle: DynamicBundle + Send + Sync + 'static {
/// Gets this [`Bundle`]'s component ids, in the order of this bundle's [`Component`]s
/// This will register the component if it doesn't exist.
#[doc(hidden)]
fn component_ids(
components: &mut ComponentsRegistrator,
) -> impl Iterator<Item = ComponentId> + use<Self>;
/// Return a iterator over this [`Bundle`]'s component ids. This will be [`None`] if the component has not been registered.
fn get_component_ids(components: &Components) -> impl Iterator<Item = Option<ComponentId>>;
}
/// Creates a [`Bundle`] by taking it from internal storage.
///
/// # Safety
///
/// Manual implementations of this trait are unsupported.
/// That is, there is no safe way to implement this trait, and you must not do so.
/// If you want a type to implement [`Bundle`], you must use [`derive@Bundle`](derive@Bundle).
///
/// [`Query`]: crate::system::Query
// Some safety points:
// - [`Bundle::component_ids`] must return the [`ComponentId`] for each component type in the
// bundle, in the _exact_ order that [`DynamicBundle::get_components`] is called.
// - [`Bundle::from_components`] must call `func` exactly once for each [`ComponentId`] returned by
// [`Bundle::component_ids`].
pub unsafe trait BundleFromComponents {
/// Calls `func`, which should return data for each component in the bundle, in the order of
/// this bundle's [`Component`]s
///
/// # Safety
/// Caller must return data for each component in the bundle, in the order of this bundle's
/// [`Component`]s
#[doc(hidden)]
unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> Self
where
// Ensure that the `OwningPtr` is used correctly
F: for<'a> FnMut(&'a mut T) -> OwningPtr<'a>,
Self: Sized;
}
/// The parts from [`Bundle`] that don't require statically knowing the components of the bundle.
pub trait DynamicBundle: Sized {
/// An operation on the entity that happens _after_ inserting this bundle.
type Effect;
/// Moves the components out of the bundle.
///
/// # Safety
/// For callers:
/// - Must be called exactly once before `apply_effect`
/// - The `StorageType` argument passed into `func` must be correct for the component being fetched.
/// - `apply_effect` must be called exactly once after this has been called if `Effect: !NoBundleEffect`
///
/// For implementors:
/// - Implementors of this function must convert `ptr` into pointers to individual components stored within
/// `Self` and call `func` on each of them in exactly the same order as [`Bundle::get_component_ids`] and
/// [`BundleFromComponents::from_components`].
/// - If any part of `ptr` is to be accessed in `apply_effect`, it must *not* be dropped at any point in this
/// function. Calling [`bevy_ptr::deconstruct_moving_ptr`] in this function automatically ensures this.
///
/// [`Component`]: crate::component::Component
// 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.
unsafe fn get_components(
ptr: MovingPtr<'_, Self>,
func: &mut impl FnMut(StorageType, OwningPtr<'_>),
);
/// Applies the after-effects of spawning this bundle.
///
/// This is applied after all residual changes to the [`World`], including flushing the internal command
/// queue.
///
/// # Safety
/// For callers:
/// - Must be called exactly once after `get_components` has been called.
/// - `ptr` must point to the instance of `Self` that `get_components` was called on,
/// all of fields that were moved out of in `get_components` will not be valid anymore.
///
/// For implementors:
/// - If any part of `ptr` is to be accessed in this function, it must *not* be dropped at any point in
/// `get_components`. Calling [`bevy_ptr::deconstruct_moving_ptr`] in `get_components` automatically
/// ensures this is the case.
///
/// [`World`]: crate::world::World
// 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.
unsafe fn apply_effect(ptr: MovingPtr<'_, MaybeUninit<Self>>, entity: &mut EntityWorldMut);
}
/// A trait implemented for [`DynamicBundle::Effect`] implementations that do nothing. This is used as a type constraint for
/// [`Bundle`] APIs that do not / cannot run [`DynamicBundle::Effect`], such as "batch spawn" APIs.
pub trait NoBundleEffect {}
| 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/bundle/impls.rs | crates/bevy_ecs/src/bundle/impls.rs | use core::{any::TypeId, iter};
use bevy_ptr::{MovingPtr, OwningPtr};
use core::mem::MaybeUninit;
use variadics_please::all_tuples_enumerated;
use crate::{
bundle::{Bundle, BundleFromComponents, DynamicBundle, NoBundleEffect},
component::{Component, ComponentId, Components, ComponentsRegistrator, StorageType},
world::EntityWorldMut,
};
// SAFETY:
// - `Bundle::component_ids` calls `ids` for C's component id (and nothing else)
// - `Bundle::get_components` is called exactly once for C and passes the component's storage type based on its associated constant.
unsafe impl<C: Component> Bundle for C {
fn component_ids(
components: &mut ComponentsRegistrator,
) -> impl Iterator<Item = ComponentId> + use<C> {
iter::once(components.register_component::<C>())
}
fn get_component_ids(components: &Components) -> impl Iterator<Item = Option<ComponentId>> {
iter::once(components.get_id(TypeId::of::<C>()))
}
}
// SAFETY:
// - `Bundle::from_components` calls `func` exactly once for C, which is the exact value returned by `Bundle::component_ids`.
unsafe impl<C: Component> BundleFromComponents for C {
unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> Self
where
// Ensure that the `OwningPtr` is used correctly
F: for<'a> FnMut(&'a mut T) -> OwningPtr<'a>,
Self: Sized,
{
let ptr = func(ctx);
// Safety: The id given in `component_ids` is for `Self`
unsafe { ptr.read() }
}
}
impl<C: Component> DynamicBundle for C {
type Effect = ();
#[inline]
unsafe fn get_components(
ptr: MovingPtr<'_, Self>,
func: &mut impl FnMut(StorageType, OwningPtr<'_>),
) -> Self::Effect {
func(C::STORAGE_TYPE, OwningPtr::from(ptr));
}
#[inline]
unsafe fn apply_effect(_ptr: MovingPtr<'_, MaybeUninit<Self>>, _entity: &mut EntityWorldMut) {}
}
macro_rules! tuple_impl {
($(#[$meta:meta])* $(($index:tt, $name: ident, $alias: ident)),*) => {
#[expect(
clippy::allow_attributes,
reason = "This is a tuple-related macro; as such, the lints below may not always apply."
)]
#[allow(
unused_mut,
unused_variables,
reason = "Zero-length tuples won't use any of the parameters."
)]
$(#[$meta])*
// SAFETY:
// - `Bundle::component_ids` calls `ids` for each component type in the
// bundle, in the exact order that `DynamicBundle::get_components` is called.
// - `Bundle::from_components` calls `func` exactly once for each `ComponentId` returned by `Bundle::component_ids`.
// - `Bundle::get_components` is called exactly once for each member. Relies on the above implementation to pass the correct
// `StorageType` into the callback.
unsafe impl<$($name: Bundle),*> Bundle for ($($name,)*) {
fn component_ids<'a>(components: &'a mut ComponentsRegistrator) -> impl Iterator<Item = ComponentId> + use<$($name,)*> {
iter::empty()$(.chain(<$name as Bundle>::component_ids(components)))*
}
fn get_component_ids(components: &Components) -> impl Iterator<Item = Option<ComponentId>> {
iter::empty()$(.chain(<$name as Bundle>::get_component_ids(components)))*
}
}
#[expect(
clippy::allow_attributes,
reason = "This is a tuple-related macro; as such, the lints below may not always apply."
)]
#[allow(
unused_mut,
unused_variables,
reason = "Zero-length tuples won't use any of the parameters."
)]
$(#[$meta])*
// SAFETY:
// - `Bundle::component_ids` calls `ids` for each component type in the
// bundle, in the exact order that `DynamicBundle::get_components` is called.
// - `Bundle::from_components` calls `func` exactly once for each `ComponentId` returned by `Bundle::component_ids`.
// - `Bundle::get_components` is called exactly once for each member. Relies on the above implementation to pass the correct
// `StorageType` into the callback.
unsafe impl<$($name: BundleFromComponents),*> BundleFromComponents for ($($name,)*) {
#[allow(
clippy::unused_unit,
reason = "Zero-length tuples will generate a function body 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."
)]
unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> Self
where
F: FnMut(&mut T) -> OwningPtr<'_>
{
#[allow(
unused_unsafe,
reason = "Zero-length tuples will not run anything in the unsafe block. Additionally, rewriting this to move the () outside of the unsafe would require putting the safety comment inside the tuple, hurting readability of the code."
)]
// SAFETY: Rust guarantees that tuple calls are evaluated 'left to right'.
// https://doc.rust-lang.org/reference/expressions.html#evaluation-order-of-operands
unsafe { ($(<$name as BundleFromComponents>::from_components(ctx, func),)*) }
}
}
#[expect(
clippy::allow_attributes,
reason = "This is a tuple-related macro; as such, the lints below may not always apply."
)]
#[allow(
unused_mut,
unused_variables,
reason = "Zero-length tuples won't use any of the parameters."
)]
$(#[$meta])*
impl<$($name: Bundle),*> DynamicBundle for ($($name,)*) {
type Effect = ($($name::Effect,)*);
#[allow(
clippy::unused_unit,
reason = "Zero-length tuples will generate a function body 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."
)]
#[inline(always)]
unsafe fn get_components(ptr: MovingPtr<'_, Self>, func: &mut impl FnMut(StorageType, OwningPtr<'_>)) {
bevy_ptr::deconstruct_moving_ptr!({
let tuple { $($index: $alias,)* } = ptr;
});
#[allow(
unused_unsafe,
reason = "Zero-length tuples will generate a function body equivalatent 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: Caller ensures requirements for calling `get_components` are met.
unsafe {
$( $name::get_components($alias, func); )*
}
}
#[allow(
clippy::unused_unit,
reason = "Zero-length tuples will generate a function body 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."
)]
#[inline(always)]
unsafe fn apply_effect(ptr: MovingPtr<'_, MaybeUninit<Self>>, entity: &mut EntityWorldMut) {
bevy_ptr::deconstruct_moving_ptr!({
let MaybeUninit::<tuple> { $($index: $alias,)* } = ptr;
});
#[allow(
unused_unsafe,
reason = "Zero-length tuples will generate a function body 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: Caller ensures requirements for calling `apply_effect` are met.
unsafe {
$( $name::apply_effect($alias, entity); )*
}
}
}
$(#[$meta])*
impl<$($name: NoBundleEffect),*> NoBundleEffect for ($($name,)*) {}
}
}
all_tuples_enumerated!(
#[doc(fake_variadic)]
tuple_impl,
0,
15,
B,
field_
);
| 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/bundle/remove.rs | crates/bevy_ecs/src/bundle/remove.rs | use alloc::vec::Vec;
use bevy_ptr::ConstNonNull;
use core::ptr::NonNull;
use crate::{
archetype::{Archetype, ArchetypeCreated, ArchetypeId, Archetypes},
bundle::{Bundle, BundleId, BundleInfo},
change_detection::MaybeLocation,
component::{ComponentId, Components, StorageType},
entity::{Entity, EntityLocation},
event::EntityComponentsTrigger,
lifecycle::{Remove, Replace, REMOVE, REPLACE},
observer::Observers,
relationship::RelationshipHookMode,
storage::{SparseSets, Storages, Table},
world::{unsafe_world_cell::UnsafeWorldCell, World},
};
// SAFETY: We have exclusive world access so our pointers can't be invalidated externally
pub(crate) struct BundleRemover<'w> {
world: UnsafeWorldCell<'w>,
bundle_info: ConstNonNull<BundleInfo>,
old_and_new_table: Option<(NonNull<Table>, NonNull<Table>)>,
old_archetype: NonNull<Archetype>,
new_archetype: NonNull<Archetype>,
pub(crate) relationship_hook_mode: RelationshipHookMode,
}
impl<'w> BundleRemover<'w> {
/// Creates a new [`BundleRemover`], if such a remover would do anything.
///
/// If `require_all` is true, the [`BundleRemover`] is only created if the entire bundle is present on the archetype.
///
/// # Safety
/// Caller must ensure that `archetype_id` is valid
#[inline]
#[deny(unsafe_op_in_unsafe_fn)]
pub(crate) unsafe fn new<T: Bundle>(
world: &'w mut World,
archetype_id: ArchetypeId,
require_all: bool,
) -> Option<Self> {
let bundle_id = world.register_bundle_info::<T>();
// SAFETY: we initialized this bundle_id in `init_info`, and caller ensures archetype is valid.
unsafe { Self::new_with_id(world, archetype_id, bundle_id, require_all) }
}
/// Creates a new [`BundleRemover`], if such a remover would do anything.
///
/// If `require_all` is true, the [`BundleRemover`] is only created if the entire bundle is present on the archetype.
///
/// # Safety
/// Caller must ensure that `bundle_id` exists in `world.bundles` and `archetype_id` is valid.
#[inline]
pub(crate) unsafe fn new_with_id(
world: &'w mut World,
archetype_id: ArchetypeId,
bundle_id: BundleId,
require_all: bool,
) -> Option<Self> {
let bundle_info = world.bundles.get_unchecked(bundle_id);
// SAFETY: Caller ensures archetype and bundle ids are correct.
let (new_archetype_id, is_new_created) = unsafe {
bundle_info.remove_bundle_from_archetype(
&mut world.archetypes,
&mut world.storages,
&world.components,
&world.observers,
archetype_id,
!require_all,
)
};
let new_archetype_id = new_archetype_id?;
if new_archetype_id == archetype_id {
return None;
}
let (old_archetype, new_archetype) =
world.archetypes.get_2_mut(archetype_id, new_archetype_id);
let tables = if old_archetype.table_id() == new_archetype.table_id() {
None
} else {
let (old, new) = world
.storages
.tables
.get_2_mut(old_archetype.table_id(), new_archetype.table_id());
Some((old.into(), new.into()))
};
let remover = Self {
bundle_info: bundle_info.into(),
new_archetype: new_archetype.into(),
old_archetype: old_archetype.into(),
old_and_new_table: tables,
world: world.as_unsafe_world_cell(),
relationship_hook_mode: RelationshipHookMode::Run,
};
if is_new_created {
remover
.world
.into_deferred()
.trigger(ArchetypeCreated(new_archetype_id));
}
Some(remover)
}
/// This can be passed to [`remove`](Self::remove) as the `pre_remove` function if you don't want to do anything before removing.
pub fn empty_pre_remove(
_: &mut SparseSets,
_: Option<&mut Table>,
_: &Components,
_: &[ComponentId],
) -> (bool, ()) {
(true, ())
}
/// Performs the removal.
///
/// `pre_remove` should return a bool for if the components still need to be dropped.
///
/// # Safety
/// The `location` must have the same archetype as the remover.
#[inline]
pub(crate) unsafe fn remove<T: 'static>(
&mut self,
entity: Entity,
location: EntityLocation,
caller: MaybeLocation,
pre_remove: impl FnOnce(
&mut SparseSets,
Option<&mut Table>,
&Components,
&[ComponentId],
) -> (bool, T),
) -> (EntityLocation, T) {
// Hooks
// SAFETY: all bundle components exist in World
unsafe {
// SAFETY: We only keep access to archetype/bundle data.
let mut deferred_world = self.world.into_deferred();
let bundle_components_in_archetype = || {
self.bundle_info
.as_ref()
.iter_explicit_components()
.filter(|component_id| self.old_archetype.as_ref().contains(*component_id))
};
if self.old_archetype.as_ref().has_replace_observer() {
let components = bundle_components_in_archetype().collect::<Vec<_>>();
// SAFETY: the REPLACE event_key corresponds to the Replace event's type
deferred_world.trigger_raw(
REPLACE,
&mut Replace { entity },
&mut EntityComponentsTrigger {
components: &components,
},
caller,
);
}
deferred_world.trigger_on_replace(
self.old_archetype.as_ref(),
entity,
bundle_components_in_archetype(),
caller,
self.relationship_hook_mode,
);
if self.old_archetype.as_ref().has_remove_observer() {
let components = bundle_components_in_archetype().collect::<Vec<_>>();
// SAFETY: the REMOVE event_key corresponds to the Remove event's type
deferred_world.trigger_raw(
REMOVE,
&mut Remove { entity },
&mut EntityComponentsTrigger {
components: &components,
},
caller,
);
}
deferred_world.trigger_on_remove(
self.old_archetype.as_ref(),
entity,
bundle_components_in_archetype(),
caller,
);
}
// SAFETY: We still have the cell, so this is unique, it doesn't conflict with other references, and we drop it shortly.
let world = unsafe { self.world.world_mut() };
let (needs_drop, pre_remove_result) = pre_remove(
&mut world.storages.sparse_sets,
self.old_and_new_table
.as_ref()
// SAFETY: There is no conflicting access for this scope.
.map(|(old, _)| unsafe { &mut *old.as_ptr() }),
&world.components,
self.bundle_info.as_ref().explicit_components(),
);
// Handle sparse set removes
for component_id in self.bundle_info.as_ref().iter_explicit_components() {
if self.old_archetype.as_ref().contains(component_id) {
world.removed_components.write(component_id, entity);
// Make sure to drop components stored in sparse sets.
// Dense components are dropped later in `move_to_and_drop_missing_unchecked`.
if let Some(StorageType::SparseSet) =
self.old_archetype.as_ref().get_storage_type(component_id)
{
world
.storages
.sparse_sets
.get_mut(component_id)
// Set exists because the component existed on the entity
.unwrap()
// If it was already forgotten, it would not be in the set.
.remove(entity);
}
}
}
// Handle archetype change
let remove_result = self
.old_archetype
.as_mut()
.swap_remove(location.archetype_row);
// if an entity was moved into this entity's archetype row, update its archetype row
if let Some(swapped_entity) = remove_result.swapped_entity {
let swapped_location = world.entities.get_spawned(swapped_entity).unwrap();
world.entities.update_existing_location(
swapped_entity.index(),
Some(EntityLocation {
archetype_id: swapped_location.archetype_id,
archetype_row: location.archetype_row,
table_id: swapped_location.table_id,
table_row: swapped_location.table_row,
}),
);
}
// Handle table change
let new_location = if let Some((mut old_table, mut new_table)) = self.old_and_new_table {
let move_result = if needs_drop {
// SAFETY: old_table_row exists
unsafe {
old_table
.as_mut()
.move_to_and_drop_missing_unchecked(location.table_row, new_table.as_mut())
}
} else {
// SAFETY: old_table_row exists
unsafe {
old_table.as_mut().move_to_and_forget_missing_unchecked(
location.table_row,
new_table.as_mut(),
)
}
};
// SAFETY: move_result.new_row is a valid position in new_archetype's table
let new_location = unsafe {
self.new_archetype
.as_mut()
.allocate(entity, move_result.new_row)
};
// if an entity was moved into this entity's table row, update its table row
if let Some(swapped_entity) = move_result.swapped_entity {
let swapped_location = world.entities.get_spawned(swapped_entity).unwrap();
world.entities.update_existing_location(
swapped_entity.index(),
Some(EntityLocation {
archetype_id: swapped_location.archetype_id,
archetype_row: swapped_location.archetype_row,
table_id: swapped_location.table_id,
table_row: location.table_row,
}),
);
world.archetypes[swapped_location.archetype_id]
.set_entity_table_row(swapped_location.archetype_row, location.table_row);
}
new_location
} else {
// The tables are the same
self.new_archetype
.as_mut()
.allocate(entity, location.table_row)
};
// SAFETY: The entity is valid and has been moved to the new location already.
unsafe {
world
.entities
.update_existing_location(entity.index(), Some(new_location));
}
(new_location, pre_remove_result)
}
}
impl BundleInfo {
/// Removes a bundle from the given archetype and returns the resulting archetype and whether a new archetype was created.
/// (or `None` if the removal was invalid).
/// This could be the same [`ArchetypeId`], in the event that removing the given bundle
/// does not result in an [`Archetype`] change.
///
/// Results are cached in the [`Archetype`] graph to avoid redundant work.
///
/// If `intersection` is false, attempting to remove a bundle with components not contained in the
/// current archetype will fail, returning `None`.
///
/// If `intersection` is true, components in the bundle but not in the current archetype
/// will be ignored.
///
/// # Safety
/// `archetype_id` must exist and components in `bundle_info` must exist
pub(crate) unsafe fn remove_bundle_from_archetype(
&self,
archetypes: &mut Archetypes,
storages: &mut Storages,
components: &Components,
observers: &Observers,
archetype_id: ArchetypeId,
intersection: bool,
) -> (Option<ArchetypeId>, bool) {
// Check the archetype graph to see if the bundle has been
// removed from this archetype in the past.
let archetype_after_remove_result = {
let edges = archetypes[archetype_id].edges();
if intersection {
edges.get_archetype_after_bundle_remove(self.id())
} else {
edges.get_archetype_after_bundle_take(self.id())
}
};
let (result, is_new_created) = if let Some(result) = archetype_after_remove_result {
// This bundle removal result is cached. Just return that!
(result, false)
} else {
let mut next_table_components;
let mut next_sparse_set_components;
let next_table_id;
{
let current_archetype = &mut archetypes[archetype_id];
let mut removed_table_components = Vec::new();
let mut removed_sparse_set_components = Vec::new();
for component_id in self.iter_explicit_components() {
if current_archetype.contains(component_id) {
// SAFETY: bundle components were already initialized by bundles.get_info
let component_info = unsafe { components.get_info_unchecked(component_id) };
match component_info.storage_type() {
StorageType::Table => removed_table_components.push(component_id),
StorageType::SparseSet => {
removed_sparse_set_components.push(component_id);
}
}
} else if !intersection {
// A component in the bundle was not present in the entity's archetype, so this
// removal is invalid. Cache the result in the archetype graph.
current_archetype
.edges_mut()
.cache_archetype_after_bundle_take(self.id(), None);
return (None, false);
}
}
// Sort removed components so we can do an efficient "sorted remove".
// Archetype components are already sorted.
removed_table_components.sort_unstable();
removed_sparse_set_components.sort_unstable();
next_table_components = current_archetype.table_components().collect();
next_sparse_set_components = current_archetype.sparse_set_components().collect();
sorted_remove(&mut next_table_components, &removed_table_components);
sorted_remove(
&mut next_sparse_set_components,
&removed_sparse_set_components,
);
next_table_id = if removed_table_components.is_empty() {
current_archetype.table_id()
} else {
// SAFETY: all components in next_table_components exist
unsafe {
storages
.tables
.get_id_or_insert(&next_table_components, components)
}
};
}
let (new_archetype_id, is_new_created) = archetypes.get_id_or_insert(
components,
observers,
next_table_id,
next_table_components,
next_sparse_set_components,
);
(Some(new_archetype_id), is_new_created)
};
let current_archetype = &mut archetypes[archetype_id];
// Cache the result in an edge.
if intersection {
current_archetype
.edges_mut()
.cache_archetype_after_bundle_remove(self.id(), result);
} else {
current_archetype
.edges_mut()
.cache_archetype_after_bundle_take(self.id(), result);
}
(result, is_new_created)
}
}
fn sorted_remove<T: Eq + Ord + Copy>(source: &mut Vec<T>, remove: &[T]) {
let mut remove_index = 0;
source.retain(|value| {
while remove_index < remove.len() && *value > remove[remove_index] {
remove_index += 1;
}
if remove_index < remove.len() {
*value != remove[remove_index]
} else {
true
}
});
}
#[cfg(test)]
mod tests {
use alloc::vec;
#[test]
fn sorted_remove() {
let mut a = vec![1, 2, 3, 4, 5, 6, 7];
let b = vec![1, 2, 3, 5, 7];
super::sorted_remove(&mut a, &b);
assert_eq!(a, vec![4, 6]);
let mut a = vec![1];
let b = vec![1];
super::sorted_remove(&mut a, &b);
assert_eq!(a, vec![]);
let mut a = vec![1];
let b = vec![2];
super::sorted_remove(&mut a, &b);
assert_eq!(a, vec![1]);
}
}
| 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/change_detection/maybe_location.rs | crates/bevy_ecs/src/change_detection/maybe_location.rs | #[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
use core::{
marker::PhantomData,
ops::{Deref, DerefMut},
panic::Location,
};
/// A value that contains a `T` if the `track_location` feature is enabled,
/// and is a ZST if it is not.
///
/// The overall API is similar to [`Option`], but whether the value is `Some` or `None` is set at compile
/// time and is the same for all values.
///
/// If the `track_location` feature is disabled, then all functions on this type that return
/// an `MaybeLocation` will have an empty body and should be removed by the optimizer.
///
/// This allows code to be written that will be checked by the compiler even when the feature is disabled,
/// but that will be entirely removed during compilation.
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct MaybeLocation<T: ?Sized = &'static Location<'static>> {
#[cfg_attr(feature = "bevy_reflect", reflect(ignore, clone))]
marker: PhantomData<T>,
#[cfg(feature = "track_location")]
value: T,
}
impl<T: core::fmt::Display> core::fmt::Display for MaybeLocation<T> {
fn fmt(&self, _f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
#[cfg(feature = "track_location")]
{
self.value.fmt(_f)?;
}
Ok(())
}
}
impl<T> MaybeLocation<T> {
/// Constructs a new `MaybeLocation` that wraps the given value.
///
/// This may only accept `Copy` types,
/// since it needs to drop the value if the `track_location` feature is disabled,
/// and non-`Copy` types cannot be dropped in `const` context.
/// Use [`new_with`][Self::new_with] if you need to construct a non-`Copy` value.
///
/// # See also
/// - [`new_with`][Self::new_with] to initialize using a closure.
/// - [`new_with_flattened`][Self::new_with_flattened] to initialize using a closure that returns an `Option<MaybeLocation<T>>`.
#[inline]
pub const fn new(_value: T) -> Self
where
T: Copy,
{
Self {
#[cfg(feature = "track_location")]
value: _value,
marker: PhantomData,
}
}
/// Constructs a new `MaybeLocation` that wraps the result of the given closure.
///
/// # See also
/// - [`new`][Self::new] to initialize using a value.
/// - [`new_with_flattened`][Self::new_with_flattened] to initialize using a closure that returns an `Option<MaybeLocation<T>>`.
#[inline]
pub fn new_with(_f: impl FnOnce() -> T) -> Self {
Self {
#[cfg(feature = "track_location")]
value: _f(),
marker: PhantomData,
}
}
/// Maps an `MaybeLocation<T> `to `MaybeLocation<U>` by applying a function to a contained value.
#[inline]
pub fn map<U>(self, _f: impl FnOnce(T) -> U) -> MaybeLocation<U> {
MaybeLocation {
#[cfg(feature = "track_location")]
value: _f(self.value),
marker: PhantomData,
}
}
/// Converts a pair of `MaybeLocation` values to an `MaybeLocation` of a tuple.
#[inline]
pub fn zip<U>(self, _other: MaybeLocation<U>) -> MaybeLocation<(T, U)> {
MaybeLocation {
#[cfg(feature = "track_location")]
value: (self.value, _other.value),
marker: PhantomData,
}
}
/// Returns the contained value or a default.
/// If the `track_location` feature is enabled, this always returns the contained value.
/// If it is disabled, this always returns `T::Default()`.
#[inline]
pub fn unwrap_or_default(self) -> T
where
T: Default,
{
self.into_option().unwrap_or_default()
}
/// Converts an `MaybeLocation` to an [`Option`] to allow run-time branching.
/// If the `track_location` feature is enabled, this always returns `Some`.
/// If it is disabled, this always returns `None`.
#[inline]
pub fn into_option(self) -> Option<T> {
#[cfg(feature = "track_location")]
{
Some(self.value)
}
#[cfg(not(feature = "track_location"))]
{
None
}
}
}
impl<T> MaybeLocation<Option<T>> {
/// Constructs a new `MaybeLocation` that wraps the result of the given closure.
/// If the closure returns `Some`, it unwraps the inner value.
///
/// # See also
/// - [`new`][Self::new] to initialize using a value.
/// - [`new_with`][Self::new_with] to initialize using a closure.
#[inline]
pub fn new_with_flattened(_f: impl FnOnce() -> Option<MaybeLocation<T>>) -> Self {
Self {
#[cfg(feature = "track_location")]
value: _f().map(|value| value.value),
marker: PhantomData,
}
}
/// Transposes a `MaybeLocation` of an [`Option`] into an [`Option`] of a `MaybeLocation`.
///
/// This can be useful if you want to use the `?` operator to exit early
/// if the `track_location` feature is enabled but the value is not found.
///
/// If the `track_location` feature is enabled,
/// this returns `Some` if the inner value is `Some`
/// and `None` if the inner value is `None`.
///
/// If it is disabled, this always returns `Some`.
///
/// # Example
///
/// ```
/// # use bevy_ecs::{change_detection::MaybeLocation, world::World};
/// # use core::panic::Location;
/// #
/// # fn test() -> Option<()> {
/// let mut world = World::new();
/// let entity = world.spawn(()).id();
/// let location: MaybeLocation<Option<&'static Location<'static>>> =
/// world.entities().entity_get_spawned_or_despawned_by(entity);
/// let location: MaybeLocation<&'static Location<'static>> = location.transpose()?;
/// # Some(())
/// # }
/// # test();
/// ```
///
/// # See also
///
/// - [`into_option`][Self::into_option] to convert to an `Option<Option<T>>`.
/// When used with [`Option::flatten`], this will have a similar effect,
/// but will return `None` when the `track_location` feature is disabled.
#[inline]
pub fn transpose(self) -> Option<MaybeLocation<T>> {
#[cfg(feature = "track_location")]
{
self.value.map(|value| MaybeLocation {
value,
marker: PhantomData,
})
}
#[cfg(not(feature = "track_location"))]
{
Some(MaybeLocation {
marker: PhantomData,
})
}
}
}
impl<T> MaybeLocation<&T> {
/// Maps an `MaybeLocation<&T>` to an `MaybeLocation<T>` by copying the contents.
#[inline]
pub const fn copied(&self) -> MaybeLocation<T>
where
T: Copy,
{
MaybeLocation {
#[cfg(feature = "track_location")]
value: *self.value,
marker: PhantomData,
}
}
}
impl<T> MaybeLocation<&mut T> {
/// Maps an `MaybeLocation<&mut T>` to an `MaybeLocation<T>` by copying the contents.
#[inline]
pub const fn copied(&self) -> MaybeLocation<T>
where
T: Copy,
{
MaybeLocation {
#[cfg(feature = "track_location")]
value: *self.value,
marker: PhantomData,
}
}
/// Assigns the contents of an `MaybeLocation<T>` to an `MaybeLocation<&mut T>`.
#[inline]
pub fn assign(&mut self, _value: MaybeLocation<T>) {
#[cfg(feature = "track_location")]
{
*self.value = _value.value;
}
}
}
impl<T: ?Sized> MaybeLocation<T> {
/// Converts from `&MaybeLocation<T>` to `MaybeLocation<&T>`.
#[inline]
pub const fn as_ref(&self) -> MaybeLocation<&T> {
MaybeLocation {
#[cfg(feature = "track_location")]
value: &self.value,
marker: PhantomData,
}
}
/// Converts from `&mut MaybeLocation<T>` to `MaybeLocation<&mut T>`.
#[inline]
pub const fn as_mut(&mut self) -> MaybeLocation<&mut T> {
MaybeLocation {
#[cfg(feature = "track_location")]
value: &mut self.value,
marker: PhantomData,
}
}
/// Converts from `&MaybeLocation<T>` to `MaybeLocation<&T::Target>`.
#[inline]
pub fn as_deref(&self) -> MaybeLocation<&T::Target>
where
T: Deref,
{
MaybeLocation {
#[cfg(feature = "track_location")]
value: &*self.value,
marker: PhantomData,
}
}
/// Converts from `&mut MaybeLocation<T>` to `MaybeLocation<&mut T::Target>`.
#[inline]
pub fn as_deref_mut(&mut self) -> MaybeLocation<&mut T::Target>
where
T: DerefMut,
{
MaybeLocation {
#[cfg(feature = "track_location")]
value: &mut *self.value,
marker: PhantomData,
}
}
}
impl MaybeLocation {
/// Returns the source location of the caller of this function. If that function's caller is
/// annotated then its call location will be returned, and so on up the stack to the first call
/// within a non-tracked function body.
#[inline]
#[track_caller]
pub const fn caller() -> Self {
// Note that this cannot use `new_with`, since `FnOnce` invocations cannot be annotated with `#[track_caller]`.
MaybeLocation {
#[cfg(feature = "track_location")]
value: Location::caller(),
marker: PhantomData,
}
}
}
| 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/change_detection/params.rs | crates/bevy_ecs/src/change_detection/params.rs | use crate::{
change_detection::{traits::*, ComponentTickCells, MaybeLocation, Tick},
ptr::PtrMut,
resource::Resource,
};
use bevy_ptr::{Ptr, UnsafeCellDeref};
use core::{
ops::{Deref, DerefMut},
panic::Location,
};
/// Used by immutable query parameters (such as [`Ref`] and [`Res`])
/// to store immutable access to the [`Tick`]s of a single component or resource.
#[derive(Clone)]
pub(crate) struct ComponentTicksRef<'w> {
pub(crate) added: &'w Tick,
pub(crate) changed: &'w Tick,
pub(crate) changed_by: MaybeLocation<&'w &'static Location<'static>>,
pub(crate) last_run: Tick,
pub(crate) this_run: Tick,
}
impl<'w> ComponentTicksRef<'w> {
/// # Safety
/// This should never alias the underlying ticks with a mutable one such as `ComponentTicksMut`.
#[inline]
pub(crate) unsafe fn from_tick_cells(
cells: ComponentTickCells<'w>,
last_run: Tick,
this_run: Tick,
) -> Self {
Self {
// SAFETY: Caller ensures there is no mutable access to the cell.
added: unsafe { cells.added.deref() },
// SAFETY: Caller ensures there is no mutable access to the cell.
changed: unsafe { cells.changed.deref() },
// SAFETY: Caller ensures there is no mutable access to the cell.
changed_by: unsafe { cells.changed_by.map(|changed_by| changed_by.deref()) },
last_run,
this_run,
}
}
}
/// Used by mutable query parameters (such as [`Mut`] and [`ResMut`])
/// to store mutable access to the [`Tick`]s of a single component or resource.
pub(crate) struct ComponentTicksMut<'w> {
pub(crate) added: &'w mut Tick,
pub(crate) changed: &'w mut Tick,
pub(crate) changed_by: MaybeLocation<&'w mut &'static Location<'static>>,
pub(crate) last_run: Tick,
pub(crate) this_run: Tick,
}
impl<'w> ComponentTicksMut<'w> {
/// # Safety
/// This should never alias the underlying ticks. All access must be unique.
#[inline]
pub(crate) unsafe fn from_tick_cells(
cells: ComponentTickCells<'w>,
last_run: Tick,
this_run: Tick,
) -> Self {
Self {
// SAFETY: Caller ensures there is no alias to the cell.
added: unsafe { cells.added.deref_mut() },
// SAFETY: Caller ensures there is no alias to the cell.
changed: unsafe { cells.changed.deref_mut() },
// SAFETY: Caller ensures there is no alias to the cell.
changed_by: unsafe { cells.changed_by.map(|changed_by| changed_by.deref_mut()) },
last_run,
this_run,
}
}
}
impl<'w> From<ComponentTicksMut<'w>> for ComponentTicksRef<'w> {
fn from(ticks: ComponentTicksMut<'w>) -> Self {
ComponentTicksRef {
added: ticks.added,
changed: ticks.changed,
changed_by: ticks.changed_by.map(|changed_by| &*changed_by),
last_run: ticks.last_run,
this_run: ticks.this_run,
}
}
}
/// Shared borrow of a [`Resource`].
///
/// See the [`Resource`] documentation for usage.
///
/// If you need a unique mutable borrow, use [`ResMut`] instead.
///
/// This [`SystemParam`](crate::system::SystemParam) fails validation if resource doesn't exist.
/// This will cause a panic, but can be configured to do nothing or warn once.
///
/// Use [`Option<Res<T>>`] instead if the resource might not always exist.
pub struct Res<'w, T: ?Sized + Resource> {
pub(crate) value: &'w T,
pub(crate) ticks: ComponentTicksRef<'w>,
}
impl<'w, T: Resource> Res<'w, T> {
/// Copies a reference to a resource.
///
/// Note that unless you actually need an instance of `Res<T>`, you should
/// prefer to just convert it to `&T` which can be freely copied.
#[expect(
clippy::should_implement_trait,
reason = "As this struct derefs to the inner resource, a `Clone` trait implementation would interfere with the common case of cloning the inner content. (A similar case of this happening can be found with `std::cell::Ref::clone()`.)"
)]
pub fn clone(this: &Self) -> Self {
Self {
value: this.value,
ticks: this.ticks.clone(),
}
}
/// Due to lifetime limitations of the `Deref` trait, this method can be used to obtain a
/// reference of the [`Resource`] with a lifetime bound to `'w` instead of the lifetime of the
/// struct itself.
pub fn into_inner(self) -> &'w T {
self.value
}
}
impl<'w, T: Resource> From<ResMut<'w, T>> for Res<'w, T> {
fn from(res: ResMut<'w, T>) -> Self {
Self {
value: res.value,
ticks: res.ticks.into(),
}
}
}
impl<'w, T: Resource> From<Res<'w, T>> for Ref<'w, T> {
/// Convert a `Res` into a `Ref`. This allows keeping the change-detection feature of `Ref`
/// while losing the specificity of `Res` for resources.
fn from(res: Res<'w, T>) -> Self {
Self {
value: res.value,
ticks: res.ticks,
}
}
}
impl<'w, 'a, T: Resource> IntoIterator for &'a Res<'w, T>
where
&'a T: IntoIterator,
{
type Item = <&'a T as IntoIterator>::Item;
type IntoIter = <&'a T as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.value.into_iter()
}
}
change_detection_impl!(Res<'w, T>, T, Resource);
impl_debug!(Res<'w, T>, Resource);
/// Unique mutable borrow of a [`Resource`].
///
/// See the [`Resource`] documentation for usage.
///
/// If you need a shared borrow, use [`Res`] instead.
///
/// This [`SystemParam`](crate::system::SystemParam) fails validation if resource doesn't exist.
/// This will cause a panic, but can be configured to do nothing or warn once.
///
/// Use [`Option<ResMut<T>>`] instead if the resource might not always exist.
pub struct ResMut<'w, T: ?Sized + Resource> {
pub(crate) value: &'w mut T,
pub(crate) ticks: ComponentTicksMut<'w>,
}
impl<'w, 'a, T: Resource> IntoIterator for &'a ResMut<'w, T>
where
&'a T: IntoIterator,
{
type Item = <&'a T as IntoIterator>::Item;
type IntoIter = <&'a T as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.value.into_iter()
}
}
impl<'w, 'a, T: Resource> IntoIterator for &'a mut ResMut<'w, T>
where
&'a mut T: IntoIterator,
{
type Item = <&'a mut T as IntoIterator>::Item;
type IntoIter = <&'a mut T as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.set_changed();
self.value.into_iter()
}
}
change_detection_impl!(ResMut<'w, T>, T, Resource);
change_detection_mut_impl!(ResMut<'w, T>, T, Resource);
impl_methods!(ResMut<'w, T>, T, Resource);
impl_debug!(ResMut<'w, T>, Resource);
impl<'w, T: Resource> From<ResMut<'w, T>> for Mut<'w, T> {
/// Convert this `ResMut` into a `Mut`. This allows keeping the change-detection feature of `Mut`
/// while losing the specificity of `ResMut` for resources.
fn from(other: ResMut<'w, T>) -> Mut<'w, T> {
Mut {
value: other.value,
ticks: other.ticks,
}
}
}
/// Shared borrow of a non-[`Send`] resource.
///
/// Only [`Send`] resources may be accessed with the [`Res`] [`SystemParam`](crate::system::SystemParam). In case that the
/// resource does not implement `Send`, this `SystemParam` wrapper can be used. This will instruct
/// the scheduler to instead run the system on the main thread so that it doesn't send the resource
/// over to another thread.
///
/// This [`SystemParam`](crate::system::SystemParam) fails validation if the non-send resource doesn't exist.
/// This will cause a panic, but can be configured to do nothing or warn once.
///
/// Use [`Option<NonSend<T>>`] instead if the resource might not always exist.
pub struct NonSend<'w, T: ?Sized + 'static> {
pub(crate) value: &'w T,
pub(crate) ticks: ComponentTicksRef<'w>,
}
change_detection_impl!(NonSend<'w, T>, T,);
impl_debug!(NonSend<'w, T>,);
impl<'w, T> From<NonSendMut<'w, T>> for NonSend<'w, T> {
fn from(other: NonSendMut<'w, T>) -> Self {
Self {
value: other.value,
ticks: other.ticks.into(),
}
}
}
/// Unique borrow of a non-[`Send`] resource.
///
/// Only [`Send`] resources may be accessed with the [`ResMut`] [`SystemParam`](crate::system::SystemParam). In case that the
/// resource does not implement `Send`, this `SystemParam` wrapper can be used. This will instruct
/// the scheduler to instead run the system on the main thread so that it doesn't send the resource
/// over to another thread.
///
/// This [`SystemParam`](crate::system::SystemParam) fails validation if non-send resource doesn't exist.
/// This will cause a panic, but can be configured to do nothing or warn once.
///
/// Use [`Option<NonSendMut<T>>`] instead if the resource might not always exist.
pub struct NonSendMut<'w, T: ?Sized + 'static> {
pub(crate) value: &'w mut T,
pub(crate) ticks: ComponentTicksMut<'w>,
}
change_detection_impl!(NonSendMut<'w, T>, T,);
change_detection_mut_impl!(NonSendMut<'w, T>, T,);
impl_methods!(NonSendMut<'w, T>, T,);
impl_debug!(NonSendMut<'w, T>,);
impl<'w, T: 'static> From<NonSendMut<'w, T>> for Mut<'w, T> {
/// Convert this `NonSendMut` into a `Mut`. This allows keeping the change-detection feature of `Mut`
/// while losing the specificity of `NonSendMut`.
fn from(other: NonSendMut<'w, T>) -> Mut<'w, T> {
Mut {
value: other.value,
ticks: other.ticks,
}
}
}
/// Shared borrow of an entity's component with access to change detection.
/// Similar to [`Mut`] but is immutable and so doesn't require unique access.
///
/// # Examples
///
/// These two systems produce the same output.
///
/// ```
/// # use bevy_ecs::change_detection::DetectChanges;
/// # use bevy_ecs::query::{Changed, With};
/// # use bevy_ecs::system::Query;
/// # use bevy_ecs::world::Ref;
/// # use bevy_ecs_macros::Component;
/// # #[derive(Component)]
/// # struct MyComponent;
///
/// fn how_many_changed_1(query: Query<(), Changed<MyComponent>>) {
/// println!("{} changed", query.iter().count());
/// }
///
/// fn how_many_changed_2(query: Query<Ref<MyComponent>>) {
/// println!("{} changed", query.iter().filter(|c| c.is_changed()).count());
/// }
/// ```
pub struct Ref<'w, T: ?Sized> {
pub(crate) value: &'w T,
pub(crate) ticks: ComponentTicksRef<'w>,
}
impl<'w, T: ?Sized> Ref<'w, T> {
/// Returns the reference wrapped by this type. The reference is allowed to outlive `self`, which makes this method more flexible than simply borrowing `self`.
pub fn into_inner(self) -> &'w T {
self.value
}
/// Map `Ref` to a different type using `f`.
///
/// This doesn't do anything else than call `f` on the wrapped value.
/// This is equivalent to [`Mut::map_unchanged`].
pub fn map<U: ?Sized>(self, f: impl FnOnce(&T) -> &U) -> Ref<'w, U> {
Ref {
value: f(self.value),
ticks: self.ticks,
}
}
/// Create a new `Ref` using provided values.
///
/// This is an advanced feature, `Ref`s are designed to be _created_ by
/// engine-internal code and _consumed_ by end-user code.
///
/// - `value` - The value wrapped by `Ref`.
/// - `added` - A [`Tick`] that stores the tick when the wrapped value was created.
/// - `changed` - A [`Tick`] that stores the last time the wrapped value was changed.
/// - `last_run` - A [`Tick`], occurring before `this_run`, which is used
/// as a reference to determine whether the wrapped value is newly added or changed.
/// - `this_run` - A [`Tick`] corresponding to the current point in time -- "now".
pub fn new(
value: &'w T,
added: &'w Tick,
changed: &'w Tick,
last_run: Tick,
this_run: Tick,
caller: MaybeLocation<&'w &'static Location<'static>>,
) -> Ref<'w, T> {
Ref {
value,
ticks: ComponentTicksRef {
added,
changed,
changed_by: caller,
last_run,
this_run,
},
}
}
/// Overwrite the `last_run` and `this_run` tick that are used for change detection.
///
/// This is an advanced feature. `Ref`s are usually _created_ by engine-internal code and
/// _consumed_ by end-user code.
pub fn set_ticks(&mut self, last_run: Tick, this_run: Tick) {
self.ticks.last_run = last_run;
self.ticks.this_run = this_run;
}
}
impl<'w, 'a, T> IntoIterator for &'a Ref<'w, T>
where
&'a T: IntoIterator,
{
type Item = <&'a T as IntoIterator>::Item;
type IntoIter = <&'a T as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.value.into_iter()
}
}
change_detection_impl!(Ref<'w, T>, T,);
impl_debug!(Ref<'w, T>,);
/// Unique mutable borrow of an entity's component or of a resource.
///
/// This can be used in queries to access change detection from immutable query methods, as opposed
/// to `&mut T` which only provides access to change detection from mutable query methods.
///
/// ```rust
/// # use bevy_ecs::prelude::*;
/// # use bevy_ecs::query::QueryData;
/// #
/// #[derive(Component, Clone, Debug)]
/// struct Name(String);
///
/// #[derive(Component, Clone, Copy, Debug)]
/// struct Health(f32);
///
/// fn my_system(mut query: Query<(Mut<Name>, &mut Health)>) {
/// // Mutable access provides change detection information for both parameters:
/// // - `name` has type `Mut<Name>`
/// // - `health` has type `Mut<Health>`
/// for (name, health) in query.iter_mut() {
/// println!("Name: {:?} (last changed {:?})", name, name.last_changed());
/// println!("Health: {:?} (last changed: {:?})", health, health.last_changed());
/// # println!("{}{}", name.0, health.0); // Silence dead_code warning
/// }
///
/// // Immutable access only provides change detection for `Name`:
/// // - `name` has type `Ref<Name>`
/// // - `health` has type `&Health`
/// for (name, health) in query.iter() {
/// println!("Name: {:?} (last changed {:?})", name, name.last_changed());
/// println!("Health: {:?}", health);
/// }
/// }
///
/// # bevy_ecs::system::assert_is_system(my_system);
/// ```
pub struct Mut<'w, T: ?Sized> {
pub(crate) value: &'w mut T,
pub(crate) ticks: ComponentTicksMut<'w>,
}
impl<'w, T: ?Sized> Mut<'w, T> {
/// Creates a new change-detection enabled smart pointer.
/// In almost all cases you do not need to call this method manually,
/// as instances of `Mut` will be created by engine-internal code.
///
/// Many use-cases of this method would be better served by [`Mut::map_unchanged`]
/// or [`Mut::reborrow`].
///
/// - `value` - The value wrapped by this smart pointer.
/// - `added` - A [`Tick`] that stores the tick when the wrapped value was created.
/// - `last_changed` - A [`Tick`] that stores the last time the wrapped value was changed.
/// This will be updated to the value of `change_tick` if the returned smart pointer
/// is modified.
/// - `last_run` - A [`Tick`], occurring before `this_run`, which is used
/// as a reference to determine whether the wrapped value is newly added or changed.
/// - `this_run` - A [`Tick`] corresponding to the current point in time -- "now".
pub fn new(
value: &'w mut T,
added: &'w mut Tick,
last_changed: &'w mut Tick,
last_run: Tick,
this_run: Tick,
caller: MaybeLocation<&'w mut &'static Location<'static>>,
) -> Self {
Self {
value,
ticks: ComponentTicksMut {
added,
changed: last_changed,
changed_by: caller,
last_run,
this_run,
},
}
}
/// Overwrite the `last_run` and `this_run` tick that are used for change detection.
///
/// This is an advanced feature. `Mut`s are usually _created_ by engine-internal code and
/// _consumed_ by end-user code.
pub fn set_ticks(&mut self, last_run: Tick, this_run: Tick) {
self.ticks.last_run = last_run;
self.ticks.this_run = this_run;
}
}
impl<'w, T: ?Sized> From<Mut<'w, T>> for Ref<'w, T> {
fn from(mut_ref: Mut<'w, T>) -> Self {
Self {
value: mut_ref.value,
ticks: mut_ref.ticks.into(),
}
}
}
impl<'w, 'a, T> IntoIterator for &'a Mut<'w, T>
where
&'a T: IntoIterator,
{
type Item = <&'a T as IntoIterator>::Item;
type IntoIter = <&'a T as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.value.into_iter()
}
}
impl<'w, 'a, T> IntoIterator for &'a mut Mut<'w, T>
where
&'a mut T: IntoIterator,
{
type Item = <&'a mut T as IntoIterator>::Item;
type IntoIter = <&'a mut T as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.set_changed();
self.value.into_iter()
}
}
change_detection_impl!(Mut<'w, T>, T,);
change_detection_mut_impl!(Mut<'w, T>, T,);
impl_methods!(Mut<'w, T>, T,);
impl_debug!(Mut<'w, T>,);
/// Unique mutable borrow of resources or an entity's component.
///
/// Similar to [`Mut`], but not generic over the component type, instead
/// exposing the raw pointer as a `*mut ()`.
///
/// Usually you don't need to use this and can instead use the APIs returning a
/// [`Mut`], but in situations where the types are not known at compile time
/// or are defined outside of rust this can be used.
pub struct MutUntyped<'w> {
pub(crate) value: PtrMut<'w>,
pub(crate) ticks: ComponentTicksMut<'w>,
}
impl<'w> MutUntyped<'w> {
/// Returns the pointer to the value, marking it as changed.
///
/// In order to avoid marking the value as changed, you need to call [`bypass_change_detection`](DetectChangesMut::bypass_change_detection).
#[inline]
pub fn into_inner(mut self) -> PtrMut<'w> {
self.set_changed();
self.value
}
/// Returns a [`MutUntyped`] with a smaller lifetime.
/// This is useful if you have `&mut MutUntyped`, but you need a `MutUntyped`.
#[inline]
pub fn reborrow(&mut self) -> MutUntyped<'_> {
MutUntyped {
value: self.value.reborrow(),
ticks: ComponentTicksMut {
added: self.ticks.added,
changed: self.ticks.changed,
changed_by: self.ticks.changed_by.as_deref_mut(),
last_run: self.ticks.last_run,
this_run: self.ticks.this_run,
},
}
}
/// Returns `true` if this value was changed or mutably dereferenced
/// either since a specific change tick.
pub fn has_changed_since(&self, tick: Tick) -> bool {
self.ticks.changed.is_newer_than(tick, self.ticks.this_run)
}
/// Returns a pointer to the value without taking ownership of this smart pointer, marking it as changed.
///
/// In order to avoid marking the value as changed, you need to call [`bypass_change_detection`](DetectChangesMut::bypass_change_detection).
#[inline]
pub fn as_mut(&mut self) -> PtrMut<'_> {
self.set_changed();
self.value.reborrow()
}
/// Returns an immutable pointer to the value without taking ownership.
#[inline]
pub fn as_ref(&self) -> Ptr<'_> {
self.value.as_ref()
}
/// Turn this [`MutUntyped`] into a [`Mut`] by mapping the inner [`PtrMut`] to another value,
/// without flagging a change.
/// This function is the untyped equivalent of [`Mut::map_unchanged`].
///
/// You should never modify the argument passed to the closure β if you want to modify the data without flagging a change, consider using [`bypass_change_detection`](DetectChangesMut::bypass_change_detection) to make your intent explicit.
///
/// If you know the type of the value you can do
/// ```no_run
/// # use bevy_ecs::change_detection::{Mut, MutUntyped};
/// # let mut_untyped: MutUntyped = unimplemented!();
/// // SAFETY: ptr is of type `u8`
/// mut_untyped.map_unchanged(|ptr| unsafe { ptr.deref_mut::<u8>() });
/// ```
/// If you have a [`ReflectFromPtr`](bevy_reflect::ReflectFromPtr) that you know belongs to this [`MutUntyped`],
/// you can do
/// ```no_run
/// # use bevy_ecs::change_detection::{Mut, MutUntyped};
/// # let mut_untyped: MutUntyped = unimplemented!();
/// # let reflect_from_ptr: bevy_reflect::ReflectFromPtr = unimplemented!();
/// // SAFETY: from the context it is known that `ReflectFromPtr` was made for the type of the `MutUntyped`
/// mut_untyped.map_unchanged(|ptr| unsafe { reflect_from_ptr.as_reflect_mut(ptr) });
/// ```
pub fn map_unchanged<T: ?Sized>(self, f: impl FnOnce(PtrMut<'w>) -> &'w mut T) -> Mut<'w, T> {
Mut {
value: f(self.value),
ticks: self.ticks,
}
}
/// Transforms this [`MutUntyped`] into a [`Mut<T>`] with the same lifetime.
///
/// # Safety
/// - `T` must be the erased pointee type for this [`MutUntyped`].
pub unsafe fn with_type<T>(self) -> Mut<'w, T> {
Mut {
// SAFETY: `value` is `Aligned` and caller ensures the pointee type is `T`.
value: unsafe { self.value.deref_mut() },
ticks: self.ticks,
}
}
}
impl<'w> DetectChanges for MutUntyped<'w> {
#[inline]
fn is_added(&self) -> bool {
self.ticks
.added
.is_newer_than(self.ticks.last_run, self.ticks.this_run)
}
#[inline]
fn is_changed(&self) -> bool {
self.ticks
.changed
.is_newer_than(self.ticks.last_run, self.ticks.this_run)
}
#[inline]
fn last_changed(&self) -> Tick {
*self.ticks.changed
}
#[inline]
fn changed_by(&self) -> MaybeLocation {
self.ticks.changed_by.copied()
}
#[inline]
fn added(&self) -> Tick {
*self.ticks.added
}
}
impl<'w> DetectChangesMut for MutUntyped<'w> {
type Inner = PtrMut<'w>;
#[inline]
#[track_caller]
fn set_changed(&mut self) {
*self.ticks.changed = self.ticks.this_run;
self.ticks.changed_by.assign(MaybeLocation::caller());
}
#[inline]
#[track_caller]
fn set_added(&mut self) {
*self.ticks.changed = self.ticks.this_run;
*self.ticks.added = self.ticks.this_run;
self.ticks.changed_by.assign(MaybeLocation::caller());
}
#[inline]
#[track_caller]
fn set_last_changed(&mut self, last_changed: Tick) {
*self.ticks.changed = last_changed;
self.ticks.changed_by.assign(MaybeLocation::caller());
}
#[inline]
#[track_caller]
fn set_last_added(&mut self, last_added: Tick) {
*self.ticks.added = last_added;
*self.ticks.changed = last_added;
self.ticks.changed_by.assign(MaybeLocation::caller());
}
#[inline]
#[track_caller]
fn bypass_change_detection(&mut self) -> &mut Self::Inner {
&mut self.value
}
}
impl core::fmt::Debug for MutUntyped<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_tuple("MutUntyped")
.field(&self.value.as_ptr())
.finish()
}
}
impl<'w, T> From<Mut<'w, T>> for MutUntyped<'w> {
fn from(value: Mut<'w, T>) -> Self {
MutUntyped {
value: value.value.into(),
ticks: value.ticks,
}
}
}
| 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/change_detection/mod.rs | crates/bevy_ecs/src/change_detection/mod.rs | //! Types that detect when their internal data mutate.
mod maybe_location;
mod params;
mod tick;
mod traits;
pub use maybe_location::MaybeLocation;
pub use params::*;
pub use tick::*;
pub use traits::{DetectChanges, DetectChangesMut};
/// The (arbitrarily chosen) minimum number of world tick increments between `check_tick` scans.
///
/// Change ticks can only be scanned when systems aren't running. Thus, if the threshold is `N`,
/// the maximum is `2 * N - 1` (i.e. the world ticks `N - 1` times, then `N` times).
///
/// If no change is older than `u32::MAX - (2 * N - 1)` following a scan, none of their ages can
/// overflow and cause false positives.
// (518,400,000 = 1000 ticks per frame * 144 frames per second * 3600 seconds per hour)
pub const CHECK_TICK_THRESHOLD: u32 = 518_400_000;
/// The maximum change tick difference that won't overflow before the next `check_tick` scan.
///
/// Changes stop being detected once they become this old.
pub const MAX_CHANGE_AGE: u32 = u32::MAX - (2 * CHECK_TICK_THRESHOLD - 1);
#[cfg(test)]
mod tests {
use bevy_ecs_macros::Resource;
use bevy_ptr::PtrMut;
use bevy_reflect::{FromType, ReflectFromPtr};
use core::ops::{Deref, DerefMut};
use crate::{
change_detection::{
ComponentTicks, ComponentTicksMut, MaybeLocation, Mut, NonSendMut, Ref, ResMut, Tick,
CHECK_TICK_THRESHOLD, MAX_CHANGE_AGE,
},
component::Component,
system::{IntoSystem, Single, System},
world::World,
};
use super::{DetectChanges, DetectChangesMut, MutUntyped};
#[derive(Component, PartialEq)]
struct C;
#[derive(Resource)]
struct R;
#[derive(Resource, PartialEq)]
struct R2(u8);
impl Deref for R2 {
type Target = u8;
fn deref(&self) -> &u8 {
&self.0
}
}
impl DerefMut for R2 {
fn deref_mut(&mut self) -> &mut u8 {
&mut self.0
}
}
#[test]
fn change_expiration() {
fn change_detected(query: Option<Single<Ref<C>>>) -> bool {
query.unwrap().is_changed()
}
fn change_expired(query: Option<Single<Ref<C>>>) -> bool {
query.unwrap().is_changed()
}
let mut world = World::new();
// component added: 1, changed: 1
world.spawn(C);
let mut change_detected_system = IntoSystem::into_system(change_detected);
let mut change_expired_system = IntoSystem::into_system(change_expired);
change_detected_system.initialize(&mut world);
change_expired_system.initialize(&mut world);
// world: 1, system last ran: 0, component changed: 1
// The spawn will be detected since it happened after the system "last ran".
assert!(change_detected_system.run((), &mut world).unwrap());
// world: 1 + MAX_CHANGE_AGE
let change_tick = world.change_tick.get_mut();
*change_tick = change_tick.wrapping_add(MAX_CHANGE_AGE);
// Both the system and component appeared `MAX_CHANGE_AGE` ticks ago.
// Since we clamp things to `MAX_CHANGE_AGE` for determinism,
// `ComponentTicks::is_changed` will now see `MAX_CHANGE_AGE > MAX_CHANGE_AGE`
// and return `false`.
assert!(!change_expired_system.run((), &mut world).unwrap());
}
#[test]
fn change_tick_wraparound() {
let mut world = World::new();
world.last_change_tick = Tick::new(u32::MAX);
*world.change_tick.get_mut() = 0;
// component added: 0, changed: 0
world.spawn(C);
world.increment_change_tick();
// Since the world is always ahead, as long as changes can't get older than `u32::MAX` (which we ensure),
// the wrapping difference will always be positive, so wraparound doesn't matter.
let mut query = world.query::<Ref<C>>();
assert!(query.single(&world).unwrap().is_changed());
}
#[test]
fn change_tick_scan() {
let mut world = World::new();
// component added: 1, changed: 1
world.spawn(C);
// a bunch of stuff happens, the component is now older than `MAX_CHANGE_AGE`
*world.change_tick.get_mut() += MAX_CHANGE_AGE + CHECK_TICK_THRESHOLD;
let change_tick = world.change_tick();
let mut query = world.query::<Ref<C>>();
for tracker in query.iter(&world) {
let ticks_since_insert = change_tick.relative_to(*tracker.ticks.added).get();
let ticks_since_change = change_tick.relative_to(*tracker.ticks.changed).get();
assert!(ticks_since_insert > MAX_CHANGE_AGE);
assert!(ticks_since_change > MAX_CHANGE_AGE);
}
// scan change ticks and clamp those at risk of overflow
world.check_change_ticks();
for tracker in query.iter(&world) {
let ticks_since_insert = change_tick.relative_to(*tracker.ticks.added).get();
let ticks_since_change = change_tick.relative_to(*tracker.ticks.changed).get();
assert_eq!(ticks_since_insert, MAX_CHANGE_AGE);
assert_eq!(ticks_since_change, MAX_CHANGE_AGE);
}
}
#[test]
fn mut_from_res_mut() {
let mut component_ticks = ComponentTicks {
added: Tick::new(1),
changed: Tick::new(2),
};
let mut caller = MaybeLocation::caller();
let ticks = ComponentTicksMut {
added: &mut component_ticks.added,
changed: &mut component_ticks.changed,
changed_by: caller.as_mut(),
last_run: Tick::new(3),
this_run: Tick::new(4),
};
let mut res = R {};
let res_mut = ResMut {
value: &mut res,
ticks,
};
let into_mut: Mut<R> = res_mut.into();
assert_eq!(1, into_mut.ticks.added.get());
assert_eq!(2, into_mut.ticks.changed.get());
assert_eq!(3, into_mut.ticks.last_run.get());
assert_eq!(4, into_mut.ticks.this_run.get());
}
#[test]
fn mut_new() {
let mut component_ticks = ComponentTicks {
added: Tick::new(1),
changed: Tick::new(3),
};
let mut res = R {};
let mut caller = MaybeLocation::caller();
let val = Mut::new(
&mut res,
&mut component_ticks.added,
&mut component_ticks.changed,
Tick::new(2), // last_run
Tick::new(4), // this_run
caller.as_mut(),
);
assert!(!val.is_added());
assert!(val.is_changed());
}
#[test]
fn mut_from_non_send_mut() {
let mut component_ticks = ComponentTicks {
added: Tick::new(1),
changed: Tick::new(2),
};
let mut caller = MaybeLocation::caller();
let ticks = ComponentTicksMut {
added: &mut component_ticks.added,
changed: &mut component_ticks.changed,
changed_by: caller.as_mut(),
last_run: Tick::new(3),
this_run: Tick::new(4),
};
let mut res = R {};
let non_send_mut = NonSendMut {
value: &mut res,
ticks,
};
let into_mut: Mut<R> = non_send_mut.into();
assert_eq!(1, into_mut.ticks.added.get());
assert_eq!(2, into_mut.ticks.changed.get());
assert_eq!(3, into_mut.ticks.last_run.get());
assert_eq!(4, into_mut.ticks.this_run.get());
}
#[test]
fn map_mut() {
use super::*;
struct Outer(i64);
let last_run = Tick::new(2);
let this_run = Tick::new(3);
let mut component_ticks = ComponentTicks {
added: Tick::new(1),
changed: Tick::new(2),
};
let mut caller = MaybeLocation::caller();
let ticks = ComponentTicksMut {
added: &mut component_ticks.added,
changed: &mut component_ticks.changed,
changed_by: caller.as_mut(),
last_run,
this_run,
};
let mut outer = Outer(0);
let ptr = Mut {
value: &mut outer,
ticks,
};
assert!(!ptr.is_changed());
// Perform a mapping operation.
let mut inner = ptr.map_unchanged(|x| &mut x.0);
assert!(!inner.is_changed());
// Mutate the inner value.
*inner = 64;
assert!(inner.is_changed());
// Modifying one field of a component should flag a change for the entire component.
assert!(component_ticks.is_changed(last_run, this_run));
}
#[test]
fn set_if_neq() {
let mut world = World::new();
world.insert_resource(R2(0));
// Resources are Changed when first added
world.increment_change_tick();
// This is required to update world::last_change_tick
world.clear_trackers();
let mut r = world.resource_mut::<R2>();
assert!(!r.is_changed(), "Resource must begin unchanged.");
r.set_if_neq(R2(0));
assert!(
!r.is_changed(),
"Resource must not be changed after setting to the same value."
);
r.set_if_neq(R2(3));
assert!(
r.is_changed(),
"Resource must be changed after setting to a different value."
);
}
#[test]
fn as_deref_mut() {
let mut world = World::new();
world.insert_resource(R2(0));
// Resources are Changed when first added
world.increment_change_tick();
// This is required to update world::last_change_tick
world.clear_trackers();
let mut r = world.resource_mut::<R2>();
assert!(!r.is_changed(), "Resource must begin unchanged.");
let mut r = r.as_deref_mut();
assert!(
!r.is_changed(),
"Dereferencing should not mark the item as changed yet"
);
r.set_if_neq(3);
assert!(
r.is_changed(),
"Resource must be changed after setting to a different value."
);
}
#[test]
fn mut_untyped_to_reflect() {
let last_run = Tick::new(2);
let this_run = Tick::new(3);
let mut component_ticks = ComponentTicks {
added: Tick::new(1),
changed: Tick::new(2),
};
let mut caller = MaybeLocation::caller();
let ticks = ComponentTicksMut {
added: &mut component_ticks.added,
changed: &mut component_ticks.changed,
changed_by: caller.as_mut(),
last_run,
this_run,
};
let mut value: i32 = 5;
let value = MutUntyped {
value: PtrMut::from(&mut value),
ticks,
};
let reflect_from_ptr = <ReflectFromPtr as FromType<i32>>::from_type();
let mut new = value.map_unchanged(|ptr| {
// SAFETY: The underlying type of `ptr` matches `reflect_from_ptr`.
unsafe { reflect_from_ptr.as_reflect_mut(ptr) }
});
assert!(!new.is_changed());
new.reflect_mut();
assert!(new.is_changed());
}
#[test]
fn mut_untyped_from_mut() {
let mut component_ticks = ComponentTicks {
added: Tick::new(1),
changed: Tick::new(2),
};
let mut caller = MaybeLocation::caller();
let ticks = ComponentTicksMut {
added: &mut component_ticks.added,
changed: &mut component_ticks.changed,
changed_by: caller.as_mut(),
last_run: Tick::new(3),
this_run: Tick::new(4),
};
let mut c = C {};
let mut_typed = Mut {
value: &mut c,
ticks,
};
let into_mut: MutUntyped = mut_typed.into();
assert_eq!(1, into_mut.ticks.added.get());
assert_eq!(2, into_mut.ticks.changed.get());
assert_eq!(3, into_mut.ticks.last_run.get());
assert_eq!(4, into_mut.ticks.this_run.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/change_detection/traits.rs | crates/bevy_ecs/src/change_detection/traits.rs | use crate::{change_detection::MaybeLocation, change_detection::Tick};
use alloc::borrow::ToOwned;
use core::mem;
/// Types that can read change detection information.
/// This change detection is controlled by [`DetectChangesMut`] types such as [`ResMut`].
///
/// ## Example
/// Using types that implement [`DetectChanges`], such as [`Res`], provide
/// a way to query if a value has been mutated in another system.
///
/// ```
/// use bevy_ecs::prelude::*;
///
/// #[derive(Resource)]
/// struct MyResource(u32);
///
/// fn my_system(mut resource: Res<MyResource>) {
/// if resource.is_changed() {
/// println!("My component was mutated!");
/// }
/// }
/// ```
///
/// [`Res`]: crate::change_detection::params::Res
/// [`ResMut`]: crate::change_detection::params::ResMut
pub trait DetectChanges {
/// Returns `true` if this value was added after the system last ran.
fn is_added(&self) -> bool;
/// Returns `true` if this value was added or mutably dereferenced
/// either since the last time the system ran or, if the system never ran,
/// since the beginning of the program.
///
/// To check if the value was mutably dereferenced only,
/// use `this.is_changed() && !this.is_added()`.
fn is_changed(&self) -> bool;
/// Returns the change tick recording the time this data was most recently changed.
///
/// Note that components and resources are also marked as changed upon insertion.
///
/// For comparison, the previous change tick of a system can be read using the
/// [`SystemChangeTick`](crate::system::SystemChangeTick)
/// [`SystemParam`](crate::system::SystemParam).
fn last_changed(&self) -> Tick;
/// Returns the change tick recording the time this data was added.
fn added(&self) -> Tick;
/// The location that last caused this to change.
fn changed_by(&self) -> MaybeLocation;
}
/// Types that implement reliable change detection.
///
/// ## Example
/// Using types that implement [`DetectChangesMut`], such as [`ResMut`], provide
/// a way to query if a value has been mutated in another system.
/// Normally change detection is triggered by either [`DerefMut`] or [`AsMut`], however
/// it can be manually triggered via [`set_changed`](DetectChangesMut::set_changed).
///
/// To ensure that changes are only triggered when the value actually differs,
/// check if the value would change before assignment, such as by checking that `new != old`.
/// You must be *sure* that you are not mutably dereferencing in this process.
///
/// [`set_if_neq`](DetectChangesMut::set_if_neq) is a helper
/// method for this common functionality.
///
/// ```
/// use bevy_ecs::prelude::*;
///
/// #[derive(Resource)]
/// struct MyResource(u32);
///
/// fn my_system(mut resource: ResMut<MyResource>) {
/// if resource.is_changed() {
/// println!("My resource was mutated!");
/// }
///
/// resource.0 = 42; // triggers change detection via [`DerefMut`]
/// }
/// ```
///
/// [`ResMut`]: crate::change_detection::params::ResMut
/// [`DerefMut`]: core::ops::DerefMut
pub trait DetectChangesMut: DetectChanges {
/// The type contained within this smart pointer
///
/// For example, for `ResMut<T>` this would be `T`.
type Inner: ?Sized;
/// Flags this value as having been changed.
///
/// Mutably accessing this smart pointer will automatically flag this value as having been changed.
/// However, mutation through interior mutability requires manual reporting.
///
/// **Note**: This operation cannot be undone.
fn set_changed(&mut self);
/// Flags this value as having been added.
///
/// It is not normally necessary to call this method.
/// The 'added' tick is set when the value is first added,
/// and is not normally changed afterwards.
///
/// **Note**: This operation cannot be undone.
fn set_added(&mut self);
/// Manually sets the change tick recording the time when this data was last mutated.
///
/// # Warning
/// This is a complex and error-prone operation, primarily intended for use with rollback networking strategies.
/// If you merely want to flag this data as changed, use [`set_changed`](DetectChangesMut::set_changed) instead.
/// If you want to avoid triggering change detection, use [`bypass_change_detection`](DetectChangesMut::bypass_change_detection) instead.
fn set_last_changed(&mut self, last_changed: Tick);
/// Manually sets the added tick recording the time when this data was last added.
///
/// # Warning
/// The caveats of [`set_last_changed`](DetectChangesMut::set_last_changed) apply. This modifies both the added and changed ticks together.
fn set_last_added(&mut self, last_added: Tick);
/// Manually bypasses change detection, allowing you to mutate the underlying value without updating the change tick.
///
/// # Warning
/// This is a risky 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 bypass_change_detection(&mut self) -> &mut Self::Inner;
/// Overwrites this smart pointer with the given value, if and only if `*self != value`.
/// Returns `true` if the value was overwritten, and returns `false` if it was not.
///
/// This is useful to ensure change detection is only triggered when the underlying value
/// changes, instead of every time it is mutably accessed.
///
/// If you're dealing with non-trivial structs which have multiple fields of non-trivial size,
/// then consider applying a `map_unchanged` beforehand to allow changing only the relevant
/// field and prevent unnecessary copying and cloning.
/// See the docs of [`Mut::map_unchanged`], [`MutUntyped::map_unchanged`],
/// [`ResMut::map_unchanged`] or [`NonSendMut::map_unchanged`] for an example
///
/// If you need the previous value, use [`replace_if_neq`](DetectChangesMut::replace_if_neq).
///
/// # Examples
///
/// ```
/// # use bevy_ecs::{prelude::*, schedule::common_conditions::resource_changed};
/// #[derive(Resource, PartialEq, Eq)]
/// pub struct Score(u32);
///
/// fn reset_score(mut score: ResMut<Score>) {
/// // Set the score to zero, unless it is already zero.
/// score.set_if_neq(Score(0));
/// }
/// # let mut world = World::new();
/// # world.insert_resource(Score(1));
/// # let mut score_changed = IntoSystem::into_system(resource_changed::<Score>);
/// # score_changed.initialize(&mut world);
/// # score_changed.run((), &mut world);
/// #
/// # let mut schedule = Schedule::default();
/// # schedule.add_systems(reset_score);
/// #
/// # // first time `reset_score` runs, the score is changed.
/// # schedule.run(&mut world);
/// # assert!(score_changed.run((), &mut world).unwrap());
/// # // second time `reset_score` runs, the score is not changed.
/// # schedule.run(&mut world);
/// # assert!(!score_changed.run((), &mut world).unwrap());
/// ```
///
/// [`Mut::map_unchanged`]: crate::change_detection::params::Mut::map_unchanged
/// [`MutUntyped::map_unchanged`]: crate::change_detection::params::MutUntyped::map_unchanged
/// [`ResMut::map_unchanged`]: crate::change_detection::params::ResMut::map_unchanged
/// [`NonSendMut::map_unchanged`]: crate::change_detection::params::NonSendMut::map_unchanged
#[inline]
#[track_caller]
fn set_if_neq(&mut self, value: Self::Inner) -> bool
where
Self::Inner: Sized + PartialEq,
{
let old = self.bypass_change_detection();
if *old != value {
*old = value;
self.set_changed();
true
} else {
false
}
}
/// Overwrites this smart pointer with the given value, if and only if `*self != value`,
/// returning the previous value if this occurs.
///
/// This is useful to ensure change detection is only triggered when the underlying value
/// changes, instead of every time it is mutably accessed.
///
/// If you're dealing with non-trivial structs which have multiple fields of non-trivial size,
/// then consider applying a `map_unchanged` beforehand to allow
/// changing only the relevant field and prevent unnecessary copying and cloning.
/// See the docs of [`Mut::map_unchanged`], [`MutUntyped::map_unchanged`],
/// [`ResMut::map_unchanged`] or [`NonSendMut::map_unchanged`] for an example
///
/// If you don't need the previous value, use [`set_if_neq`](DetectChangesMut::set_if_neq).
///
/// # Examples
///
/// ```
/// # use bevy_ecs::{prelude::*, schedule::common_conditions::{resource_changed, on_message}};
/// #[derive(Resource, PartialEq, Eq)]
/// pub struct Score(u32);
///
/// #[derive(Message, PartialEq, Eq)]
/// pub struct ScoreChanged {
/// current: u32,
/// previous: u32,
/// }
///
/// fn reset_score(mut score: ResMut<Score>, mut score_changed: MessageWriter<ScoreChanged>) {
/// // Set the score to zero, unless it is already zero.
/// let new_score = 0;
/// if let Some(Score(previous_score)) = score.replace_if_neq(Score(new_score)) {
/// // If `score` change, emit a `ScoreChanged` event.
/// score_changed.write(ScoreChanged {
/// current: new_score,
/// previous: previous_score,
/// });
/// }
/// }
/// # let mut world = World::new();
/// # world.insert_resource(Messages::<ScoreChanged>::default());
/// # world.insert_resource(Score(1));
/// # let mut score_changed = IntoSystem::into_system(resource_changed::<Score>);
/// # score_changed.initialize(&mut world);
/// # score_changed.run((), &mut world);
/// #
/// # let mut score_changed_event = IntoSystem::into_system(on_message::<ScoreChanged>);
/// # score_changed_event.initialize(&mut world);
/// # score_changed_event.run((), &mut world);
/// #
/// # let mut schedule = Schedule::default();
/// # schedule.add_systems(reset_score);
/// #
/// # // first time `reset_score` runs, the score is changed.
/// # schedule.run(&mut world);
/// # assert!(score_changed.run((), &mut world).unwrap());
/// # assert!(score_changed_event.run((), &mut world).unwrap());
/// # // second time `reset_score` runs, the score is not changed.
/// # schedule.run(&mut world);
/// # assert!(!score_changed.run((), &mut world).unwrap());
/// # assert!(!score_changed_event.run((), &mut world).unwrap());
/// ```
///
/// [`Mut::map_unchanged`]: crate::change_detection::params::Mut::map_unchanged
/// [`MutUntyped::map_unchanged`]: crate::change_detection::params::MutUntyped::map_unchanged
/// [`ResMut::map_unchanged`]: crate::change_detection::params::ResMut::map_unchanged
/// [`NonSendMut::map_unchanged`]: crate::change_detection::params::NonSendMut::map_unchanged
#[inline]
#[must_use = "If you don't need to handle the previous value, use `set_if_neq` instead."]
fn replace_if_neq(&mut self, value: Self::Inner) -> Option<Self::Inner>
where
Self::Inner: Sized + PartialEq,
{
let old = self.bypass_change_detection();
if *old != value {
let previous = mem::replace(old, value);
self.set_changed();
Some(previous)
} else {
None
}
}
/// Overwrites this smart pointer with a clone of the given value, if and only if `*self != value`.
/// Returns `true` if the value was overwritten, and returns `false` if it was not.
///
/// This method is useful when the caller only has a borrowed form of `Inner`,
/// e.g. when writing a `&str` into a `Mut<String>`.
///
/// # Examples
/// ```
/// # extern crate alloc;
/// # use alloc::borrow::ToOwned;
/// # use bevy_ecs::{prelude::*, schedule::common_conditions::resource_changed};
/// #[derive(Resource)]
/// pub struct Message(String);
///
/// fn update_message(mut message: ResMut<Message>) {
/// // Set the score to zero, unless it is already zero.
/// ResMut::map_unchanged(message, |Message(msg)| msg).clone_from_if_neq("another string");
/// }
/// # let mut world = World::new();
/// # world.insert_resource(Message("initial string".into()));
/// # let mut message_changed = IntoSystem::into_system(resource_changed::<Message>);
/// # message_changed.initialize(&mut world);
/// # message_changed.run((), &mut world);
/// #
/// # let mut schedule = Schedule::default();
/// # schedule.add_systems(update_message);
/// #
/// # // first time `reset_score` runs, the score is changed.
/// # schedule.run(&mut world);
/// # assert!(message_changed.run((), &mut world).unwrap());
/// # // second time `reset_score` runs, the score is not changed.
/// # schedule.run(&mut world);
/// # assert!(!message_changed.run((), &mut world).unwrap());
/// ```
fn clone_from_if_neq<T>(&mut self, value: &T) -> bool
where
T: ToOwned<Owned = Self::Inner> + ?Sized,
Self::Inner: PartialEq<T>,
{
let old = self.bypass_change_detection();
if old != value {
value.clone_into(old);
self.set_changed();
true
} else {
false
}
}
}
macro_rules! change_detection_impl {
($name:ident < $( $generics:tt ),+ >, $target:ty, $($traits:ident)?) => {
impl<$($generics),* : ?Sized $(+ $traits)?> DetectChanges for $name<$($generics),*> {
#[inline]
fn is_added(&self) -> bool {
self.ticks
.added
.is_newer_than(self.ticks.last_run, self.ticks.this_run)
}
#[inline]
fn is_changed(&self) -> bool {
self.ticks
.changed
.is_newer_than(self.ticks.last_run, self.ticks.this_run)
}
#[inline]
fn last_changed(&self) -> Tick {
*self.ticks.changed
}
#[inline]
fn added(&self) -> Tick {
*self.ticks.added
}
#[inline]
fn changed_by(&self) -> MaybeLocation {
self.ticks.changed_by.copied()
}
}
impl<$($generics),*: ?Sized $(+ $traits)?> Deref for $name<$($generics),*> {
type Target = $target;
#[inline]
fn deref(&self) -> &Self::Target {
self.value
}
}
impl<$($generics),* $(: $traits)?> AsRef<$target> for $name<$($generics),*> {
#[inline]
fn as_ref(&self) -> &$target {
self.deref()
}
}
}
}
pub(crate) use change_detection_impl;
macro_rules! change_detection_mut_impl {
($name:ident < $( $generics:tt ),+ >, $target:ty, $($traits:ident)?) => {
impl<$($generics),* : ?Sized $(+ $traits)?> DetectChangesMut for $name<$($generics),*> {
type Inner = $target;
#[inline]
#[track_caller]
fn set_changed(&mut self) {
*self.ticks.changed = self.ticks.this_run;
self.ticks.changed_by.assign(MaybeLocation::caller());
}
#[inline]
#[track_caller]
fn set_added(&mut self) {
*self.ticks.changed = self.ticks.this_run;
*self.ticks.added = self.ticks.this_run;
self.ticks.changed_by.assign(MaybeLocation::caller());
}
#[inline]
#[track_caller]
fn set_last_changed(&mut self, last_changed: Tick) {
*self.ticks.changed = last_changed;
self.ticks.changed_by.assign(MaybeLocation::caller());
}
#[inline]
#[track_caller]
fn set_last_added(&mut self, last_added: Tick) {
*self.ticks.added = last_added;
*self.ticks.changed = last_added;
self.ticks.changed_by.assign(MaybeLocation::caller());
}
#[inline]
fn bypass_change_detection(&mut self) -> &mut Self::Inner {
self.value
}
}
impl<$($generics),* : ?Sized $(+ $traits)?> DerefMut for $name<$($generics),*> {
#[inline]
#[track_caller]
fn deref_mut(&mut self) -> &mut Self::Target {
self.set_changed();
self.ticks.changed_by.assign(MaybeLocation::caller());
self.value
}
}
impl<$($generics),* $(: $traits)?> AsMut<$target> for $name<$($generics),*> {
#[inline]
fn as_mut(&mut self) -> &mut $target {
self.deref_mut()
}
}
};
}
pub(crate) use change_detection_mut_impl;
macro_rules! impl_methods {
($name:ident < $( $generics:tt ),+ >, $target:ty, $($traits:ident)?) => {
impl<$($generics),* : ?Sized $(+ $traits)?> $name<$($generics),*> {
/// Consume `self` and return a mutable reference to the
/// contained value while marking `self` as "changed".
#[inline]
pub fn into_inner(mut self) -> &'w mut $target {
self.set_changed();
self.value
}
/// Returns a `Mut<>` with a smaller lifetime.
/// This is useful if you have `&mut
#[doc = stringify!($name)]
/// <T>`, but you need a `Mut<T>`.
pub fn reborrow(&mut self) -> Mut<'_, $target> {
Mut {
value: self.value,
ticks: ComponentTicksMut {
added: self.ticks.added,
changed: self.ticks.changed,
changed_by: self.ticks.changed_by.as_deref_mut(),
last_run: self.ticks.last_run,
this_run: self.ticks.this_run,
},
}
}
/// Maps to an inner value by applying a function to the contained reference, without flagging a change.
///
/// You should never modify the argument passed to the closure -- if you want to modify the data
/// without flagging a change, consider using [`DetectChangesMut::bypass_change_detection`] to make your intent explicit.
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(PartialEq)] pub struct Vec2;
/// # impl Vec2 { pub const ZERO: Self = Self; }
/// # #[derive(Component)] pub struct Transform { translation: Vec2 }
/// // When run, zeroes the translation of every entity.
/// fn reset_positions(mut transforms: Query<&mut Transform>) {
/// for transform in &mut transforms {
/// // We pinky promise not to modify `t` within the closure.
/// // Breaking this promise will result in logic errors, but will never cause undefined behavior.
/// let mut translation = transform.map_unchanged(|t| &mut t.translation);
/// // Only reset the translation if it isn't already zero;
/// translation.set_if_neq(Vec2::ZERO);
/// }
/// }
/// # bevy_ecs::system::assert_is_system(reset_positions);
/// ```
pub fn map_unchanged<U: ?Sized>(self, f: impl FnOnce(&mut $target) -> &mut U) -> Mut<'w, U> {
Mut {
value: f(self.value),
ticks: self.ticks,
}
}
/// Optionally maps to an inner value by applying a function to the contained reference.
/// This is useful in a situation where you need to convert a `Mut<T>` to a `Mut<U>`, but only if `T` contains `U`.
///
/// As with `map_unchanged`, you should never modify the argument passed to the closure.
pub fn filter_map_unchanged<U: ?Sized>(self, f: impl FnOnce(&mut $target) -> Option<&mut U>) -> Option<Mut<'w, U>> {
let value = f(self.value);
value.map(|value| Mut {
value,
ticks: self.ticks,
})
}
/// Optionally maps to an inner value by applying a function to the contained reference, returns an error on failure.
/// This is useful in a situation where you need to convert a `Mut<T>` to a `Mut<U>`, but only if `T` contains `U`.
///
/// As with `map_unchanged`, you should never modify the argument passed to the closure.
pub fn try_map_unchanged<U: ?Sized, E>(self, f: impl FnOnce(&mut $target) -> Result<&mut U, E>) -> Result<Mut<'w, U>, E> {
let value = f(self.value);
value.map(|value| Mut {
value,
ticks: self.ticks,
})
}
/// Allows you access to the dereferenced value of this pointer without immediately
/// triggering change detection.
pub fn as_deref_mut(&mut self) -> Mut<'_, <$target as Deref>::Target>
where $target: DerefMut
{
self.reborrow().map_unchanged(|v| v.deref_mut())
}
}
};
}
pub(crate) use impl_methods;
macro_rules! impl_debug {
($name:ident < $( $generics:tt ),+ >, $($traits:ident)?) => {
impl<$($generics),* : ?Sized $(+ $traits)?> core::fmt::Debug for $name<$($generics),*>
where T: core::fmt::Debug
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_tuple(stringify!($name))
.field(&self.value)
.finish()
}
}
};
}
pub(crate) use impl_debug;
| 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/change_detection/tick.rs | crates/bevy_ecs/src/change_detection/tick.rs | use bevy_ecs_macros::Event;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
use core::{cell::UnsafeCell, panic::Location};
use crate::change_detection::{MaybeLocation, MAX_CHANGE_AGE};
/// A value that tracks when a system ran relative to other systems.
/// This is used to power change detection.
///
/// *Note* that a system that hasn't been run yet has a `Tick` of 0.
#[derive(Copy, Clone, Default, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, Hash, PartialEq, Clone)
)]
pub struct Tick {
tick: u32,
}
impl Tick {
/// The maximum relative age for a change tick.
/// The value of this is equal to [`MAX_CHANGE_AGE`].
///
/// Since change detection will not work for any ticks older than this,
/// ticks are periodically scanned to ensure their relative values are below this.
pub const MAX: Self = Self::new(MAX_CHANGE_AGE);
/// Creates a new [`Tick`] wrapping the given value.
#[inline]
pub const fn new(tick: u32) -> Self {
Self { tick }
}
/// Gets the value of this change tick.
#[inline]
pub const fn get(self) -> u32 {
self.tick
}
/// Sets the value of this change tick.
#[inline]
pub fn set(&mut self, tick: u32) {
self.tick = tick;
}
/// Returns `true` if this `Tick` occurred since the system's `last_run`.
///
/// `this_run` is the current tick of the system, used as a reference to help deal with wraparound.
#[inline]
pub fn is_newer_than(self, last_run: Tick, this_run: Tick) -> bool {
// This works even with wraparound because the world tick (`this_run`) is always "newer" than
// `last_run` and `self.tick`, and we scan periodically to clamp `ComponentTicks` values
// so they never get older than `u32::MAX` (the difference would overflow).
//
// The clamp here ensures determinism (since scans could differ between app runs).
let ticks_since_insert = this_run.relative_to(self).tick.min(MAX_CHANGE_AGE);
let ticks_since_system = this_run.relative_to(last_run).tick.min(MAX_CHANGE_AGE);
ticks_since_system > ticks_since_insert
}
/// Returns a change tick representing the relationship between `self` and `other`.
#[inline]
pub(crate) fn relative_to(self, other: Self) -> Self {
let tick = self.tick.wrapping_sub(other.tick);
Self { tick }
}
/// Wraps this change tick's value if it exceeds [`Tick::MAX`].
///
/// Returns `true` if wrapping was performed. Otherwise, returns `false`.
#[inline]
pub fn check_tick(&mut self, check: CheckChangeTicks) -> bool {
let age = check.present_tick().relative_to(*self);
// This comparison assumes that `age` has not overflowed `u32::MAX` before, which will be true
// so long as this check always runs before that can happen.
if age.get() > Self::MAX.get() {
*self = check.present_tick().relative_to(Self::MAX);
true
} else {
false
}
}
}
/// An [`Event`] that can be used to maintain [`Tick`]s in custom data structures, enabling to make
/// use of bevy's periodic checks that clamps ticks to a certain range, preventing overflows and thus
/// keeping methods like [`Tick::is_newer_than`] reliably return `false` for ticks that got too old.
///
/// # Example
///
/// Here a schedule is stored in a custom resource. This way the systems in it would not have their change
/// ticks automatically updated via [`World::check_change_ticks`](crate::world::World::check_change_ticks),
/// possibly causing `Tick`-related bugs on long-running apps.
///
/// To fix that, add an observer for this event that calls the schedule's
/// [`Schedule::check_change_ticks`](bevy_ecs::schedule::Schedule::check_change_ticks).
///
/// ```
/// use bevy_ecs::prelude::*;
/// use bevy_ecs::change_detection::CheckChangeTicks;
///
/// #[derive(Resource)]
/// struct CustomSchedule(Schedule);
///
/// # let mut world = World::new();
/// world.add_observer(|check: On<CheckChangeTicks>, mut schedule: ResMut<CustomSchedule>| {
/// schedule.0.check_change_ticks(*check);
/// });
/// ```
#[derive(Debug, Clone, Copy, Event)]
pub struct CheckChangeTicks(pub(crate) Tick);
impl CheckChangeTicks {
/// Get the present `Tick` that other ticks get compared to.
pub fn present_tick(self) -> Tick {
self.0
}
}
/// Interior-mutable access to the [`Tick`]s of a single component or resource.
#[derive(Copy, Clone, Debug)]
pub struct ComponentTickCells<'a> {
/// The tick indicating when the value was added to the world.
pub added: &'a UnsafeCell<Tick>,
/// The tick indicating the last time the value was modified.
pub changed: &'a UnsafeCell<Tick>,
/// The calling location that last modified the value.
pub changed_by: MaybeLocation<&'a UnsafeCell<&'static Location<'static>>>,
}
/// Records when a component or resource was added and when it was last mutably dereferenced (or added).
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
pub struct ComponentTicks {
/// Tick recording the time this component or resource was added.
pub added: Tick,
/// Tick recording the time this component or resource was most recently changed.
pub changed: Tick,
}
impl ComponentTicks {
/// Returns `true` if the component or resource was added after the system last ran
/// (or the system is running for the first time).
#[inline]
pub fn is_added(&self, last_run: Tick, this_run: Tick) -> bool {
self.added.is_newer_than(last_run, this_run)
}
/// Returns `true` if the component or resource was added or mutably dereferenced after the system last ran
/// (or the system is running for the first time).
#[inline]
pub fn is_changed(&self, last_run: Tick, this_run: Tick) -> bool {
self.changed.is_newer_than(last_run, this_run)
}
/// Creates a new instance with the same change tick for `added` and `changed`.
pub fn new(change_tick: Tick) -> Self {
Self {
added: change_tick,
changed: change_tick,
}
}
/// Manually sets the change tick.
///
/// This is normally done automatically via the [`DerefMut`](core::ops::DerefMut) implementation
/// on [`Mut<T>`](crate::change_detection::Mut), [`ResMut<T>`](crate::change_detection::ResMut), etc.
/// However, components and resources that make use of interior mutability might require manual updates.
///
/// # Example
/// ```no_run
/// # use bevy_ecs::{world::World, change_detection::ComponentTicks};
/// let world: World = unimplemented!();
/// let component_ticks: ComponentTicks = unimplemented!();
///
/// component_ticks.set_changed(world.read_change_tick());
/// ```
#[inline]
pub fn set_changed(&mut self, change_tick: Tick) {
self.changed = change_tick;
}
}
| 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/entity/clone_entities.rs | crates/bevy_ecs/src/entity/clone_entities.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."
)]
use crate::{
archetype::Archetype,
bundle::{Bundle, BundleRemover, InsertMode},
change_detection::MaybeLocation,
component::{Component, ComponentCloneBehavior, ComponentCloneFn, ComponentId, ComponentInfo},
entity::{hash_map::EntityHashMap, Entity, EntityAllocator, EntityMapper},
query::DebugCheckedUnwrap,
relationship::RelationshipHookMode,
world::World,
};
use alloc::{boxed::Box, collections::VecDeque, vec::Vec};
use bevy_platform::collections::{hash_map::Entry, HashMap, HashSet};
use bevy_ptr::{Ptr, PtrMut};
use bevy_utils::prelude::DebugName;
use bumpalo::Bump;
use core::{any::TypeId, cell::LazyCell, ops::Range};
use derive_more::From;
/// Provides read access to the source component (the component being cloned) in a [`ComponentCloneFn`].
pub struct SourceComponent<'a> {
ptr: Ptr<'a>,
info: &'a ComponentInfo,
}
impl<'a> SourceComponent<'a> {
/// Returns a reference to the component on the source entity.
///
/// Will return `None` if `ComponentId` of requested component does not match `ComponentId` of source component
pub fn read<C: Component>(&self) -> Option<&C> {
if self
.info
.type_id()
.is_some_and(|id| id == TypeId::of::<C>())
{
// SAFETY:
// - Components and ComponentId are from the same world
// - source_component_ptr holds valid data of the type referenced by ComponentId
unsafe { Some(self.ptr.deref::<C>()) }
} else {
None
}
}
/// Returns the "raw" pointer to the source component.
pub fn ptr(&self) -> Ptr<'a> {
self.ptr
}
/// Returns a reference to the component on the source entity as [`&dyn Reflect`](bevy_reflect::Reflect).
///
/// Will return `None` if:
/// - World does not have [`AppTypeRegistry`](`crate::reflect::AppTypeRegistry`).
/// - Component does not implement [`ReflectFromPtr`](bevy_reflect::ReflectFromPtr).
/// - Component is not registered.
/// - Component does not have [`TypeId`]
/// - Registered [`ReflectFromPtr`](bevy_reflect::ReflectFromPtr)'s [`TypeId`] does not match component's [`TypeId`]
#[cfg(feature = "bevy_reflect")]
pub fn read_reflect(
&self,
registry: &bevy_reflect::TypeRegistry,
) -> Option<&dyn bevy_reflect::Reflect> {
let type_id = self.info.type_id()?;
let reflect_from_ptr = registry.get_type_data::<bevy_reflect::ReflectFromPtr>(type_id)?;
if reflect_from_ptr.type_id() != type_id {
return None;
}
// SAFETY: `source_component_ptr` stores data represented by `component_id`, which we used to get `ReflectFromPtr`.
unsafe { Some(reflect_from_ptr.as_reflect(self.ptr)) }
}
}
/// Context for component clone handlers.
///
/// Provides fast access to useful resources like [`AppTypeRegistry`](crate::reflect::AppTypeRegistry)
/// and allows component clone handler to get information about component being cloned.
pub struct ComponentCloneCtx<'a, 'b> {
component_id: ComponentId,
target_component_written: bool,
target_component_moved: bool,
bundle_scratch: &'a mut BundleScratch<'b>,
bundle_scratch_allocator: &'b Bump,
allocator: &'a EntityAllocator,
source: Entity,
target: Entity,
component_info: &'a ComponentInfo,
state: &'a mut EntityClonerState,
mapper: &'a mut dyn EntityMapper,
#[cfg(feature = "bevy_reflect")]
type_registry: Option<&'a crate::reflect::AppTypeRegistry>,
#[cfg(not(feature = "bevy_reflect"))]
#[expect(dead_code, reason = "type_registry is only used with bevy_reflect")]
type_registry: Option<&'a ()>,
}
impl<'a, 'b> ComponentCloneCtx<'a, 'b> {
/// Create a new instance of `ComponentCloneCtx` that can be passed to component clone handlers.
///
/// # Safety
/// Caller must ensure that:
/// - `component_info` corresponds to the `component_id` in the same world,.
/// - `source_component_ptr` points to a valid component of type represented by `component_id`.
unsafe fn new(
component_id: ComponentId,
source: Entity,
target: Entity,
bundle_scratch_allocator: &'b Bump,
bundle_scratch: &'a mut BundleScratch<'b>,
allocator: &'a EntityAllocator,
component_info: &'a ComponentInfo,
entity_cloner: &'a mut EntityClonerState,
mapper: &'a mut dyn EntityMapper,
#[cfg(feature = "bevy_reflect")] type_registry: Option<&'a crate::reflect::AppTypeRegistry>,
#[cfg(not(feature = "bevy_reflect"))] type_registry: Option<&'a ()>,
) -> Self {
Self {
component_id,
source,
target,
bundle_scratch,
target_component_written: false,
target_component_moved: false,
bundle_scratch_allocator,
allocator,
mapper,
component_info,
state: entity_cloner,
type_registry,
}
}
/// Returns true if [`write_target_component`](`Self::write_target_component`) was called before.
pub fn target_component_written(&self) -> bool {
self.target_component_written
}
/// Returns `true` if used in moving context
pub fn moving(&self) -> bool {
self.state.move_components
}
/// Returns the current source entity.
pub fn source(&self) -> Entity {
self.source
}
/// Returns the current target entity.
pub fn target(&self) -> Entity {
self.target
}
/// Returns the [`ComponentId`] of the component being cloned.
pub fn component_id(&self) -> ComponentId {
self.component_id
}
/// Returns the [`ComponentInfo`] of the component being cloned.
pub fn component_info(&self) -> &ComponentInfo {
self.component_info
}
/// Returns true if the [`EntityCloner`] is configured to recursively clone entities. When this is enabled,
/// entities stored in a cloned entity's [`RelationshipTarget`](crate::relationship::RelationshipTarget) component with
/// [`RelationshipTarget::LINKED_SPAWN`](crate::relationship::RelationshipTarget::LINKED_SPAWN) will also be cloned.
#[inline]
pub fn linked_cloning(&self) -> bool {
self.state.linked_cloning
}
/// Returns this context's [`EntityMapper`].
pub fn entity_mapper(&mut self) -> &mut dyn EntityMapper {
self.mapper
}
/// Writes component data to target entity.
///
/// # Panics
/// This will panic if:
/// - Component has already been written once.
/// - Component being written is not registered in the world.
/// - `ComponentId` of component being written does not match expected `ComponentId`.
pub fn write_target_component<C: Component>(&mut self, mut component: C) {
C::map_entities(&mut component, &mut self.mapper);
let debug_name = DebugName::type_name::<C>();
let short_name = debug_name.shortname();
if self.target_component_written {
panic!("Trying to write component '{short_name}' multiple times")
}
if self
.component_info
.type_id()
.is_none_or(|id| id != TypeId::of::<C>())
{
panic!("TypeId of component '{short_name}' does not match source component TypeId")
};
// SAFETY: the TypeId of self.component_id has been checked to ensure it matches `C`
unsafe {
self.bundle_scratch
.push(self.bundle_scratch_allocator, self.component_id, component);
};
self.target_component_written = true;
}
/// Writes component data to target entity by providing a pointer to source component data.
///
/// # Safety
/// Caller must ensure that the passed in `ptr` references data that corresponds to the type of the source / target [`ComponentId`].
/// `ptr` must also contain data that the written component can "own" (for example, this should not directly copy non-Copy data).
///
/// # Panics
/// This will panic if component has already been written once.
pub unsafe fn write_target_component_ptr(&mut self, ptr: Ptr) {
if self.target_component_written {
panic!("Trying to write component multiple times")
}
let layout = self.component_info.layout();
let target_ptr = self.bundle_scratch_allocator.alloc_layout(layout);
core::ptr::copy_nonoverlapping(ptr.as_ptr(), target_ptr.as_ptr(), layout.size());
self.bundle_scratch
.push_ptr(self.component_id, PtrMut::new(target_ptr));
self.target_component_written = true;
}
/// Writes component data to target entity.
///
/// # Panics
/// This will panic if:
/// - World does not have [`AppTypeRegistry`](`crate::reflect::AppTypeRegistry`).
/// - Component does not implement [`ReflectFromPtr`](bevy_reflect::ReflectFromPtr).
/// - Source component does not have [`TypeId`].
/// - Passed component's [`TypeId`] does not match source component [`TypeId`].
/// - Component has already been written once.
#[cfg(feature = "bevy_reflect")]
pub fn write_target_component_reflect(&mut self, component: Box<dyn bevy_reflect::Reflect>) {
if self.target_component_written {
panic!("Trying to write component multiple times")
}
let source_type_id = self
.component_info
.type_id()
.expect("Source component must have TypeId");
let component_type_id = component.type_id();
if source_type_id != component_type_id {
panic!("Passed component TypeId does not match source component TypeId")
}
let component_layout = self.component_info.layout();
let component_data_ptr = Box::into_raw(component).cast::<u8>();
let target_component_data_ptr =
self.bundle_scratch_allocator.alloc_layout(component_layout);
// SAFETY:
// - target_component_data_ptr and component_data have the same data type.
// - component_data_ptr has layout of component_layout
unsafe {
core::ptr::copy_nonoverlapping(
component_data_ptr,
target_component_data_ptr.as_ptr(),
component_layout.size(),
);
self.bundle_scratch
.push_ptr(self.component_id, PtrMut::new(target_component_data_ptr));
if component_layout.size() > 0 {
// Ensure we don't attempt to deallocate zero-sized components
alloc::alloc::dealloc(component_data_ptr, component_layout);
}
}
self.target_component_written = true;
}
/// Returns [`AppTypeRegistry`](`crate::reflect::AppTypeRegistry`) if it exists in the world.
///
/// NOTE: Prefer this method instead of manually reading the resource from the world.
#[cfg(feature = "bevy_reflect")]
pub fn type_registry(&self) -> Option<&crate::reflect::AppTypeRegistry> {
self.type_registry
}
/// Queues the `entity` to be cloned by the current [`EntityCloner`]
pub fn queue_entity_clone(&mut self, entity: Entity) {
let target = self.allocator.alloc();
self.mapper.set_mapped(entity, target);
self.state.clone_queue.push_back(entity);
}
/// Queues a deferred clone operation, which will run with exclusive [`World`] access immediately after calling the clone handler for each component on an entity.
/// This exists, despite its similarity to [`Commands`](crate::system::Commands), to provide access to the entity mapper in the current context.
pub fn queue_deferred(
&mut self,
deferred: impl FnOnce(&mut World, &mut dyn EntityMapper) + 'static,
) {
self.state.deferred_commands.push_back(Box::new(deferred));
}
/// Marks component as moved and it's `drop` won't run.
fn move_component(&mut self) {
self.target_component_moved = true;
self.target_component_written = true;
}
}
/// A configuration determining how to clone entities. This can be built using [`EntityCloner::build_opt_out`]/
/// [`opt_in`](EntityCloner::build_opt_in), which
/// returns an [`EntityClonerBuilder`].
///
/// After configuration is complete an entity can be cloned using [`Self::clone_entity`].
///
///```
/// use bevy_ecs::prelude::*;
/// use bevy_ecs::entity::EntityCloner;
///
/// #[derive(Component, Clone, PartialEq, Eq)]
/// struct A {
/// field: usize,
/// }
///
/// let mut world = World::default();
///
/// let component = A { field: 5 };
///
/// let entity = world.spawn(component.clone()).id();
/// let entity_clone = world.spawn_empty().id();
///
/// EntityCloner::build_opt_out(&mut world).clone_entity(entity, entity_clone);
///
/// assert!(world.get::<A>(entity_clone).is_some_and(|c| *c == component));
///```
///
/// # Default cloning strategy
/// By default, all types that derive [`Component`] and implement either [`Clone`] or `Reflect` (with `ReflectComponent`) will be cloned
/// (with `Clone`-based implementation preferred in case component implements both).
///
/// It should be noted that if `Component` is implemented manually or if `Clone` implementation is conditional
/// (like when deriving `Clone` for a type with a generic parameter without `Clone` bound),
/// the component will be cloned using the [default cloning strategy](crate::component::ComponentCloneBehavior::global_default_fn).
/// To use `Clone`-based handler ([`ComponentCloneBehavior::clone`]) in this case it should be set manually using one
/// of the methods mentioned in the [Clone Behaviors](#Clone-Behaviors) section
///
/// Here's an example of how to do it using [`clone_behavior`](Component::clone_behavior):
/// ```
/// # use bevy_ecs::prelude::*;
/// # use bevy_ecs::component::{StorageType, ComponentCloneBehavior, Mutable};
/// #[derive(Clone, Component)]
/// #[component(clone_behavior = clone::<Self>())]
/// struct SomeComponent;
///
/// ```
///
/// # Clone Behaviors
/// [`EntityCloner`] clones entities by cloning components using [`ComponentCloneBehavior`], and there are multiple layers
/// to decide which handler to use for which component. The overall hierarchy looks like this (priority from most to least):
/// 1. local overrides using [`EntityClonerBuilder::override_clone_behavior`]
/// 2. component-defined handler using [`Component::clone_behavior`]
/// 3. default handler override using [`EntityClonerBuilder::with_default_clone_fn`].
/// 4. reflect-based or noop default clone handler depending on if `bevy_reflect` feature is enabled or not.
///
/// # Moving components
/// [`EntityCloner`] can be configured to move components instead of cloning them by using [`EntityClonerBuilder::move_components`].
/// In this mode components will be moved - removed from source entity and added to the target entity.
///
/// Components with [`ComponentCloneBehavior::Ignore`] clone behavior will not be moved, while components that
/// have a [`ComponentCloneBehavior::Custom`] clone behavior will be cloned using it and then removed from the source entity.
/// All other components will be bitwise copied from the source entity onto the target entity and then removed without dropping.
///
/// Choosing to move components instead of cloning makes [`EntityClonerBuilder::with_default_clone_fn`] ineffective since it's replaced by
/// move handler for components that have [`ComponentCloneBehavior::Default`] clone behavior.
///
/// Note that moving components still triggers `on_remove` hooks/observers on source entity and `on_insert`/`on_add` hooks/observers on the target entity.
#[derive(Default)]
pub struct EntityCloner {
filter: EntityClonerFilter,
state: EntityClonerState,
}
/// An expandable scratch space for defining a dynamic bundle.
struct BundleScratch<'a> {
component_ids: Vec<ComponentId>,
component_ptrs: Vec<PtrMut<'a>>,
}
impl<'a> BundleScratch<'a> {
pub(crate) fn with_capacity(capacity: usize) -> Self {
Self {
component_ids: Vec::with_capacity(capacity),
component_ptrs: Vec::with_capacity(capacity),
}
}
/// Pushes the `ptr` component onto this storage with the given `id` [`ComponentId`].
///
/// # Safety
/// The `id` [`ComponentId`] must match the component `ptr` for whatever [`World`] this scratch will
/// be written to. `ptr` must contain valid uniquely-owned data that matches the type of component referenced
/// in `id`.
pub(crate) unsafe fn push_ptr(&mut self, id: ComponentId, ptr: PtrMut<'a>) {
self.component_ids.push(id);
self.component_ptrs.push(ptr);
}
/// Pushes the `C` component onto this storage with the given `id` [`ComponentId`], using the given `bump` allocator.
///
/// # Safety
/// The `id` [`ComponentId`] must match the component `C` for whatever [`World`] this scratch will
/// be written to.
pub(crate) unsafe fn push<C: Component>(
&mut self,
allocator: &'a Bump,
id: ComponentId,
component: C,
) {
let component_ref = allocator.alloc(component);
self.component_ids.push(id);
self.component_ptrs.push(PtrMut::from(component_ref));
}
/// Writes the scratch components to the given entity in the given world.
///
/// # Safety
/// All [`ComponentId`] values in this instance must come from `world`.
#[track_caller]
pub(crate) unsafe fn write(
self,
world: &mut World,
entity: Entity,
relationship_hook_insert_mode: RelationshipHookMode,
) {
// SAFETY:
// - All `component_ids` are from the same world as `entity`
// - All `component_data_ptrs` are valid types represented by `component_ids`
unsafe {
world.entity_mut(entity).insert_by_ids_internal(
&self.component_ids,
self.component_ptrs.into_iter().map(|ptr| ptr.promote()),
relationship_hook_insert_mode,
);
}
}
}
impl EntityCloner {
/// Returns a new [`EntityClonerBuilder`] using the given `world` with the [`OptOut`] configuration.
///
/// 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 build_opt_out(world: &mut World) -> EntityClonerBuilder<'_, OptOut> {
EntityClonerBuilder {
world,
filter: Default::default(),
state: Default::default(),
}
}
/// Returns a new [`EntityClonerBuilder`] using the given `world` with the [`OptIn`] configuration.
///
/// 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.
///
/// Components allowed to be cloned through this builder would also allow their required components,
/// which will be cloned from the source entity only if the target entity does not contain them already.
/// To skip adding required components see [`without_required_components`](EntityClonerBuilder<OptIn>::without_required_components).
pub fn build_opt_in(world: &mut World) -> EntityClonerBuilder<'_, OptIn> {
EntityClonerBuilder {
world,
filter: Default::default(),
state: Default::default(),
}
}
/// Returns `true` if this cloner is configured to clone entities referenced in cloned components via [`RelationshipTarget::LINKED_SPAWN`](crate::relationship::RelationshipTarget::LINKED_SPAWN).
/// This will produce "deep" / recursive clones of relationship trees that have "linked spawn".
#[inline]
pub fn linked_cloning(&self) -> bool {
self.state.linked_cloning
}
/// Clones and inserts components from the `source` entity into `target` entity using the stored configuration.
/// If this [`EntityCloner`] has [`EntityCloner::linked_cloning`], then it will recursively spawn entities as defined
/// by [`RelationshipTarget`](crate::relationship::RelationshipTarget) components with
/// [`RelationshipTarget::LINKED_SPAWN`](crate::relationship::RelationshipTarget::LINKED_SPAWN)
#[track_caller]
pub fn clone_entity(&mut self, world: &mut World, source: Entity, target: Entity) {
let mut map = EntityHashMap::<Entity>::new();
map.set_mapped(source, target);
self.clone_entity_mapped(world, source, &mut map);
}
/// Clones and inserts components from the `source` entity into a newly spawned entity using the stored configuration.
/// If this [`EntityCloner`] has [`EntityCloner::linked_cloning`], then it will recursively spawn entities as defined
/// by [`RelationshipTarget`](crate::relationship::RelationshipTarget) components with
/// [`RelationshipTarget::LINKED_SPAWN`](crate::relationship::RelationshipTarget::LINKED_SPAWN)
#[track_caller]
pub fn spawn_clone(&mut self, world: &mut World, source: Entity) -> Entity {
let target = world.spawn_empty().id();
self.clone_entity(world, source, target);
target
}
/// Clones the entity into whatever entity `mapper` chooses for it.
#[track_caller]
pub fn clone_entity_mapped(
&mut self,
world: &mut World,
source: Entity,
mapper: &mut dyn EntityMapper,
) -> Entity {
Self::clone_entity_mapped_internal(&mut self.state, &mut self.filter, world, source, mapper)
}
#[track_caller]
#[inline]
fn clone_entity_mapped_internal(
state: &mut EntityClonerState,
filter: &mut impl CloneByFilter,
world: &mut World,
source: Entity,
mapper: &mut dyn EntityMapper,
) -> Entity {
// All relationships on the root should have their hooks run
let target = Self::clone_entity_internal(
state,
filter,
world,
source,
mapper,
RelationshipHookMode::Run,
);
let child_hook_insert_mode = if state.linked_cloning {
// When spawning "linked relationships", we want to ignore hooks for relationships we are spawning, while
// still registering with original relationship targets that are "not linked" to the current recursive spawn.
RelationshipHookMode::RunIfNotLinked
} else {
// If we are not cloning "linked relationships" recursively, then we want any cloned relationship components to
// register themselves with their original relationship target.
RelationshipHookMode::Run
};
loop {
let queued = state.clone_queue.pop_front();
if let Some(queued) = queued {
Self::clone_entity_internal(
state,
filter,
world,
queued,
mapper,
child_hook_insert_mode,
);
} else {
break;
}
}
target
}
/// Clones and inserts components from the `source` entity into the entity mapped by `mapper` from `source` using the stored configuration.
#[track_caller]
fn clone_entity_internal(
state: &mut EntityClonerState,
filter: &mut impl CloneByFilter,
world: &mut World,
source: Entity,
mapper: &mut dyn EntityMapper,
relationship_hook_insert_mode: RelationshipHookMode,
) -> Entity {
let target = mapper.get_mapped(source);
// The target may need to be constructed if it hasn't been already.
// If this fails, it either didn't need to be constructed (ok) or doesn't exist (caught better later).
let _ = world.spawn_empty_at(target);
// PERF: reusing allocated space across clones would be more efficient. Consider an allocation model similar to `Commands`.
let bundle_scratch_allocator = Bump::new();
let mut bundle_scratch: BundleScratch;
let mut moved_components: Vec<ComponentId> = Vec::new();
let mut deferred_cloned_component_ids: Vec<ComponentId> = Vec::new();
{
let world = world.as_unsafe_world_cell();
let source_entity = world
.get_entity(source)
.expect("Source entity must be valid and spawned.");
let source_archetype = source_entity.archetype();
#[cfg(feature = "bevy_reflect")]
// SAFETY: we have unique access to `world`, nothing else accesses the registry at this moment, and we clone
// the registry, which prevents future conflicts.
let app_registry = unsafe {
world
.get_resource::<crate::reflect::AppTypeRegistry>()
.cloned()
};
#[cfg(not(feature = "bevy_reflect"))]
let app_registry = Option::<()>::None;
bundle_scratch = BundleScratch::with_capacity(source_archetype.component_count());
let target_archetype = LazyCell::new(|| {
world
.get_entity(target)
.expect("Target entity must be valid and spawned.")
.archetype()
});
if state.move_components {
moved_components.reserve(source_archetype.component_count());
// Replace default handler with special handler which would track if component was moved instead of cloned.
// This is later used to determine whether we need to run component's drop function when removing it from the source entity or not.
state.default_clone_fn = |_, ctx| ctx.move_component();
}
filter.clone_components(source_archetype, target_archetype, |component| {
let handler = match state.clone_behavior_overrides.get(&component).or_else(|| {
world
.components()
.get_info(component)
.map(ComponentInfo::clone_behavior)
}) {
Some(behavior) => match behavior {
ComponentCloneBehavior::Default => state.default_clone_fn,
ComponentCloneBehavior::Ignore => return,
ComponentCloneBehavior::Custom(custom) => *custom,
},
None => state.default_clone_fn,
};
// SAFETY: This component exists because it is present on the archetype.
let info = unsafe { world.components().get_info_unchecked(component) };
// SAFETY:
// - There are no other mutable references to source entity.
// - `component` is from `source_entity`'s archetype
let source_component_ptr =
unsafe { source_entity.get_by_id(component).debug_checked_unwrap() };
let source_component = SourceComponent {
info,
ptr: source_component_ptr,
};
// SAFETY:
// - `components` and `component` are from the same world
// - `source_component_ptr` is valid and points to the same type as represented by `component`
let mut ctx = unsafe {
ComponentCloneCtx::new(
component,
source,
target,
&bundle_scratch_allocator,
&mut bundle_scratch,
world.entities_allocator(),
info,
state,
mapper,
app_registry.as_ref(),
)
};
(handler)(&source_component, &mut ctx);
if ctx.state.move_components {
if ctx.target_component_moved {
moved_components.push(component);
}
// Component wasn't written by the clone handler, so assume it's going to be
// cloned/processed using deferred_commands instead.
// This means that it's ComponentId won't be present in BundleScratch's component_ids,
// but it should still be removed when move_components is true.
else if !ctx.target_component_written() {
deferred_cloned_component_ids.push(component);
}
}
});
}
world.flush();
for deferred in state.deferred_commands.drain(..) {
(deferred)(world, mapper);
}
if !world.entities.contains(target) {
panic!("Target entity does not exist");
}
if state.move_components {
let mut source_entity = world.entity_mut(source);
let cloned_components = if deferred_cloned_component_ids.is_empty() {
&bundle_scratch.component_ids
} else {
// Remove all cloned components with drop by concatenating both vectors
deferred_cloned_component_ids.extend(&bundle_scratch.component_ids);
&deferred_cloned_component_ids
};
source_entity.remove_by_ids_with_caller(
cloned_components,
MaybeLocation::caller(),
RelationshipHookMode::RunIfNotLinked,
BundleRemover::empty_pre_remove,
);
let table_row = source_entity.location().table_row;
// Copy moved components and then forget them without calling drop
source_entity.remove_by_ids_with_caller(
&moved_components,
MaybeLocation::caller(),
RelationshipHookMode::RunIfNotLinked,
|sparse_sets, mut table, components, bundle| {
for &component_id in bundle {
let Some(component_ptr) = sparse_sets
.get(component_id)
.and_then(|component| component.get(source))
.or_else(|| {
// SAFETY: table_row is within this table because we just got it from entity's current location
table.as_mut().and_then(|table| unsafe {
table.get_component(component_id, table_row)
})
})
else {
// Component was removed by some other component's clone side effect before we got to it.
continue;
};
// SAFETY: component_id is valid because remove_by_ids_with_caller checked it before calling this closure
let info = unsafe { components.get_info_unchecked(component_id) };
let layout = info.layout();
let target_ptr = bundle_scratch_allocator.alloc_layout(layout);
// SAFETY:
// - component_ptr points to data with component layout
// - target_ptr was just allocated with component layout
// - component_ptr and target_ptr don't overlap
// - component_ptr matches component_id
unsafe {
core::ptr::copy_nonoverlapping(
component_ptr.as_ptr(),
target_ptr.as_ptr(),
layout.size(),
);
bundle_scratch.push_ptr(component_id, PtrMut::new(target_ptr));
}
}
(/* should drop? */ false, ())
},
);
}
// SAFETY:
// - All `component_ids` are from the same world as `target` entity
| 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/index_map.rs | crates/bevy_ecs/src/entity/index_map.rs | //! Contains the [`EntityIndexMap`] type, an [`IndexMap`] pre-configured to use [`EntityHash`] hashing.
//!
//! This module is a lightweight wrapper around `indexmap`'s [`IndexMap`] that is more performant for [`Entity`] keys.
use core::{
cmp::Ordering,
fmt::{self, Debug, Formatter},
hash::{BuildHasher, Hash, Hasher},
iter::FusedIterator,
marker::PhantomData,
ops::{
Bound, Deref, DerefMut, Index, IndexMut, Range, RangeBounds, RangeFrom, RangeFull,
RangeInclusive, RangeTo, RangeToInclusive,
},
ptr,
};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
pub use indexmap::map::Entry;
use indexmap::map::{self, IndexMap, IntoValues, ValuesMut};
use super::{Entity, EntityEquivalent, EntityHash, EntitySetIterator};
use bevy_platform::prelude::Box;
/// A [`IndexMap`] pre-configured to use [`EntityHash`] hashing.
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serialize", derive(serde::Deserialize, serde::Serialize))]
#[derive(Debug, Clone)]
pub struct EntityIndexMap<V>(pub(crate) IndexMap<Entity, V, EntityHash>);
impl<V> EntityIndexMap<V> {
/// Creates an empty `EntityIndexMap`.
///
/// Equivalent to [`IndexMap::with_hasher(EntityHash)`].
///
/// [`IndexMap::with_hasher(EntityHash)`]: IndexMap::with_hasher
pub const fn new() -> Self {
Self(IndexMap::with_hasher(EntityHash))
}
/// Creates an empty `EntityIndexMap` with the specified capacity.
///
/// Equivalent to [`IndexMap::with_capacity_and_hasher(n, EntityHash)`].
///
/// [`IndexMap:with_capacity_and_hasher(n, EntityHash)`]: IndexMap::with_capacity_and_hasher
pub fn with_capacity(n: usize) -> Self {
Self(IndexMap::with_capacity_and_hasher(n, EntityHash))
}
/// Returns the inner [`IndexMap`].
pub fn into_inner(self) -> IndexMap<Entity, V, EntityHash> {
self.0
}
/// Returns a slice of all the key-value pairs in the map.
///
/// Equivalent to [`IndexMap::as_slice`].
pub fn as_slice(&self) -> &Slice<V> {
// SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
unsafe { Slice::from_slice_unchecked(self.0.as_slice()) }
}
/// Returns a mutable slice of all the key-value pairs in the map.
///
/// Equivalent to [`IndexMap::as_mut_slice`].
pub fn as_mut_slice(&mut self) -> &mut Slice<V> {
// SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
unsafe { Slice::from_slice_unchecked_mut(self.0.as_mut_slice()) }
}
/// Converts into a boxed slice of all the key-value pairs in the map.
///
/// Equivalent to [`IndexMap::into_boxed_slice`].
pub fn into_boxed_slice(self) -> Box<Slice<V>> {
// SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
unsafe { Slice::from_boxed_slice_unchecked(self.0.into_boxed_slice()) }
}
/// Returns a slice of key-value pairs in the given range of indices.
///
/// Equivalent to [`IndexMap::get_range`].
pub fn get_range<R: RangeBounds<usize>>(&self, range: R) -> Option<&Slice<V>> {
self.0.get_range(range).map(|slice|
// SAFETY: EntityIndexSetSlice is a transparent wrapper around indexmap::set::Slice.
unsafe { Slice::from_slice_unchecked(slice) })
}
/// Returns a mutable slice of key-value pairs in the given range of indices.
///
/// Equivalent to [`IndexMap::get_range_mut`].
pub fn get_range_mut<R: RangeBounds<usize>>(&mut self, range: R) -> Option<&mut Slice<V>> {
self.0.get_range_mut(range).map(|slice|
// SAFETY: EntityIndexSetSlice is a transparent wrapper around indexmap::set::Slice.
unsafe { Slice::from_slice_unchecked_mut(slice) })
}
/// Return an iterator over the key-value pairs of the map, in their order.
///
/// Equivalent to [`IndexMap::iter`].
pub fn iter(&self) -> Iter<'_, V> {
Iter(self.0.iter(), PhantomData)
}
/// Return a mutable iterator over the key-value pairs of the map, in their order.
///
/// Equivalent to [`IndexMap::iter_mut`].
pub fn iter_mut(&mut self) -> IterMut<'_, V> {
IterMut(self.0.iter_mut(), PhantomData)
}
/// Clears the `IndexMap` in the given index range, returning those
/// key-value pairs as a drain iterator.
///
/// Equivalent to [`IndexMap::drain`].
pub fn drain<R: RangeBounds<usize>>(&mut self, range: R) -> Drain<'_, V> {
Drain(self.0.drain(range), PhantomData)
}
/// Return an iterator over the keys of the map, in their order.
///
/// Equivalent to [`IndexMap::keys`].
pub fn keys(&self) -> Keys<'_, V> {
Keys(self.0.keys(), PhantomData)
}
/// Return an owning iterator over the keys of the map, in their order.
///
/// Equivalent to [`IndexMap::into_keys`].
pub fn into_keys(self) -> IntoKeys<V> {
IntoKeys(self.0.into_keys(), PhantomData)
}
}
impl<V> Default for EntityIndexMap<V> {
fn default() -> Self {
Self(Default::default())
}
}
impl<V> Deref for EntityIndexMap<V> {
type Target = IndexMap<Entity, V, EntityHash>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<V> DerefMut for EntityIndexMap<V> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<'a, V: Copy> Extend<(&'a Entity, &'a V)> for EntityIndexMap<V> {
fn extend<T: IntoIterator<Item = (&'a Entity, &'a V)>>(&mut self, iter: T) {
self.0.extend(iter);
}
}
impl<V> Extend<(Entity, V)> for EntityIndexMap<V> {
fn extend<T: IntoIterator<Item = (Entity, V)>>(&mut self, iter: T) {
self.0.extend(iter);
}
}
impl<V, const N: usize> From<[(Entity, V); N]> for EntityIndexMap<V> {
fn from(value: [(Entity, V); N]) -> Self {
Self(IndexMap::from_iter(value))
}
}
impl<V> FromIterator<(Entity, V)> for EntityIndexMap<V> {
fn from_iter<I: IntoIterator<Item = (Entity, V)>>(iterable: I) -> Self {
Self(IndexMap::from_iter(iterable))
}
}
impl<V, Q: EntityEquivalent + ?Sized> Index<&Q> for EntityIndexMap<V> {
type Output = V;
fn index(&self, key: &Q) -> &V {
self.0.index(&key.entity())
}
}
impl<V> Index<(Bound<usize>, Bound<usize>)> for EntityIndexMap<V> {
type Output = Slice<V>;
fn index(&self, key: (Bound<usize>, Bound<usize>)) -> &Self::Output {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<V> Index<Range<usize>> for EntityIndexMap<V> {
type Output = Slice<V>;
fn index(&self, key: Range<usize>) -> &Self::Output {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<V> Index<RangeFrom<usize>> for EntityIndexMap<V> {
type Output = Slice<V>;
fn index(&self, key: RangeFrom<usize>) -> &Self::Output {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<V> Index<RangeFull> for EntityIndexMap<V> {
type Output = Slice<V>;
fn index(&self, key: RangeFull) -> &Self::Output {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<V> Index<RangeInclusive<usize>> for EntityIndexMap<V> {
type Output = Slice<V>;
fn index(&self, key: RangeInclusive<usize>) -> &Self::Output {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<V> Index<RangeTo<usize>> for EntityIndexMap<V> {
type Output = Slice<V>;
fn index(&self, key: RangeTo<usize>) -> &Self::Output {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<V> Index<RangeToInclusive<usize>> for EntityIndexMap<V> {
type Output = Slice<V>;
fn index(&self, key: RangeToInclusive<usize>) -> &Self::Output {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<V> Index<usize> for EntityIndexMap<V> {
type Output = V;
fn index(&self, key: usize) -> &V {
self.0.index(key)
}
}
impl<V, Q: EntityEquivalent + ?Sized> IndexMut<&Q> for EntityIndexMap<V> {
fn index_mut(&mut self, key: &Q) -> &mut V {
self.0.index_mut(&key.entity())
}
}
impl<V> IndexMut<(Bound<usize>, Bound<usize>)> for EntityIndexMap<V> {
fn index_mut(&mut self, key: (Bound<usize>, Bound<usize>)) -> &mut Self::Output {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked_mut(self.0.index_mut(key)) }
}
}
impl<V> IndexMut<Range<usize>> for EntityIndexMap<V> {
fn index_mut(&mut self, key: Range<usize>) -> &mut Self::Output {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked_mut(self.0.index_mut(key)) }
}
}
impl<V> IndexMut<RangeFrom<usize>> for EntityIndexMap<V> {
fn index_mut(&mut self, key: RangeFrom<usize>) -> &mut Self::Output {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked_mut(self.0.index_mut(key)) }
}
}
impl<V> IndexMut<RangeFull> for EntityIndexMap<V> {
fn index_mut(&mut self, key: RangeFull) -> &mut Self::Output {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked_mut(self.0.index_mut(key)) }
}
}
impl<V> IndexMut<RangeInclusive<usize>> for EntityIndexMap<V> {
fn index_mut(&mut self, key: RangeInclusive<usize>) -> &mut Self::Output {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked_mut(self.0.index_mut(key)) }
}
}
impl<V> IndexMut<RangeTo<usize>> for EntityIndexMap<V> {
fn index_mut(&mut self, key: RangeTo<usize>) -> &mut Self::Output {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked_mut(self.0.index_mut(key)) }
}
}
impl<V> IndexMut<RangeToInclusive<usize>> for EntityIndexMap<V> {
fn index_mut(&mut self, key: RangeToInclusive<usize>) -> &mut Self::Output {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked_mut(self.0.index_mut(key)) }
}
}
impl<V> IndexMut<usize> for EntityIndexMap<V> {
fn index_mut(&mut self, key: usize) -> &mut V {
self.0.index_mut(key)
}
}
impl<'a, V> IntoIterator for &'a EntityIndexMap<V> {
type Item = (&'a Entity, &'a V);
type IntoIter = Iter<'a, V>;
fn into_iter(self) -> Self::IntoIter {
Iter(self.0.iter(), PhantomData)
}
}
impl<'a, V> IntoIterator for &'a mut EntityIndexMap<V> {
type Item = (&'a Entity, &'a mut V);
type IntoIter = IterMut<'a, V>;
fn into_iter(self) -> Self::IntoIter {
IterMut(self.0.iter_mut(), PhantomData)
}
}
impl<V> IntoIterator for EntityIndexMap<V> {
type Item = (Entity, V);
type IntoIter = IntoIter<V>;
fn into_iter(self) -> Self::IntoIter {
IntoIter(self.0.into_iter(), PhantomData)
}
}
impl<V1, V2, S2> PartialEq<IndexMap<Entity, V2, S2>> for EntityIndexMap<V1>
where
V1: PartialEq<V2>,
S2: BuildHasher,
{
fn eq(&self, other: &IndexMap<Entity, V2, S2>) -> bool {
self.0.eq(other)
}
}
impl<V1, V2> PartialEq<EntityIndexMap<V2>> for EntityIndexMap<V1>
where
V1: PartialEq<V2>,
{
fn eq(&self, other: &EntityIndexMap<V2>) -> bool {
self.0.eq(other)
}
}
impl<V: Eq> Eq for EntityIndexMap<V> {}
/// A dynamically-sized slice of key-value pairs in an [`EntityIndexMap`].
///
/// Equivalent to an [`indexmap::map::Slice<V>`] whose source [`IndexMap`]
/// uses [`EntityHash`].
#[repr(transparent)]
pub struct Slice<V, S = EntityHash>(PhantomData<S>, map::Slice<Entity, V>);
impl<V> Slice<V> {
/// Returns an empty slice.
///
/// Equivalent to [`map::Slice::new`].
pub const fn new<'a>() -> &'a Self {
// SAFETY: The source slice is empty.
unsafe { Self::from_slice_unchecked(map::Slice::new()) }
}
/// Returns an empty mutable slice.
///
/// Equivalent to [`map::Slice::new_mut`].
pub fn new_mut<'a>() -> &'a mut Self {
// SAFETY: The source slice is empty.
unsafe { Self::from_slice_unchecked_mut(map::Slice::new_mut()) }
}
/// Constructs a [`entity::index_map::Slice`] from a [`indexmap::map::Slice`] unsafely.
///
/// # Safety
///
/// `slice` must stem from an [`IndexMap`] using [`EntityHash`].
///
/// [`entity::index_map::Slice`]: `crate::entity::index_map::Slice`
pub const unsafe fn from_slice_unchecked(slice: &map::Slice<Entity, V>) -> &Self {
// SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
unsafe { &*(ptr::from_ref(slice) as *const Self) }
}
/// Constructs a [`entity::index_map::Slice`] from a [`indexmap::map::Slice`] unsafely.
///
/// # Safety
///
/// `slice` must stem from an [`IndexMap`] using [`EntityHash`].
///
/// [`entity::index_map::Slice`]: `crate::entity::index_map::Slice`
pub const unsafe fn from_slice_unchecked_mut(slice: &mut map::Slice<Entity, V>) -> &mut Self {
// SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
unsafe { &mut *(ptr::from_mut(slice) as *mut Self) }
}
/// Casts `self` to the inner slice.
pub const fn as_inner(&self) -> &map::Slice<Entity, V> {
&self.1
}
/// Constructs a boxed [`entity::index_map::Slice`] from a boxed [`indexmap::map::Slice`] unsafely.
///
/// # Safety
///
/// `slice` must stem from an [`IndexMap`] using [`EntityHash`].
///
/// [`entity::index_map::Slice`]: `crate::entity::index_map::Slice`
pub unsafe fn from_boxed_slice_unchecked(slice: Box<map::Slice<Entity, V>>) -> Box<Self> {
// SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
unsafe { Box::from_raw(Box::into_raw(slice) as *mut Self) }
}
/// Casts a reference to `self` to the inner slice.
#[expect(
clippy::borrowed_box,
reason = "We wish to access the Box API of the inner type, without consuming it."
)]
pub fn as_boxed_inner(self: &Box<Self>) -> &Box<map::Slice<Entity, V>> {
// SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
unsafe { &*(ptr::from_ref(self).cast::<Box<map::Slice<Entity, V>>>()) }
}
/// Casts `self` to the inner slice.
pub fn into_boxed_inner(self: Box<Self>) -> Box<map::Slice<Entity, V>> {
// SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
unsafe { Box::from_raw(Box::into_raw(self) as *mut map::Slice<Entity, V>) }
}
/// Get a key-value pair by index, with mutable access to the value.
///
/// Equivalent to [`map::Slice::get_index_mut`].
pub fn get_index_mut(&mut self, index: usize) -> Option<(&Entity, &mut V)> {
self.1.get_index_mut(index)
}
/// Returns a slice of key-value pairs in the given range of indices.
///
/// Equivalent to [`map::Slice::get_range`].
pub fn get_range<R: RangeBounds<usize>>(&self, range: R) -> Option<&Self> {
self.1.get_range(range).map(|slice|
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(slice) })
}
/// Returns a mutable slice of key-value pairs in the given range of indices.
///
/// Equivalent to [`map::Slice::get_range_mut`].
pub fn get_range_mut<R: RangeBounds<usize>>(&mut self, range: R) -> Option<&mut Self> {
self.1.get_range_mut(range).map(|slice|
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked_mut(slice) })
}
/// Get the first key-value pair, with mutable access to the value.
///
/// Equivalent to [`map::Slice::first_mut`].
pub fn first_mut(&mut self) -> Option<(&Entity, &mut V)> {
self.1.first_mut()
}
/// Get the last key-value pair, with mutable access to the value.
///
/// Equivalent to [`map::Slice::last_mut`].
pub fn last_mut(&mut self) -> Option<(&Entity, &mut V)> {
self.1.last_mut()
}
/// Divides one slice into two at an index.
///
/// Equivalent to [`map::Slice::split_at`].
pub fn split_at(&self, index: usize) -> (&Self, &Self) {
let (slice_1, slice_2) = self.1.split_at(index);
// SAFETY: These are subslices of a valid slice.
unsafe {
(
Self::from_slice_unchecked(slice_1),
Self::from_slice_unchecked(slice_2),
)
}
}
/// Divides one mutable slice into two at an index.
///
/// Equivalent to [`map::Slice::split_at_mut`].
pub fn split_at_mut(&mut self, index: usize) -> (&mut Self, &mut Self) {
let (slice_1, slice_2) = self.1.split_at_mut(index);
// SAFETY: These are subslices of a valid slice.
unsafe {
(
Self::from_slice_unchecked_mut(slice_1),
Self::from_slice_unchecked_mut(slice_2),
)
}
}
/// Returns the first key-value pair and the rest of the slice,
/// or `None` if it is empty.
///
/// Equivalent to [`map::Slice::split_first`].
pub fn split_first(&self) -> Option<((&Entity, &V), &Self)> {
self.1.split_first().map(|(first, rest)| {
(
first,
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(rest) },
)
})
}
/// Returns the first key-value pair and the rest of the slice,
/// with mutable access to the value, or `None` if it is empty.
///
/// Equivalent to [`map::Slice::split_first_mut`].
pub fn split_first_mut(&mut self) -> Option<((&Entity, &mut V), &mut Self)> {
self.1.split_first_mut().map(|(first, rest)| {
(
first,
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked_mut(rest) },
)
})
}
/// Returns the last key-value pair and the rest of the slice,
/// or `None` if it is empty.
///
/// Equivalent to [`map::Slice::split_last`].
pub fn split_last(&self) -> Option<((&Entity, &V), &Self)> {
self.1.split_last().map(|(last, rest)| {
(
last,
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(rest) },
)
})
}
/// Returns the last key-value pair and the rest of the slice,
/// with mutable access to the value, or `None` if it is empty.
///
/// Equivalent to [`map::Slice::split_last_mut`].
pub fn split_last_mut(&mut self) -> Option<((&Entity, &mut V), &mut Self)> {
self.1.split_last_mut().map(|(last, rest)| {
(
last,
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked_mut(rest) },
)
})
}
/// Return an iterator over the key-value pairs of the map slice.
///
/// Equivalent to [`map::Slice::iter`].
pub fn iter(&self) -> Iter<'_, V> {
Iter(self.1.iter(), PhantomData)
}
/// Return an iterator over the key-value pairs of the map slice.
///
/// Equivalent to [`map::Slice::iter_mut`].
pub fn iter_mut(&mut self) -> IterMut<'_, V> {
IterMut(self.1.iter_mut(), PhantomData)
}
/// Return an iterator over the keys of the map slice.
///
/// Equivalent to [`map::Slice::keys`].
pub fn keys(&self) -> Keys<'_, V> {
Keys(self.1.keys(), PhantomData)
}
/// Return an owning iterator over the keys of the map slice.
///
/// Equivalent to [`map::Slice::into_keys`].
pub fn into_keys(self: Box<Self>) -> IntoKeys<V> {
IntoKeys(self.into_boxed_inner().into_keys(), PhantomData)
}
/// Return an iterator over mutable references to the values of the map slice.
///
/// Equivalent to [`map::Slice::values_mut`].
pub fn values_mut(&mut self) -> ValuesMut<'_, Entity, V> {
self.1.values_mut()
}
/// Return an owning iterator over the values of the map slice.
///
/// Equivalent to [`map::Slice::into_values`].
pub fn into_values(self: Box<Self>) -> IntoValues<Entity, V> {
self.into_boxed_inner().into_values()
}
}
impl<V> Deref for Slice<V> {
type Target = map::Slice<Entity, V>;
fn deref(&self) -> &Self::Target {
&self.1
}
}
impl<V: Debug> Debug for Slice<V> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("Slice")
.field(&self.0)
.field(&&self.1)
.finish()
}
}
impl<V: Clone> Clone for Box<Slice<V>> {
fn clone(&self) -> Self {
// SAFETY: This a clone of a valid slice.
unsafe { Slice::from_boxed_slice_unchecked(self.as_boxed_inner().clone()) }
}
}
impl<V> Default for &Slice<V> {
fn default() -> Self {
// SAFETY: The source slice is empty.
unsafe { Slice::from_slice_unchecked(<&map::Slice<Entity, V>>::default()) }
}
}
impl<V> Default for &mut Slice<V> {
fn default() -> Self {
// SAFETY: The source slice is empty.
unsafe { Slice::from_slice_unchecked_mut(<&mut map::Slice<Entity, V>>::default()) }
}
}
impl<V> Default for Box<Slice<V>> {
fn default() -> Self {
// SAFETY: The source slice is empty.
unsafe { Slice::from_boxed_slice_unchecked(<Box<map::Slice<Entity, V>>>::default()) }
}
}
impl<V: Copy> From<&Slice<V>> for Box<Slice<V>> {
fn from(value: &Slice<V>) -> Self {
// SAFETY: This slice is a copy of a valid slice.
unsafe { Slice::from_boxed_slice_unchecked(value.1.into()) }
}
}
impl<V: Hash> Hash for Slice<V> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.1.hash(state);
}
}
impl<'a, V> IntoIterator for &'a Slice<V> {
type Item = (&'a Entity, &'a V);
type IntoIter = Iter<'a, V>;
fn into_iter(self) -> Self::IntoIter {
Iter(self.1.iter(), PhantomData)
}
}
impl<'a, V> IntoIterator for &'a mut Slice<V> {
type Item = (&'a Entity, &'a mut V);
type IntoIter = IterMut<'a, V>;
fn into_iter(self) -> Self::IntoIter {
IterMut(self.1.iter_mut(), PhantomData)
}
}
impl<V> IntoIterator for Box<Slice<V>> {
type Item = (Entity, V);
type IntoIter = IntoIter<V>;
fn into_iter(self) -> Self::IntoIter {
IntoIter(self.into_boxed_inner().into_iter(), PhantomData)
}
}
impl<V: PartialOrd> PartialOrd for Slice<V> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.1.partial_cmp(&other.1)
}
}
impl<V: Ord> Ord for Slice<V> {
fn cmp(&self, other: &Self) -> Ordering {
self.1.cmp(other)
}
}
impl<V: PartialEq> PartialEq for Slice<V> {
fn eq(&self, other: &Self) -> bool {
self.1 == other.1
}
}
impl<V: Eq> Eq for Slice<V> {}
impl<V> Index<(Bound<usize>, Bound<usize>)> for Slice<V> {
type Output = Self;
fn index(&self, key: (Bound<usize>, Bound<usize>)) -> &Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(self.1.index(key)) }
}
}
impl<V> Index<Range<usize>> for Slice<V> {
type Output = Self;
fn index(&self, key: Range<usize>) -> &Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(self.1.index(key)) }
}
}
impl<V> Index<RangeFrom<usize>> for Slice<V> {
type Output = Self;
fn index(&self, key: RangeFrom<usize>) -> &Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(self.1.index(key)) }
}
}
impl<V> Index<RangeFull> for Slice<V> {
type Output = Self;
fn index(&self, key: RangeFull) -> &Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(self.1.index(key)) }
}
}
impl<V> Index<RangeInclusive<usize>> for Slice<V> {
type Output = Self;
fn index(&self, key: RangeInclusive<usize>) -> &Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(self.1.index(key)) }
}
}
impl<V> Index<RangeTo<usize>> for Slice<V> {
type Output = Self;
fn index(&self, key: RangeTo<usize>) -> &Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(self.1.index(key)) }
}
}
impl<V> Index<RangeToInclusive<usize>> for Slice<V> {
type Output = Self;
fn index(&self, key: RangeToInclusive<usize>) -> &Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(self.1.index(key)) }
}
}
impl<V> Index<usize> for Slice<V> {
type Output = V;
fn index(&self, key: usize) -> &V {
self.1.index(key)
}
}
impl<V> IndexMut<(Bound<usize>, Bound<usize>)> for Slice<V> {
fn index_mut(&mut self, key: (Bound<usize>, Bound<usize>)) -> &mut Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked_mut(self.1.index_mut(key)) }
}
}
impl<V> IndexMut<Range<usize>> for Slice<V> {
fn index_mut(&mut self, key: Range<usize>) -> &mut Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked_mut(self.1.index_mut(key)) }
}
}
impl<V> IndexMut<RangeFrom<usize>> for Slice<V> {
fn index_mut(&mut self, key: RangeFrom<usize>) -> &mut Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked_mut(self.1.index_mut(key)) }
}
}
impl<V> IndexMut<RangeFull> for Slice<V> {
fn index_mut(&mut self, key: RangeFull) -> &mut Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked_mut(self.1.index_mut(key)) }
}
}
impl<V> IndexMut<RangeInclusive<usize>> for Slice<V> {
fn index_mut(&mut self, key: RangeInclusive<usize>) -> &mut Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked_mut(self.1.index_mut(key)) }
}
}
impl<V> IndexMut<RangeTo<usize>> for Slice<V> {
fn index_mut(&mut self, key: RangeTo<usize>) -> &mut Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked_mut(self.1.index_mut(key)) }
}
}
impl<V> IndexMut<RangeToInclusive<usize>> for Slice<V> {
fn index_mut(&mut self, key: RangeToInclusive<usize>) -> &mut Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked_mut(self.1.index_mut(key)) }
}
}
impl<V> IndexMut<usize> for Slice<V> {
fn index_mut(&mut self, key: usize) -> &mut V {
self.1.index_mut(key)
}
}
/// An iterator over the entries of an [`EntityIndexMap`].
///
/// This `struct` is created by the [`EntityIndexMap::iter`] method.
/// See its documentation for more.
pub struct Iter<'a, V, S = EntityHash>(map::Iter<'a, Entity, V>, PhantomData<S>);
impl<'a, V> Iter<'a, V> {
/// Returns the inner [`Iter`](map::Iter).
pub fn into_inner(self) -> map::Iter<'a, Entity, V> {
self.0
}
/// Returns a slice of the remaining entries in the iterator.
///
/// Equivalent to [`map::Iter::as_slice`].
pub fn as_slice(&self) -> &Slice<V> {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.as_slice()) }
}
}
impl<'a, V> Deref for Iter<'a, V> {
type Target = map::Iter<'a, Entity, V>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a, V> Iterator for Iter<'a, V> {
type Item = (&'a Entity, &'a V);
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl<V> DoubleEndedIterator for Iter<'_, V> {
fn next_back(&mut self) -> Option<Self::Item> {
self.0.next_back()
}
}
impl<V> ExactSizeIterator for Iter<'_, V> {}
impl<V> FusedIterator for Iter<'_, V> {}
impl<V> Clone for Iter<'_, V> {
fn clone(&self) -> Self {
Self(self.0.clone(), PhantomData)
}
}
impl<V: Debug> Debug for Iter<'_, V> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("Iter").field(&self.0).field(&self.1).finish()
}
}
impl<V> Default for Iter<'_, V> {
fn default() -> Self {
Self(Default::default(), PhantomData)
}
}
/// A mutable iterator over the entries of an [`EntityIndexMap`].
///
/// This `struct` is created by the [`EntityIndexMap::iter_mut`] method.
/// See its documentation for more.
pub struct IterMut<'a, V, S = EntityHash>(map::IterMut<'a, Entity, V>, PhantomData<S>);
impl<'a, V> IterMut<'a, V> {
/// Returns the inner [`IterMut`](map::IterMut).
pub fn into_inner(self) -> map::IterMut<'a, Entity, V> {
self.0
}
/// Returns a slice of the remaining entries in the iterator.
///
/// Equivalent to [`map::IterMut::as_slice`].
pub fn as_slice(&self) -> &Slice<V> {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.as_slice()) }
}
/// Returns a mutable slice of the remaining entries in the iterator.
///
/// Equivalent to [`map::IterMut::into_slice`].
pub fn into_slice(self) -> &'a mut Slice<V> {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked_mut(self.0.into_slice()) }
}
}
impl<'a, V> Deref for IterMut<'a, V> {
type Target = map::IterMut<'a, Entity, V>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a, V> Iterator for IterMut<'a, V> {
type Item = (&'a Entity, &'a mut V);
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl<V> DoubleEndedIterator for IterMut<'_, V> {
fn next_back(&mut self) -> Option<Self::Item> {
self.0.next_back()
}
}
impl<V> ExactSizeIterator for IterMut<'_, V> {}
impl<V> FusedIterator for IterMut<'_, V> {}
impl<V: Debug> Debug for IterMut<'_, V> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("IterMut")
.field(&self.0)
.field(&self.1)
.finish()
}
}
impl<V> Default for IterMut<'_, V> {
fn default() -> Self {
Self(Default::default(), PhantomData)
}
}
/// An owning iterator over the entries of an [`IndexMap`].
///
/// This `struct` is created by the [`IndexMap::into_iter`] method
/// (provided by the [`IntoIterator`] trait). See its documentation for more.
pub struct IntoIter<V, S = EntityHash>(map::IntoIter<Entity, V>, PhantomData<S>);
impl<V> IntoIter<V> {
/// Returns the inner [`IntoIter`](map::IntoIter).
pub fn into_inner(self) -> map::IntoIter<Entity, V> {
self.0
}
/// Returns a slice of the remaining entries in the iterator.
///
/// Equivalent to [`map::IntoIter::as_slice`].
pub fn as_slice(&self) -> &Slice<V> {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.as_slice()) }
}
/// Returns a mutable slice of the remaining entries in the iterator.
///
/// Equivalent to [`map::IntoIter::as_mut_slice`].
pub fn as_mut_slice(&mut self) -> &mut Slice<V> {
// SAFETY: The source IndexMap uses EntityHash.
unsafe { Slice::from_slice_unchecked_mut(self.0.as_mut_slice()) }
}
}
impl<V> Deref for IntoIter<V> {
type Target = map::IntoIter<Entity, V>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<V> Iterator for IntoIter<V> {
type Item = (Entity, V);
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl<V> DoubleEndedIterator for IntoIter<V> {
fn next_back(&mut self) -> Option<Self::Item> {
self.0.next_back()
}
}
impl<V> ExactSizeIterator for IntoIter<V> {}
impl<V> FusedIterator for IntoIter<V> {}
impl<V: Clone> Clone for IntoIter<V> {
fn clone(&self) -> Self {
Self(self.0.clone(), PhantomData)
}
}
impl<V: Debug> Debug for IntoIter<V> {
| 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/entity_set.rs | crates/bevy_ecs/src/entity/entity_set.rs | use alloc::{
boxed::Box,
collections::{btree_map, btree_set},
rc::Rc,
};
use bevy_platform::collections::HashSet;
use core::{
array,
fmt::{Debug, Formatter},
hash::{BuildHasher, Hash},
iter::{self, FusedIterator},
option, result,
};
use super::{Entity, UniqueEntityEquivalentSlice};
use bevy_platform::sync::Arc;
/// A trait for types that contain an [`Entity`].
///
/// This trait behaves similarly to `Borrow<Entity>`, but yielding `Entity` directly.
///
/// It should only be implemented when:
/// - Retrieving the [`Entity`] is a simple operation.
/// - The [`Entity`] contained by the type is unambiguous.
pub trait ContainsEntity {
/// Returns the contained entity.
fn entity(&self) -> Entity;
}
/// A trait for types that represent an [`Entity`].
///
/// Comparison trait behavior between an [`EntityEquivalent`] type and its underlying entity will match.
/// This property includes [`PartialEq`], [`Eq`], [`PartialOrd`], [`Ord`] and [`Hash`],
/// and remains even after [`Clone`] and/or [`Borrow`] calls.
///
/// # Safety
/// Any [`PartialEq`], [`Eq`], [`PartialOrd`], and [`Ord`] impls must evaluate the same for `Self` and
/// its underlying entity.
/// `x.entity() == y.entity()` must be equivalent to `x == y`.
///
/// The above equivalence must also hold through and between calls to any [`Clone`] and
/// [`Borrow`]/[`BorrowMut`] impls in place of [`entity()`].
///
/// The result of [`entity()`] must be unaffected by any interior mutability.
///
/// The aforementioned properties imply determinism in both [`entity()`] calls
/// and comparison trait behavior.
///
/// All [`Hash`] impls except that for [`Entity`] must delegate to the [`Hash`] impl of
/// another [`EntityEquivalent`] type. All conversions to the delegatee within the [`Hash`] impl must
/// follow [`entity()`] equivalence.
///
/// It should be noted that [`Hash`] is *not* a comparison trait, and with [`Hash::hash`] being forcibly
/// generic over all [`Hasher`]s, **cannot** guarantee determinism or uniqueness of any final hash values
/// on its own.
/// To obtain hash values forming the same total order as [`Entity`], any [`Hasher`] used must be
/// deterministic and concerning [`Entity`], collisionless.
/// Standard library hash collections handle collisions with an [`Eq`] fallback, but do not account for
/// determinism when [`BuildHasher`] is unspecified,.
///
/// [`Hash`]: core::hash::Hash
/// [`Hasher`]: core::hash::Hasher
/// [`Borrow`]: core::borrow::Borrow
/// [`BorrowMut`]: core::borrow::BorrowMut
/// [`entity()`]: ContainsEntity::entity
pub unsafe trait EntityEquivalent: ContainsEntity + Eq {}
impl ContainsEntity for Entity {
fn entity(&self) -> Entity {
*self
}
}
// SAFETY:
// The trait implementations of Entity are correct and deterministic.
unsafe impl EntityEquivalent for Entity {}
impl<T: ContainsEntity> ContainsEntity for &T {
fn entity(&self) -> Entity {
(**self).entity()
}
}
// SAFETY:
// `&T` delegates `PartialEq`, `Eq`, `PartialOrd`, `Ord`, and `Hash` to T.
// `Clone` and `Borrow` maintain equality.
// `&T` is `Freeze`.
unsafe impl<T: EntityEquivalent> EntityEquivalent for &T {}
impl<T: ContainsEntity> ContainsEntity for &mut T {
fn entity(&self) -> Entity {
(**self).entity()
}
}
// SAFETY:
// `&mut T` delegates `PartialEq`, `Eq`, `PartialOrd`, `Ord`, and `Hash` to T.
// `Borrow` and `BorrowMut` maintain equality.
// `&mut T` is `Freeze`.
unsafe impl<T: EntityEquivalent> EntityEquivalent for &mut T {}
impl<T: ContainsEntity> ContainsEntity for Box<T> {
fn entity(&self) -> Entity {
(**self).entity()
}
}
// SAFETY:
// `Box<T>` delegates `PartialEq`, `Eq`, `PartialOrd`, `Ord`, and `Hash` to T.
// `Clone`, `Borrow` and `BorrowMut` maintain equality.
// `Box<T>` is `Freeze`.
unsafe impl<T: EntityEquivalent> EntityEquivalent for Box<T> {}
impl<T: ContainsEntity> ContainsEntity for Rc<T> {
fn entity(&self) -> Entity {
(**self).entity()
}
}
// SAFETY:
// `Rc<T>` delegates `PartialEq`, `Eq`, `PartialOrd`, `Ord`, and `Hash` to T.
// `Clone`, `Borrow` and `BorrowMut` maintain equality.
// `Rc<T>` is `Freeze`.
unsafe impl<T: EntityEquivalent> EntityEquivalent for Rc<T> {}
impl<T: ContainsEntity> ContainsEntity for Arc<T> {
fn entity(&self) -> Entity {
(**self).entity()
}
}
// SAFETY:
// `Arc<T>` delegates `PartialEq`, `Eq`, `PartialOrd`, `Ord`, and `Hash` to T.
// `Clone`, `Borrow` and `BorrowMut` maintain equality.
// `Arc<T>` is `Freeze`.
unsafe impl<T: EntityEquivalent> EntityEquivalent for Arc<T> {}
/// A set of unique entities.
///
/// Any element returned by [`Self::IntoIter`] will compare non-equal to every other element in the iterator.
/// As a consequence, [`into_iter()`] on `EntitySet` will always produce another `EntitySet`.
///
/// Implementing this trait allows for unique query iteration over a list of entities.
/// See [`iter_many_unique`] and [`iter_many_unique_mut`]
///
/// Note that there is no guarantee of the [`IntoIterator`] impl being deterministic,
/// it might return different iterators when called multiple times.
/// Neither is there a guarantee that the comparison trait impls of `EntitySet` match that
/// of the respective [`EntitySetIterator`] (or of a [`Vec`] collected from its elements)
///
/// [`Self::IntoIter`]: IntoIterator::IntoIter
/// [`into_iter()`]: IntoIterator::into_iter
/// [`iter_many_unique`]: crate::system::Query::iter_many_unique
/// [`iter_many_unique_mut`]: crate::system::Query::iter_many_unique_mut
/// [`Vec`]: alloc::vec::Vec
pub trait EntitySet: IntoIterator<IntoIter: EntitySetIterator> {}
impl<T: IntoIterator<IntoIter: EntitySetIterator>> EntitySet for T {}
/// An iterator over a set of unique entities.
///
/// Every `EntitySetIterator` is also [`EntitySet`].
///
/// # Safety
///
/// `x != y` must hold for any 2 elements returned by the iterator.
/// This is always true for iterators that cannot return more than one element.
pub unsafe trait EntitySetIterator: Iterator<Item: EntityEquivalent> {
/// Transforms an `EntitySetIterator` into a collection.
///
/// This is a specialized form of [`collect`], for collections which benefit from the uniqueness guarantee.
/// When present, this should always be preferred over [`collect`].
///
/// [`collect`]: Iterator::collect
// FIXME: When subtrait item shadowing stabilizes, this should be renamed and shadow `Iterator::collect`
fn collect_set<B: FromEntitySetIterator<Self::Item>>(self) -> B
where
Self: Sized,
{
FromEntitySetIterator::from_entity_set_iter(self)
}
}
// SAFETY:
// A correct `BTreeMap` contains only unique keys.
// EntityEquivalent guarantees a trustworthy Ord impl for T, and thus a correct `BTreeMap`.
unsafe impl<K: EntityEquivalent, V> EntitySetIterator for btree_map::Keys<'_, K, V> {}
// SAFETY:
// A correct `BTreeMap` contains only unique keys.
// EntityEquivalent guarantees a trustworthy Ord impl for T, and thus a correct `BTreeMap`.
unsafe impl<K: EntityEquivalent, V> EntitySetIterator for btree_map::IntoKeys<K, V> {}
// SAFETY:
// A correct `BTreeSet` contains only unique elements.
// EntityEquivalent guarantees a trustworthy Ord impl for T, and thus a correct `BTreeSet`.
// The sub-range maintains uniqueness.
unsafe impl<T: EntityEquivalent> EntitySetIterator for btree_set::Range<'_, T> {}
// SAFETY:
// A correct `BTreeSet` contains only unique elements.
// EntityEquivalent guarantees a trustworthy Ord impl for T, and thus a correct `BTreeSet`.
// The "intersection" operation maintains uniqueness.
unsafe impl<T: EntityEquivalent + Ord> EntitySetIterator for btree_set::Intersection<'_, T> {}
// SAFETY:
// A correct `BTreeSet` contains only unique elements.
// EntityEquivalent guarantees a trustworthy Ord impl for T, and thus a correct `BTreeSet`.
// The "union" operation maintains uniqueness.
unsafe impl<T: EntityEquivalent + Ord> EntitySetIterator for btree_set::Union<'_, T> {}
// SAFETY:
// A correct `BTreeSet` contains only unique elements.
// EntityEquivalent guarantees a trustworthy Ord impl for T, and thus a correct `BTreeSet`.
// The "difference" operation maintains uniqueness.
unsafe impl<T: EntityEquivalent + Ord> EntitySetIterator for btree_set::Difference<'_, T> {}
// SAFETY:
// A correct `BTreeSet` contains only unique elements.
// EntityEquivalent guarantees a trustworthy Ord impl for T, and thus a correct `BTreeSet`.
// The "symmetric difference" operation maintains uniqueness.
unsafe impl<T: EntityEquivalent + Ord> EntitySetIterator for btree_set::SymmetricDifference<'_, T> {}
// SAFETY:
// A correct `BTreeSet` contains only unique elements.
// EntityEquivalent guarantees a trustworthy Ord impl for T, and thus a correct `BTreeSet`.
unsafe impl<T: EntityEquivalent> EntitySetIterator for btree_set::Iter<'_, T> {}
// SAFETY:
// A correct `BTreeSet` contains only unique elements.
// EntityEquivalent guarantees a trustworthy Ord impl for T, and thus a correct `BTreeSet`.
unsafe impl<T: EntityEquivalent> EntitySetIterator for btree_set::IntoIter<T> {}
// SAFETY: This iterator only returns one element.
unsafe impl<T: EntityEquivalent> EntitySetIterator for option::Iter<'_, T> {}
// SAFETY: This iterator only returns one element.
// unsafe impl<T: EntityEquivalent> EntitySetIterator for option::IterMut<'_, T> {}
// SAFETY: This iterator only returns one element.
unsafe impl<T: EntityEquivalent> EntitySetIterator for option::IntoIter<T> {}
// SAFETY: This iterator only returns one element.
unsafe impl<T: EntityEquivalent> EntitySetIterator for result::Iter<'_, T> {}
// SAFETY: This iterator only returns one element.
// unsafe impl<T: EntityEquivalent> EntitySetIterator for result::IterMut<'_, T> {}
// SAFETY: This iterator only returns one element.
unsafe impl<T: EntityEquivalent> EntitySetIterator for result::IntoIter<T> {}
// SAFETY: This iterator only returns one element.
unsafe impl<T: EntityEquivalent> EntitySetIterator for array::IntoIter<T, 1> {}
// SAFETY: This iterator does not return any elements.
unsafe impl<T: EntityEquivalent> EntitySetIterator for array::IntoIter<T, 0> {}
// SAFETY: This iterator only returns one element.
unsafe impl<T: EntityEquivalent, F: FnOnce() -> T> EntitySetIterator for iter::OnceWith<F> {}
// SAFETY: This iterator only returns one element.
unsafe impl<T: EntityEquivalent> EntitySetIterator for iter::Once<T> {}
// SAFETY: This iterator does not return any elements.
unsafe impl<T: EntityEquivalent> EntitySetIterator for iter::Empty<T> {}
// SAFETY: Taking a mutable reference of an iterator has no effect on its elements.
unsafe impl<I: EntitySetIterator + ?Sized> EntitySetIterator for &mut I {}
// SAFETY: Boxing an iterator has no effect on its elements.
unsafe impl<I: EntitySetIterator + ?Sized> EntitySetIterator for Box<I> {}
// SAFETY: EntityEquivalent ensures that Copy does not affect equality, via its restrictions on Clone.
unsafe impl<'a, T: 'a + EntityEquivalent + Copy, I: EntitySetIterator<Item = &'a T>>
EntitySetIterator for iter::Copied<I>
{
}
// SAFETY: EntityEquivalent ensures that Clone does not affect equality.
unsafe impl<'a, T: 'a + EntityEquivalent + Clone, I: EntitySetIterator<Item = &'a T>>
EntitySetIterator for iter::Cloned<I>
{
}
// SAFETY: Discarding elements maintains uniqueness.
unsafe impl<I: EntitySetIterator, P: FnMut(&<I as Iterator>::Item) -> bool> EntitySetIterator
for iter::Filter<I, P>
{
}
// SAFETY: Yielding only `None` after yielding it once can only remove elements, which maintains uniqueness.
unsafe impl<I: EntitySetIterator> EntitySetIterator for iter::Fuse<I> {}
// SAFETY:
// Obtaining immutable references the elements of an iterator does not affect uniqueness.
// EntityEquivalent ensures the lack of interior mutability.
unsafe impl<I: EntitySetIterator, F: FnMut(&<I as Iterator>::Item)> EntitySetIterator
for iter::Inspect<I, F>
{
}
// SAFETY: Reversing an iterator does not affect uniqueness.
unsafe impl<I: DoubleEndedIterator + EntitySetIterator> EntitySetIterator for iter::Rev<I> {}
// SAFETY: Discarding elements maintains uniqueness.
unsafe impl<I: EntitySetIterator> EntitySetIterator for iter::Skip<I> {}
// SAFETY: Discarding elements maintains uniqueness.
unsafe impl<I: EntitySetIterator, P: FnMut(&<I as Iterator>::Item) -> bool> EntitySetIterator
for iter::SkipWhile<I, P>
{
}
// SAFETY: Discarding elements maintains uniqueness.
unsafe impl<I: EntitySetIterator> EntitySetIterator for iter::Take<I> {}
// SAFETY: Discarding elements maintains uniqueness.
unsafe impl<I: EntitySetIterator, P: FnMut(&<I as Iterator>::Item) -> bool> EntitySetIterator
for iter::TakeWhile<I, P>
{
}
// SAFETY: Discarding elements maintains uniqueness.
unsafe impl<I: EntitySetIterator> EntitySetIterator for iter::StepBy<I> {}
/// Conversion from an `EntitySetIterator`.
///
/// Some collections, while they can be constructed from plain iterators,
/// benefit strongly from the additional uniqueness guarantee [`EntitySetIterator`] offers.
/// Mirroring [`Iterator::collect`]/[`FromIterator::from_iter`], [`EntitySetIterator::collect_set`] and
/// `FromEntitySetIterator::from_entity_set_iter` can be used for construction.
///
/// See also: [`EntitySet`].
// FIXME: When subtrait item shadowing stabilizes, this should be renamed and shadow `FromIterator::from_iter`
pub trait FromEntitySetIterator<A: EntityEquivalent>: FromIterator<A> {
/// Creates a value from an [`EntitySetIterator`].
fn from_entity_set_iter<T: EntitySet<Item = A>>(set_iter: T) -> Self;
}
impl<T: EntityEquivalent + Hash, S: BuildHasher + Default> FromEntitySetIterator<T>
for HashSet<T, S>
{
fn from_entity_set_iter<I: EntitySet<Item = T>>(set_iter: I) -> Self {
let iter = set_iter.into_iter();
let set = HashSet::<T, S>::with_capacity_and_hasher(iter.size_hint().0, S::default());
iter.fold(set, |mut set, e| {
// SAFETY: Every element in self is unique.
unsafe {
set.insert_unique_unchecked(e);
}
set
})
}
}
/// An iterator that yields unique entities.
///
/// This wrapper can provide an [`EntitySetIterator`] implementation when an instance of `I` is known to uphold uniqueness.
pub struct UniqueEntityIter<I: Iterator<Item: EntityEquivalent>> {
iter: I,
}
impl<I: EntitySetIterator> UniqueEntityIter<I> {
/// Constructs a `UniqueEntityIter` from an [`EntitySetIterator`].
pub fn from_entity_set_iterator<S>(iter: I) -> Self {
Self { iter }
}
}
impl<I: Iterator<Item: EntityEquivalent>> UniqueEntityIter<I> {
/// Constructs a [`UniqueEntityIter`] from an iterator unsafely.
///
/// # Safety
/// `iter` must only yield unique elements.
/// As in, the resulting iterator must adhere to the safety contract of [`EntitySetIterator`].
pub unsafe fn from_iterator_unchecked(iter: I) -> Self {
Self { iter }
}
/// Returns the inner `I`.
pub fn into_inner(self) -> I {
self.iter
}
/// Returns a reference to the inner `I`.
pub fn as_inner(&self) -> &I {
&self.iter
}
/// Returns a mutable reference to the inner `I`.
///
/// # Safety
///
/// `self` must always contain an iterator that yields unique elements,
/// even while this reference is live.
pub unsafe fn as_mut_inner(&mut self) -> &mut I {
&mut self.iter
}
}
impl<I: Iterator<Item: EntityEquivalent>> Iterator for UniqueEntityIter<I> {
type Item = I::Item;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<I: ExactSizeIterator<Item: EntityEquivalent>> ExactSizeIterator for UniqueEntityIter<I> {}
impl<I: DoubleEndedIterator<Item: EntityEquivalent>> DoubleEndedIterator for UniqueEntityIter<I> {
fn next_back(&mut self) -> Option<Self::Item> {
self.iter.next_back()
}
}
impl<I: FusedIterator<Item: EntityEquivalent>> FusedIterator for UniqueEntityIter<I> {}
// SAFETY: The underlying iterator is ensured to only return unique elements by its construction.
unsafe impl<I: Iterator<Item: EntityEquivalent>> EntitySetIterator for UniqueEntityIter<I> {}
impl<T, I: Iterator<Item: EntityEquivalent> + AsRef<[T]>> AsRef<[T]> for UniqueEntityIter<I> {
fn as_ref(&self) -> &[T] {
self.iter.as_ref()
}
}
impl<T: EntityEquivalent, I: Iterator<Item: EntityEquivalent> + AsRef<[T]>>
AsRef<UniqueEntityEquivalentSlice<T>> for UniqueEntityIter<I>
{
fn as_ref(&self) -> &UniqueEntityEquivalentSlice<T> {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.iter.as_ref()) }
}
}
impl<T: EntityEquivalent, I: Iterator<Item: EntityEquivalent> + AsMut<[T]>>
AsMut<UniqueEntityEquivalentSlice<T>> for UniqueEntityIter<I>
{
fn as_mut(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.iter.as_mut()) }
}
}
// Default does not guarantee uniqueness, meaning `I` needs to be EntitySetIterator.
impl<I: EntitySetIterator + Default> Default for UniqueEntityIter<I> {
fn default() -> Self {
Self {
iter: Default::default(),
}
}
}
// Clone does not guarantee to maintain uniqueness, meaning `I` needs to be EntitySetIterator.
impl<I: EntitySetIterator + Clone> Clone for UniqueEntityIter<I> {
fn clone(&self) -> Self {
Self {
iter: self.iter.clone(),
}
}
}
impl<I: Iterator<Item: EntityEquivalent> + Debug> Debug for UniqueEntityIter<I> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
f.debug_struct("UniqueEntityIter")
.field("iter", &self.iter)
.finish()
}
}
#[cfg(test)]
mod tests {
use alloc::{vec, vec::Vec};
use crate::prelude::{Schedule, World};
use crate::component::Component;
use crate::entity::Entity;
use crate::query::{QueryState, With};
use crate::system::Query;
use crate::world::Mut;
use super::UniqueEntityIter;
#[derive(Component, Clone)]
pub struct Thing;
#[expect(
clippy::iter_skip_zero,
reason = "The `skip(0)` is used to ensure that the `Skip` iterator implements `EntitySet`, which is needed to pass the iterator as the `entities` parameter."
)]
#[test]
fn preserving_uniqueness() {
let mut world = World::new();
let mut query = QueryState::<&mut Thing>::new(&mut world);
let spawn_batch: Vec<Entity> = world.spawn_batch(vec![Thing; 1000]).collect();
// SAFETY: SpawnBatchIter is `EntitySetIterator`,
let mut unique_entity_iter =
unsafe { UniqueEntityIter::from_iterator_unchecked(spawn_batch.iter()) };
let entity_set = unique_entity_iter
.by_ref()
.filter(|_| true)
.fuse()
.inspect(|_| ())
.rev()
.skip(0)
.skip_while(|_| false)
.take(1000)
.take_while(|_| true)
.step_by(2)
.cloned();
// With `iter_many_mut` collecting is not possible, because you need to drop each `Mut`/`&mut` before the next is retrieved.
let _results: Vec<Mut<Thing>> =
query.iter_many_unique_mut(&mut world, entity_set).collect();
}
#[test]
fn nesting_queries() {
let mut world = World::new();
world.spawn_batch(vec![Thing; 1000]);
pub fn system(
mut thing_entities: Query<Entity, With<Thing>>,
mut things: Query<&mut Thing>,
) {
things.iter_many_unique(thing_entities.iter());
things.iter_many_unique_mut(thing_entities.iter_mut());
}
let mut schedule = Schedule::default();
schedule.add_systems(system);
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/entity/unique_vec.rs | crates/bevy_ecs/src/entity/unique_vec.rs | //! A wrapper around entity [`Vec`]s with a uniqueness invariant.
use core::{
borrow::{Borrow, BorrowMut},
mem::MaybeUninit,
ops::{
Bound, Deref, DerefMut, Index, IndexMut, Range, RangeBounds, RangeFrom, RangeFull,
RangeInclusive, RangeTo, RangeToInclusive,
},
};
use alloc::{
borrow::{Cow, ToOwned},
boxed::Box,
collections::{BTreeSet, BinaryHeap, TryReserveError, VecDeque},
rc::Rc,
vec::{self, Vec},
};
use bevy_platform::sync::Arc;
use super::{
unique_slice::{self, UniqueEntityEquivalentSlice},
Entity, EntityEquivalent, EntitySet, FromEntitySetIterator, UniqueEntityEquivalentArray,
UniqueEntityIter,
};
/// A `Vec` that contains only unique entities.
///
/// "Unique" means that `x != y` holds for any 2 entities in this collection.
/// This is always true when less than 2 entities are present.
///
/// This type is best obtained by its `FromEntitySetIterator` impl, via either
/// `EntityIterator::collect_set` or `UniqueEntityEquivalentVec::from_entity_iter`.
///
/// While this type can be constructed via `Iterator::collect`, doing so is inefficient,
/// and not recommended.
///
/// When `T` is [`Entity`], use the [`UniqueEntityVec`] alias.
#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct UniqueEntityEquivalentVec<T: EntityEquivalent>(Vec<T>);
/// A `Vec` that contains only unique [`Entity`].
///
/// This is the default case of a [`UniqueEntityEquivalentVec`].
pub type UniqueEntityVec = UniqueEntityEquivalentVec<Entity>;
impl<T: EntityEquivalent> UniqueEntityEquivalentVec<T> {
/// Constructs a new, empty `UniqueEntityEquivalentVec<T>`.
///
/// Equivalent to [`Vec::new`].
pub const fn new() -> Self {
Self(Vec::new())
}
/// Constructs a new, empty `UniqueEntityEquivalentVec<T>` with at least the specified capacity.
///
/// Equivalent to [`Vec::with_capacity`]
pub fn with_capacity(capacity: usize) -> Self {
Self(Vec::with_capacity(capacity))
}
/// Creates a `UniqueEntityEquivalentVec<T>` directly from a pointer, a length, and a capacity.
///
/// Equivalent to [`Vec::from_raw_parts`].
///
/// # Safety
///
/// It must be safe to call [`Vec::from_raw_parts`] with these inputs,
/// and the resulting [`Vec`] must only contain unique elements.
pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
// SAFETY: Caller ensures it's safe to call `Vec::from_raw_parts`
Self(unsafe { Vec::from_raw_parts(ptr, length, capacity) })
}
/// Constructs a `UniqueEntityEquivalentVec` from a [`Vec<T>`] unsafely.
///
/// # Safety
///
/// `vec` must contain only unique elements.
pub unsafe fn from_vec_unchecked(vec: Vec<T>) -> Self {
Self(vec)
}
/// Returns the inner [`Vec<T>`].
pub fn into_inner(self) -> Vec<T> {
self.0
}
/// Returns a reference to the inner [`Vec<T>`].
pub fn as_vec(&self) -> &Vec<T> {
&self.0
}
/// Returns a mutable reference to the inner [`Vec<T>`].
///
/// # Safety
///
/// The elements of this `Vec` must always remain unique, even while
/// this mutable reference is live.
pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<T> {
&mut self.0
}
/// Returns the total number of elements the vector can hold without
/// reallocating.
///
/// Equivalent to [`Vec::capacity`].
pub fn capacity(&self) -> usize {
self.0.capacity()
}
/// Reserves capacity for at least `additional` more elements to be inserted
/// in the given `Vec<T>`.
///
/// Equivalent to [`Vec::reserve`].
pub fn reserve(&mut self, additional: usize) {
self.0.reserve(additional);
}
/// Reserves the minimum capacity for at least `additional` more elements to
/// be inserted in the given `UniqueEntityEquivalentVec<T>`.
///
/// Equivalent to [`Vec::reserve_exact`].
pub fn reserve_exact(&mut self, additional: usize) {
self.0.reserve_exact(additional);
}
/// Tries to reserve capacity for at least `additional` more elements to be inserted
/// in the given `Vec<T>`.
///
/// Equivalent to [`Vec::try_reserve`].
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.0.try_reserve(additional)
}
/// Tries to reserve the minimum capacity for at least `additional`
/// elements to be inserted in the given `Vec<T>`.
///
/// Equivalent to [`Vec::try_reserve_exact`].
pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.0.try_reserve_exact(additional)
}
/// Shrinks the capacity of the vector as much as possible.
///
/// Equivalent to [`Vec::shrink_to_fit`].
pub fn shrink_to_fit(&mut self) {
self.0.shrink_to_fit();
}
/// Shrinks the capacity of the vector with a lower bound.
///
/// Equivalent to [`Vec::shrink_to`].
pub fn shrink_to(&mut self, min_capacity: usize) {
self.0.shrink_to(min_capacity);
}
/// Converts the vector into `Box<UniqueEntityEquivalentSlice<T>>`.
pub fn into_boxed_slice(self) -> Box<UniqueEntityEquivalentSlice<T>> {
// SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
unsafe {
UniqueEntityEquivalentSlice::from_boxed_slice_unchecked(self.0.into_boxed_slice())
}
}
/// Extracts a slice containing the entire vector.
pub fn as_slice(&self) -> &UniqueEntityEquivalentSlice<T> {
self
}
/// Extracts a mutable slice of the entire vector.
pub fn as_mut_slice(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {
self
}
/// Shortens the vector, keeping the first `len` elements and dropping
/// the rest.
///
/// Equivalent to [`Vec::truncate`].
pub fn truncate(&mut self, len: usize) {
self.0.truncate(len);
}
/// Returns a raw pointer to the vector's buffer, or a dangling raw pointer
/// valid for zero sized reads if the vector didn't allocate.
///
/// Equivalent to [`Vec::as_ptr`].
pub fn as_ptr(&self) -> *const T {
self.0.as_ptr()
}
/// Returns a raw mutable pointer to the vector's buffer, or a dangling
/// raw pointer valid for zero sized reads if the vector didn't allocate.
///
/// Equivalent to [`Vec::as_mut_ptr`].
pub fn as_mut_ptr(&mut self) -> *mut T {
self.0.as_mut_ptr()
}
/// Forces the length of the vector to `new_len`.
///
/// Equivalent to [`Vec::set_len`].
///
/// # Safety
///
/// It must be safe to call [`Vec::set_len`] with these inputs,
/// and the resulting [`Vec`] must only contain unique elements.
pub unsafe fn set_len(&mut self, new_len: usize) {
// SAFETY: Caller ensures it's safe to call `Vec::set_len`
unsafe { self.0.set_len(new_len) };
}
/// Removes an element from the vector and returns it.
///
/// Equivalent to [`Vec::swap_remove`].
pub fn swap_remove(&mut self, index: usize) -> T {
self.0.swap_remove(index)
}
/// Inserts an element at position `index` within the vector, shifting all
/// elements after it to the right.
///
/// Equivalent to [`Vec::insert`].
///
/// # Safety
///
/// No `T` contained by `self` may equal `element`.
pub unsafe fn insert(&mut self, index: usize, element: T) {
self.0.insert(index, element);
}
/// Removes and returns the element at position `index` within the vector,
/// shifting all elements after it to the left.
///
/// Equivalent to [`Vec::remove`].
pub fn remove(&mut self, index: usize) -> T {
self.0.remove(index)
}
/// Retains only the elements specified by the predicate.
///
/// Equivalent to [`Vec::retain`].
pub fn retain<F>(&mut self, f: F)
where
F: FnMut(&T) -> bool,
{
self.0.retain(f);
}
/// Retains only the elements specified by the predicate, passing a mutable reference to it.
///
/// Equivalent to [`Vec::retain_mut`].
///
/// # Safety
///
/// `self` must only contain unique elements after each individual execution of `f`.
pub unsafe fn retain_mut<F>(&mut self, f: F)
where
F: FnMut(&mut T) -> bool,
{
self.0.retain_mut(f);
}
/// Removes all but the first of consecutive elements in the vector that resolve to the same
/// key.
///
/// Equivalent to [`Vec::dedup_by_key`].
///
/// # Safety
///
/// `self` must only contain unique elements after each individual execution of `key`.
pub unsafe fn dedup_by_key<F, K>(&mut self, key: F)
where
F: FnMut(&mut T) -> K,
K: PartialEq,
{
self.0.dedup_by_key(key);
}
/// Removes all but the first of consecutive elements in the vector satisfying a given equality
/// relation.
///
/// Equivalent to [`Vec::dedup_by`].
///
/// # Safety
///
/// `self` must only contain unique elements after each individual execution of `same_bucket`.
pub unsafe fn dedup_by<F>(&mut self, same_bucket: F)
where
F: FnMut(&mut T, &mut T) -> bool,
{
self.0.dedup_by(same_bucket);
}
/// Appends an element to the back of a collection.
///
/// Equivalent to [`Vec::push`].
///
/// # Safety
///
/// No `T` contained by `self` may equal `element`.
pub unsafe fn push(&mut self, value: T) {
self.0.push(value);
}
/// Moves all the elements of `other` into `self`, leaving `other` empty.
///
/// Equivalent to [`Vec::append`].
///
/// # Safety
///
/// `other` must contain no elements that equal any element in `self`.
pub unsafe fn append(&mut self, other: &mut UniqueEntityEquivalentVec<T>) {
self.0.append(&mut other.0);
}
/// Removes the last element from a vector and returns it, or [`None`] if it
/// is empty.
///
/// Equivalent to [`Vec::pop`].
pub fn pop(&mut self) -> Option<T> {
self.0.pop()
}
/// Removes the specified range from the vector in bulk, returning all
/// removed elements as an iterator.
///
/// Equivalent to [`Vec::drain`].
pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
where
R: RangeBounds<usize>,
{
// SAFETY: `self` and thus `range` contains only unique elements.
unsafe { UniqueEntityIter::from_iterator_unchecked(self.0.drain(range)) }
}
/// Clears the vector, removing all values.
///
/// Equivalent to [`Vec::clear`].
pub fn clear(&mut self) {
self.0.clear();
}
/// Returns the number of elements in the vector, also referred to
/// as its 'length'.
///
/// Equivalent to [`Vec::len`].
pub fn len(&self) -> usize {
self.0.len()
}
/// Returns `true` if the vector contains no elements.
///
/// Equivalent to [`Vec::is_empty`].
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Splits the collection into two at the given index.
///
/// Equivalent to [`Vec::split_off`].
pub fn split_off(&mut self, at: usize) -> Self {
Self(self.0.split_off(at))
}
/// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
///
/// Equivalent to [`Vec::resize_with`].
///
/// # Safety
///
/// `f` must only produce unique `T`, and none of these may equal any `T` in `self`.
pub unsafe fn resize_with<F>(&mut self, new_len: usize, f: F)
where
F: FnMut() -> T,
{
self.0.resize_with(new_len, f);
}
/// Consumes and leaks the Vec, returning a mutable reference to the contents, `&'a mut UniqueEntityEquivalentSlice<T>`.
pub fn leak<'a>(self) -> &'a mut UniqueEntityEquivalentSlice<T> {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.leak()) }
}
/// Returns the remaining spare capacity of the vector as a slice of
/// [`MaybeUninit<T>`].
///
/// Equivalent to [`Vec::spare_capacity_mut`].
pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
self.0.spare_capacity_mut()
}
/// Creates a splicing iterator that replaces the specified range in the vector
/// with the given `replace_with` iterator and yields the removed items.
///
/// Equivalent to [`Vec::splice`].
///
/// # Safety
///
/// `replace_with` must not yield any elements that equal any elements in `self`,
/// except for those in `range`.
pub unsafe fn splice<R, I>(
&mut self,
range: R,
replace_with: I,
) -> Splice<'_, <I as IntoIterator>::IntoIter>
where
R: RangeBounds<usize>,
I: EntitySet<Item = T>,
{
// SAFETY: `self` and thus `range` contains only unique elements.
unsafe { UniqueEntityIter::from_iterator_unchecked(self.0.splice(range, replace_with)) }
}
}
impl<T: EntityEquivalent> Default for UniqueEntityEquivalentVec<T> {
fn default() -> Self {
Self(Vec::default())
}
}
impl<T: EntityEquivalent> Deref for UniqueEntityEquivalentVec<T> {
type Target = UniqueEntityEquivalentSlice<T>;
fn deref(&self) -> &Self::Target {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(&self.0) }
}
}
impl<T: EntityEquivalent> DerefMut for UniqueEntityEquivalentVec<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(&mut self.0) }
}
}
impl<'a, T: EntityEquivalent> IntoIterator for &'a UniqueEntityEquivalentVec<T>
where
&'a T: EntityEquivalent,
{
type Item = &'a T;
type IntoIter = unique_slice::Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
// SAFETY: `self` contains only unique elements.
unsafe { UniqueEntityIter::from_iterator_unchecked(self.0.iter()) }
}
}
impl<T: EntityEquivalent> IntoIterator for UniqueEntityEquivalentVec<T> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
// SAFETY: `self` contains only unique elements.
unsafe { UniqueEntityIter::from_iterator_unchecked(self.0.into_iter()) }
}
}
impl<T: EntityEquivalent> AsMut<Self> for UniqueEntityEquivalentVec<T> {
fn as_mut(&mut self) -> &mut UniqueEntityEquivalentVec<T> {
self
}
}
impl<T: EntityEquivalent> AsMut<UniqueEntityEquivalentSlice<T>> for UniqueEntityEquivalentVec<T> {
fn as_mut(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {
self
}
}
impl<T: EntityEquivalent> AsRef<Self> for UniqueEntityEquivalentVec<T> {
fn as_ref(&self) -> &Self {
self
}
}
impl<T: EntityEquivalent> AsRef<Vec<T>> for UniqueEntityEquivalentVec<T> {
fn as_ref(&self) -> &Vec<T> {
&self.0
}
}
impl<T: EntityEquivalent> Borrow<Vec<T>> for UniqueEntityEquivalentVec<T> {
fn borrow(&self) -> &Vec<T> {
&self.0
}
}
impl<T: EntityEquivalent> AsRef<[T]> for UniqueEntityEquivalentVec<T> {
fn as_ref(&self) -> &[T] {
&self.0
}
}
impl<T: EntityEquivalent> AsRef<UniqueEntityEquivalentSlice<T>> for UniqueEntityEquivalentVec<T> {
fn as_ref(&self) -> &UniqueEntityEquivalentSlice<T> {
self
}
}
impl<T: EntityEquivalent> Borrow<[T]> for UniqueEntityEquivalentVec<T> {
fn borrow(&self) -> &[T] {
&self.0
}
}
impl<T: EntityEquivalent> Borrow<UniqueEntityEquivalentSlice<T>> for UniqueEntityEquivalentVec<T> {
fn borrow(&self) -> &UniqueEntityEquivalentSlice<T> {
self
}
}
impl<T: EntityEquivalent> BorrowMut<UniqueEntityEquivalentSlice<T>>
for UniqueEntityEquivalentVec<T>
{
fn borrow_mut(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {
self
}
}
impl<T: EntityEquivalent + PartialEq<U>, U> PartialEq<Vec<U>> for UniqueEntityEquivalentVec<T> {
fn eq(&self, other: &Vec<U>) -> bool {
self.0.eq(other)
}
}
impl<T: EntityEquivalent + PartialEq<U>, U> PartialEq<&[U]> for UniqueEntityEquivalentVec<T> {
fn eq(&self, other: &&[U]) -> bool {
self.0.eq(other)
}
}
impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>
PartialEq<&UniqueEntityEquivalentSlice<U>> for UniqueEntityEquivalentVec<T>
{
fn eq(&self, other: &&UniqueEntityEquivalentSlice<U>) -> bool {
self.0.eq(other)
}
}
impl<T: EntityEquivalent + PartialEq<U>, U> PartialEq<&mut [U]> for UniqueEntityEquivalentVec<T> {
fn eq(&self, other: &&mut [U]) -> bool {
self.0.eq(other)
}
}
impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>
PartialEq<&mut UniqueEntityEquivalentSlice<U>> for UniqueEntityEquivalentVec<T>
{
fn eq(&self, other: &&mut UniqueEntityEquivalentSlice<U>) -> bool {
self.0.eq(other)
}
}
impl<T: EntityEquivalent + PartialEq<U>, U, const N: usize> PartialEq<&[U; N]>
for UniqueEntityEquivalentVec<T>
{
fn eq(&self, other: &&[U; N]) -> bool {
self.0.eq(other)
}
}
impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent, const N: usize>
PartialEq<&UniqueEntityEquivalentArray<U, N>> for UniqueEntityEquivalentVec<T>
{
fn eq(&self, other: &&UniqueEntityEquivalentArray<U, N>) -> bool {
self.0.eq(&other.as_inner())
}
}
impl<T: EntityEquivalent + PartialEq<U>, U, const N: usize> PartialEq<&mut [U; N]>
for UniqueEntityEquivalentVec<T>
{
fn eq(&self, other: &&mut [U; N]) -> bool {
self.0.eq(&**other)
}
}
impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent, const N: usize>
PartialEq<&mut UniqueEntityEquivalentArray<U, N>> for UniqueEntityEquivalentVec<T>
{
fn eq(&self, other: &&mut UniqueEntityEquivalentArray<U, N>) -> bool {
self.0.eq(other.as_inner())
}
}
impl<T: EntityEquivalent + PartialEq<U>, U> PartialEq<[U]> for UniqueEntityEquivalentVec<T> {
fn eq(&self, other: &[U]) -> bool {
self.0.eq(other)
}
}
impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>
PartialEq<UniqueEntityEquivalentSlice<U>> for UniqueEntityEquivalentVec<T>
{
fn eq(&self, other: &UniqueEntityEquivalentSlice<U>) -> bool {
self.0.eq(&**other)
}
}
impl<T: EntityEquivalent + PartialEq<U>, U, const N: usize> PartialEq<[U; N]>
for UniqueEntityEquivalentVec<T>
{
fn eq(&self, other: &[U; N]) -> bool {
self.0.eq(other)
}
}
impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent, const N: usize>
PartialEq<UniqueEntityEquivalentArray<U, N>> for UniqueEntityEquivalentVec<T>
{
fn eq(&self, other: &UniqueEntityEquivalentArray<U, N>) -> bool {
self.0.eq(other.as_inner())
}
}
impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<UniqueEntityEquivalentVec<U>> for Vec<T> {
fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
self.eq(&other.0)
}
}
impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<UniqueEntityEquivalentVec<U>> for &[T] {
fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
self.eq(&other.0)
}
}
impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<UniqueEntityEquivalentVec<U>> for &mut [T] {
fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
self.eq(&other.0)
}
}
impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>
PartialEq<UniqueEntityEquivalentVec<U>> for [T]
{
fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
self.eq(&other.0)
}
}
impl<T: PartialEq<U> + Clone, U: EntityEquivalent> PartialEq<UniqueEntityEquivalentVec<U>>
for Cow<'_, [T]>
{
fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
self.eq(&other.0)
}
}
impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<UniqueEntityEquivalentVec<U>> for VecDeque<T> {
fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
self.eq(&other.0)
}
}
impl<T: EntityEquivalent + Clone> From<&UniqueEntityEquivalentSlice<T>>
for UniqueEntityEquivalentVec<T>
{
fn from(value: &UniqueEntityEquivalentSlice<T>) -> Self {
value.to_vec()
}
}
impl<T: EntityEquivalent + Clone> From<&mut UniqueEntityEquivalentSlice<T>>
for UniqueEntityEquivalentVec<T>
{
fn from(value: &mut UniqueEntityEquivalentSlice<T>) -> Self {
value.to_vec()
}
}
impl<T: EntityEquivalent> From<Box<UniqueEntityEquivalentSlice<T>>>
for UniqueEntityEquivalentVec<T>
{
fn from(value: Box<UniqueEntityEquivalentSlice<T>>) -> Self {
value.into_vec()
}
}
impl<T: EntityEquivalent> From<Cow<'_, UniqueEntityEquivalentSlice<T>>>
for UniqueEntityEquivalentVec<T>
where
UniqueEntityEquivalentSlice<T>: ToOwned<Owned = UniqueEntityEquivalentVec<T>>,
{
fn from(value: Cow<UniqueEntityEquivalentSlice<T>>) -> Self {
value.into_owned()
}
}
impl<T: EntityEquivalent + Clone> From<&[T; 1]> for UniqueEntityEquivalentVec<T> {
fn from(value: &[T; 1]) -> Self {
Self(Vec::from(value))
}
}
impl<T: EntityEquivalent + Clone> From<&[T; 0]> for UniqueEntityEquivalentVec<T> {
fn from(value: &[T; 0]) -> Self {
Self(Vec::from(value))
}
}
impl<T: EntityEquivalent + Clone> From<&mut [T; 1]> for UniqueEntityEquivalentVec<T> {
fn from(value: &mut [T; 1]) -> Self {
Self(Vec::from(value))
}
}
impl<T: EntityEquivalent + Clone> From<&mut [T; 0]> for UniqueEntityEquivalentVec<T> {
fn from(value: &mut [T; 0]) -> Self {
Self(Vec::from(value))
}
}
impl<T: EntityEquivalent> From<[T; 1]> for UniqueEntityEquivalentVec<T> {
fn from(value: [T; 1]) -> Self {
Self(Vec::from(value))
}
}
impl<T: EntityEquivalent> From<[T; 0]> for UniqueEntityEquivalentVec<T> {
fn from(value: [T; 0]) -> Self {
Self(Vec::from(value))
}
}
impl<T: EntityEquivalent + Clone, const N: usize> From<&UniqueEntityEquivalentArray<T, N>>
for UniqueEntityEquivalentVec<T>
{
fn from(value: &UniqueEntityEquivalentArray<T, N>) -> Self {
Self(Vec::from(value.as_inner().clone()))
}
}
impl<T: EntityEquivalent + Clone, const N: usize> From<&mut UniqueEntityEquivalentArray<T, N>>
for UniqueEntityEquivalentVec<T>
{
fn from(value: &mut UniqueEntityEquivalentArray<T, N>) -> Self {
Self(Vec::from(value.as_inner().clone()))
}
}
impl<T: EntityEquivalent, const N: usize> From<UniqueEntityEquivalentArray<T, N>>
for UniqueEntityEquivalentVec<T>
{
fn from(value: UniqueEntityEquivalentArray<T, N>) -> Self {
Self(Vec::from(value.into_inner()))
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>> for Vec<T> {
fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
value.0
}
}
impl<'a, T: EntityEquivalent + Clone> From<UniqueEntityEquivalentVec<T>> for Cow<'a, [T]> {
fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
Cow::from(value.0)
}
}
impl<'a, T: EntityEquivalent + Clone> From<UniqueEntityEquivalentVec<T>>
for Cow<'a, UniqueEntityEquivalentSlice<T>>
{
fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
Cow::Owned(value)
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>> for Arc<[T]> {
fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
Arc::from(value.0)
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>>
for Arc<UniqueEntityEquivalentSlice<T>>
{
fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_arc_slice_unchecked(Arc::from(value.0)) }
}
}
impl<T: EntityEquivalent + Ord> From<UniqueEntityEquivalentVec<T>> for BinaryHeap<T> {
fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
BinaryHeap::from(value.0)
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>> for Box<[T]> {
fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
Box::from(value.0)
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>> for Rc<[T]> {
fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
Rc::from(value.0)
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>>
for Rc<UniqueEntityEquivalentSlice<T>>
{
fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_rc_slice_unchecked(Rc::from(value.0)) }
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>> for VecDeque<T> {
fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
VecDeque::from(value.0)
}
}
impl<T: EntityEquivalent, const N: usize> TryFrom<UniqueEntityEquivalentVec<T>> for Box<[T; N]> {
type Error = UniqueEntityEquivalentVec<T>;
fn try_from(value: UniqueEntityEquivalentVec<T>) -> Result<Self, Self::Error> {
Box::try_from(value.0).map_err(UniqueEntityEquivalentVec)
}
}
impl<T: EntityEquivalent, const N: usize> TryFrom<UniqueEntityEquivalentVec<T>>
for Box<UniqueEntityEquivalentArray<T, N>>
{
type Error = UniqueEntityEquivalentVec<T>;
fn try_from(value: UniqueEntityEquivalentVec<T>) -> Result<Self, Self::Error> {
Box::try_from(value.0)
.map(|v|
// SAFETY: All elements in the original Vec are unique.
unsafe { UniqueEntityEquivalentArray::from_boxed_array_unchecked(v) })
.map_err(UniqueEntityEquivalentVec)
}
}
impl<T: EntityEquivalent, const N: usize> TryFrom<UniqueEntityEquivalentVec<T>> for [T; N] {
type Error = UniqueEntityEquivalentVec<T>;
fn try_from(value: UniqueEntityEquivalentVec<T>) -> Result<Self, Self::Error> {
<[T; N] as TryFrom<Vec<T>>>::try_from(value.0).map_err(UniqueEntityEquivalentVec)
}
}
impl<T: EntityEquivalent, const N: usize> TryFrom<UniqueEntityEquivalentVec<T>>
for UniqueEntityEquivalentArray<T, N>
{
type Error = UniqueEntityEquivalentVec<T>;
fn try_from(value: UniqueEntityEquivalentVec<T>) -> Result<Self, Self::Error> {
<[T; N] as TryFrom<Vec<T>>>::try_from(value.0)
.map(|v|
// SAFETY: All elements in the original Vec are unique.
unsafe { UniqueEntityEquivalentArray::from_array_unchecked(v) })
.map_err(UniqueEntityEquivalentVec)
}
}
impl<T: EntityEquivalent> From<BTreeSet<T>> for UniqueEntityEquivalentVec<T> {
fn from(value: BTreeSet<T>) -> Self {
Self(value.into_iter().collect::<Vec<T>>())
}
}
impl<T: EntityEquivalent> FromIterator<T> for UniqueEntityEquivalentVec<T> {
/// This impl only uses `Eq` to validate uniqueness, resulting in O(n^2) complexity.
/// It can make sense for very low N, or if `T` implements neither `Ord` nor `Hash`.
/// When possible, use `FromEntitySetIterator::from_entity_iter` instead.
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
// Matches the `HashSet::from_iter` reservation logic.
let iter = iter.into_iter();
let unique_vec = Self::with_capacity(iter.size_hint().0);
// Internal iteration (fold/for_each) is known to result in better code generation
// over a for loop.
iter.fold(unique_vec, |mut unique_vec, item| {
if !unique_vec.0.contains(&item) {
unique_vec.0.push(item);
}
unique_vec
})
}
}
impl<T: EntityEquivalent> FromEntitySetIterator<T> for UniqueEntityEquivalentVec<T> {
fn from_entity_set_iter<I: EntitySet<Item = T>>(iter: I) -> Self {
// SAFETY: `iter` is an `EntitySet`.
unsafe { Self::from_vec_unchecked(Vec::from_iter(iter)) }
}
}
impl<T: EntityEquivalent> Extend<T> for UniqueEntityEquivalentVec<T> {
/// Use with caution, because this impl only uses `Eq` to validate uniqueness,
/// resulting in O(n^2) complexity.
/// It can make sense for very low N, or if `T` implements neither `Ord` nor `Hash`.
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
// Matches the `HashSet::extend` reservation logic. Their reasoning:
// "Keys may be already present or show multiple times in the iterator.
// Reserve the entire hint lower bound if the map is empty.
// Otherwise reserve half the hint (rounded up), so the map
// will only resize twice in the worst case."
let iter = iter.into_iter();
let reserve = if self.is_empty() {
iter.size_hint().0
} else {
iter.size_hint().0.div_ceil(2)
};
self.reserve(reserve);
// Internal iteration (fold/for_each) is known to result in better code generation
// over a for loop.
iter.for_each(move |item| {
if !self.0.contains(&item) {
self.0.push(item);
}
});
}
}
impl<'a, T: EntityEquivalent + Copy + 'a> Extend<&'a T> for UniqueEntityEquivalentVec<T> {
/// Use with caution, because this impl only uses `Eq` to validate uniqueness,
/// resulting in O(n^2) complexity.
/// It can make sense for very low N, or if `T` implements neither `Ord` nor `Hash`.
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
// Matches the `HashSet::extend` reservation logic. Their reasoning:
// "Keys may be already present or show multiple times in the iterator.
// Reserve the entire hint lower bound if the map is empty.
// Otherwise reserve half the hint (rounded up), so the map
// will only resize twice in the worst case."
let iter = iter.into_iter();
let reserve = if self.is_empty() {
iter.size_hint().0
} else {
iter.size_hint().0.div_ceil(2)
};
self.reserve(reserve);
// Internal iteration (fold/for_each) is known to result in better code generation
// over a for loop.
iter.for_each(move |item| {
if !self.0.contains(item) {
self.0.push(*item);
}
});
}
}
impl<T: EntityEquivalent> Index<(Bound<usize>, Bound<usize>)> for UniqueEntityEquivalentVec<T> {
type Output = UniqueEntityEquivalentSlice<T>;
fn index(&self, key: (Bound<usize>, Bound<usize>)) -> &Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<T: EntityEquivalent> Index<Range<usize>> for UniqueEntityEquivalentVec<T> {
type Output = UniqueEntityEquivalentSlice<T>;
fn index(&self, key: Range<usize>) -> &Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<T: EntityEquivalent> Index<RangeFrom<usize>> for UniqueEntityEquivalentVec<T> {
type Output = UniqueEntityEquivalentSlice<T>;
fn index(&self, key: RangeFrom<usize>) -> &Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<T: EntityEquivalent> Index<RangeFull> for UniqueEntityEquivalentVec<T> {
type Output = UniqueEntityEquivalentSlice<T>;
fn index(&self, key: RangeFull) -> &Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<T: EntityEquivalent> Index<RangeInclusive<usize>> for UniqueEntityEquivalentVec<T> {
type Output = UniqueEntityEquivalentSlice<T>;
fn index(&self, key: RangeInclusive<usize>) -> &Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<T: EntityEquivalent> Index<RangeTo<usize>> for UniqueEntityEquivalentVec<T> {
type Output = UniqueEntityEquivalentSlice<T>;
fn index(&self, key: RangeTo<usize>) -> &Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<T: EntityEquivalent> Index<RangeToInclusive<usize>> for UniqueEntityEquivalentVec<T> {
type Output = UniqueEntityEquivalentSlice<T>;
| 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/hash_map.rs | crates/bevy_ecs/src/entity/hash_map.rs | //! Contains the [`EntityHashMap`] type, a [`HashMap`] pre-configured to use [`EntityHash`] hashing.
//!
//! This module is a lightweight wrapper around Bevy's [`HashMap`] that is more performant for [`Entity`] keys.
use core::{
fmt::{self, Debug, Formatter},
iter::FusedIterator,
marker::PhantomData,
ops::{Deref, DerefMut, Index},
};
use bevy_platform::collections::hash_map::{self, HashMap};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
use super::{Entity, EntityEquivalent, EntityHash, EntitySetIterator};
/// A [`HashMap`] pre-configured to use [`EntityHash`] hashing.
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serialize", derive(serde::Deserialize, serde::Serialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntityHashMap<V>(pub(crate) HashMap<Entity, V, EntityHash>);
impl<V> EntityHashMap<V> {
/// Creates an empty `EntityHashMap`.
///
/// Equivalent to [`HashMap::with_hasher(EntityHash)`].
///
/// [`HashMap::with_hasher(EntityHash)`]: HashMap::with_hasher
pub const fn new() -> Self {
Self(HashMap::with_hasher(EntityHash))
}
/// Creates an empty `EntityHashMap` with the specified capacity.
///
/// Equivalent to [`HashMap::with_capacity_and_hasher(n, EntityHash)`].
///
/// [`HashMap:with_capacity_and_hasher(n, EntityHash)`]: HashMap::with_capacity_and_hasher
pub fn with_capacity(n: usize) -> Self {
Self(HashMap::with_capacity_and_hasher(n, EntityHash))
}
/// Returns the inner [`HashMap`].
pub fn into_inner(self) -> HashMap<Entity, V, EntityHash> {
self.0
}
/// An iterator visiting all keys in arbitrary order.
/// The iterator element type is `&'a Entity`.
///
/// Equivalent to [`HashMap::keys`].
pub fn keys(&self) -> Keys<'_, V> {
Keys(self.0.keys(), PhantomData)
}
/// Creates a consuming iterator visiting all the keys in arbitrary order.
/// The map cannot be used after calling this.
/// The iterator element type is [`Entity`].
///
/// Equivalent to [`HashMap::into_keys`].
pub fn into_keys(self) -> IntoKeys<V> {
IntoKeys(self.0.into_keys(), PhantomData)
}
}
impl<V> Default for EntityHashMap<V> {
fn default() -> Self {
Self(Default::default())
}
}
impl<V> Deref for EntityHashMap<V> {
type Target = HashMap<Entity, V, EntityHash>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<V> DerefMut for EntityHashMap<V> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<'a, V: Copy> Extend<&'a (Entity, V)> for EntityHashMap<V> {
fn extend<T: IntoIterator<Item = &'a (Entity, V)>>(&mut self, iter: T) {
self.0.extend(iter);
}
}
impl<'a, V: Copy> Extend<(&'a Entity, &'a V)> for EntityHashMap<V> {
fn extend<T: IntoIterator<Item = (&'a Entity, &'a V)>>(&mut self, iter: T) {
self.0.extend(iter);
}
}
impl<V> Extend<(Entity, V)> for EntityHashMap<V> {
fn extend<T: IntoIterator<Item = (Entity, V)>>(&mut self, iter: T) {
self.0.extend(iter);
}
}
impl<V, const N: usize> From<[(Entity, V); N]> for EntityHashMap<V> {
fn from(value: [(Entity, V); N]) -> Self {
Self(HashMap::from_iter(value))
}
}
impl<V> FromIterator<(Entity, V)> for EntityHashMap<V> {
fn from_iter<I: IntoIterator<Item = (Entity, V)>>(iterable: I) -> Self {
Self(HashMap::from_iter(iterable))
}
}
impl<V, Q: EntityEquivalent + ?Sized> Index<&Q> for EntityHashMap<V> {
type Output = V;
fn index(&self, key: &Q) -> &V {
self.0.index(&key.entity())
}
}
impl<'a, V> IntoIterator for &'a EntityHashMap<V> {
type Item = (&'a Entity, &'a V);
type IntoIter = hash_map::Iter<'a, Entity, V>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl<'a, V> IntoIterator for &'a mut EntityHashMap<V> {
type Item = (&'a Entity, &'a mut V);
type IntoIter = hash_map::IterMut<'a, Entity, V>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter_mut()
}
}
impl<V> IntoIterator for EntityHashMap<V> {
type Item = (Entity, V);
type IntoIter = hash_map::IntoIter<Entity, V>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
/// An iterator over the keys of a [`EntityHashMap`] in arbitrary order.
/// The iterator element type is `&'a Entity`.
///
/// This struct is created by the [`keys`] method on [`EntityHashMap`]. See its documentation for more.
///
/// [`keys`]: EntityHashMap::keys
pub struct Keys<'a, V, S = EntityHash>(hash_map::Keys<'a, Entity, V>, PhantomData<S>);
impl<'a, V> Keys<'a, V> {
/// Returns the inner [`Keys`](hash_map::Keys).
pub fn into_inner(self) -> hash_map::Keys<'a, Entity, V> {
self.0
}
}
impl<'a, V> Deref for Keys<'a, V> {
type Target = hash_map::Keys<'a, Entity, V>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a, V> Iterator for Keys<'a, V> {
type Item = &'a Entity;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl<V> ExactSizeIterator for Keys<'_, V> {}
impl<V> FusedIterator for Keys<'_, V> {}
impl<V> Clone for Keys<'_, V> {
fn clone(&self) -> Self {
Self(self.0.clone(), PhantomData)
}
}
impl<V: Debug> Debug for Keys<'_, V> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("Keys").field(&self.0).field(&self.1).finish()
}
}
impl<V> Default for Keys<'_, V> {
fn default() -> Self {
Self(Default::default(), PhantomData)
}
}
// SAFETY: Keys stems from a correctly behaving `HashMap<Entity, V, EntityHash>`.
unsafe impl<V> EntitySetIterator for Keys<'_, V> {}
/// An owning iterator over the keys of a [`EntityHashMap`] in arbitrary order.
/// The iterator element type is [`Entity`].
///
/// This struct is created by the [`into_keys`] method on [`EntityHashMap`].
/// See its documentation for more.
/// The map cannot be used after calling that method.
///
/// [`into_keys`]: EntityHashMap::into_keys
pub struct IntoKeys<V, S = EntityHash>(hash_map::IntoKeys<Entity, V>, PhantomData<S>);
impl<V> IntoKeys<V> {
/// Returns the inner [`IntoKeys`](hash_map::IntoKeys).
pub fn into_inner(self) -> hash_map::IntoKeys<Entity, V> {
self.0
}
}
impl<V> Deref for IntoKeys<V> {
type Target = hash_map::IntoKeys<Entity, V>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<V> Iterator for IntoKeys<V> {
type Item = Entity;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl<V> ExactSizeIterator for IntoKeys<V> {}
impl<V> FusedIterator for IntoKeys<V> {}
impl<V: Debug> Debug for IntoKeys<V> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("IntoKeys")
.field(&self.0)
.field(&self.1)
.finish()
}
}
impl<V> Default for IntoKeys<V> {
fn default() -> Self {
Self(Default::default(), PhantomData)
}
}
// SAFETY: IntoKeys stems from a correctly behaving `HashMap<Entity, V, EntityHash>`.
unsafe impl<V> EntitySetIterator for IntoKeys<V> {}
#[cfg(test)]
mod tests {
use super::*;
use bevy_reflect::Reflect;
use static_assertions::assert_impl_all;
// Check that the HashMaps are Clone if the key/values are Clone
assert_impl_all!(EntityHashMap::<usize>: Clone);
// EntityHashMap should implement Reflect
#[cfg(feature = "bevy_reflect")]
assert_impl_all!(EntityHashMap::<i32>: Reflect);
}
| 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/entity/hash_set.rs | crates/bevy_ecs/src/entity/hash_set.rs | //! Contains the [`EntityHashSet`] type, a [`HashSet`] pre-configured to use [`EntityHash`] hashing.
//!
//! This module is a lightweight wrapper around Bevy's [`HashSet`] that is more performant for [`Entity`] keys.
use core::{
fmt::{self, Debug, Formatter},
iter::FusedIterator,
marker::PhantomData,
ops::{
BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Deref, DerefMut, Sub,
SubAssign,
},
};
use bevy_platform::collections::hash_set::{self, HashSet};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
use super::{Entity, EntityHash, EntitySet, EntitySetIterator, FromEntitySetIterator};
/// A [`HashSet`] pre-configured to use [`EntityHash`] hashing.
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serialize", derive(serde::Deserialize, serde::Serialize))]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EntityHashSet(pub(crate) HashSet<Entity, EntityHash>);
impl EntityHashSet {
/// Creates an empty `EntityHashSet`.
///
/// Equivalent to [`HashSet::with_hasher(EntityHash)`].
///
/// [`HashSet::with_hasher(EntityHash)`]: HashSet::with_hasher
pub const fn new() -> Self {
Self(HashSet::with_hasher(EntityHash))
}
/// Creates an empty `EntityHashSet` with the specified capacity.
///
/// Equivalent to [`HashSet::with_capacity_and_hasher(n, EntityHash)`].
///
/// [`HashSet::with_capacity_and_hasher(n, EntityHash)`]: HashSet::with_capacity_and_hasher
pub fn with_capacity(n: usize) -> Self {
Self(HashSet::with_capacity_and_hasher(n, EntityHash))
}
/// Returns the number of elements in the set.
pub fn len(&self) -> usize {
self.0.len()
}
/// Returns `true` if the set contains no elements.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns the inner [`HashSet`].
pub fn into_inner(self) -> HashSet<Entity, EntityHash> {
self.0
}
/// Clears the set, returning all elements in an iterator.
///
/// Equivalent to [`HashSet::drain`].
pub fn drain(&mut self) -> Drain<'_> {
Drain(self.0.drain(), PhantomData)
}
/// An iterator visiting all elements in arbitrary order.
/// The iterator element type is `&'a Entity`.
///
/// Equivalent to [`HashSet::iter`].
pub fn iter(&self) -> Iter<'_> {
Iter(self.0.iter(), PhantomData)
}
/// Drains elements which are true under the given predicate,
/// and returns an iterator over the removed items.
///
/// Equivalent to [`HashSet::extract_if`].
pub fn extract_if<F: FnMut(&Entity) -> bool>(&mut self, f: F) -> ExtractIf<'_, F> {
ExtractIf(self.0.extract_if(f), PhantomData)
}
}
impl Deref for EntityHashSet {
type Target = HashSet<Entity, EntityHash>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for EntityHashSet {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<'a> IntoIterator for &'a EntityHashSet {
type Item = &'a Entity;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Self::IntoIter {
Iter((&self.0).into_iter(), PhantomData)
}
}
impl IntoIterator for EntityHashSet {
type Item = Entity;
type IntoIter = IntoIter;
fn into_iter(self) -> Self::IntoIter {
IntoIter(self.0.into_iter(), PhantomData)
}
}
impl BitAnd for &EntityHashSet {
type Output = EntityHashSet;
fn bitand(self, rhs: Self) -> Self::Output {
EntityHashSet(self.0.bitand(&rhs.0))
}
}
impl BitAndAssign<&EntityHashSet> for EntityHashSet {
fn bitand_assign(&mut self, rhs: &Self) {
self.0.bitand_assign(&rhs.0);
}
}
impl BitOr for &EntityHashSet {
type Output = EntityHashSet;
fn bitor(self, rhs: Self) -> Self::Output {
EntityHashSet(self.0.bitor(&rhs.0))
}
}
impl BitOrAssign<&EntityHashSet> for EntityHashSet {
fn bitor_assign(&mut self, rhs: &Self) {
self.0.bitor_assign(&rhs.0);
}
}
impl BitXor for &EntityHashSet {
type Output = EntityHashSet;
fn bitxor(self, rhs: Self) -> Self::Output {
EntityHashSet(self.0.bitxor(&rhs.0))
}
}
impl BitXorAssign<&EntityHashSet> for EntityHashSet {
fn bitxor_assign(&mut self, rhs: &Self) {
self.0.bitxor_assign(&rhs.0);
}
}
impl Sub for &EntityHashSet {
type Output = EntityHashSet;
fn sub(self, rhs: Self) -> Self::Output {
EntityHashSet(self.0.sub(&rhs.0))
}
}
impl SubAssign<&EntityHashSet> for EntityHashSet {
fn sub_assign(&mut self, rhs: &Self) {
self.0.sub_assign(&rhs.0);
}
}
impl<'a> Extend<&'a Entity> for EntityHashSet {
fn extend<T: IntoIterator<Item = &'a Entity>>(&mut self, iter: T) {
self.0.extend(iter);
}
}
impl Extend<Entity> for EntityHashSet {
fn extend<T: IntoIterator<Item = Entity>>(&mut self, iter: T) {
self.0.extend(iter);
}
}
impl<const N: usize> From<[Entity; N]> for EntityHashSet {
fn from(value: [Entity; N]) -> Self {
Self(HashSet::from_iter(value))
}
}
impl FromIterator<Entity> for EntityHashSet {
fn from_iter<I: IntoIterator<Item = Entity>>(iterable: I) -> Self {
Self(HashSet::from_iter(iterable))
}
}
impl FromEntitySetIterator<Entity> for EntityHashSet {
fn from_entity_set_iter<I: EntitySet<Item = Entity>>(set_iter: I) -> Self {
let iter = set_iter.into_iter();
let set = EntityHashSet::with_capacity(iter.size_hint().0);
iter.fold(set, |mut set, e| {
// SAFETY: Every element in self is unique.
unsafe {
set.insert_unique_unchecked(e);
}
set
})
}
}
/// An iterator over the items of an [`EntityHashSet`].
///
/// This struct is created by the [`iter`] method on [`EntityHashSet`]. See its documentation for more.
///
/// [`iter`]: EntityHashSet::iter
pub struct Iter<'a, S = EntityHash>(hash_set::Iter<'a, Entity>, PhantomData<S>);
impl<'a> Iter<'a> {
/// Returns the inner [`Iter`](hash_set::Iter).
pub fn into_inner(self) -> hash_set::Iter<'a, Entity> {
self.0
}
}
impl<'a> Deref for Iter<'a> {
type Target = hash_set::Iter<'a, Entity>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a> Iterator for Iter<'a> {
type Item = &'a Entity;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl ExactSizeIterator for Iter<'_> {}
impl FusedIterator for Iter<'_> {}
impl Clone for Iter<'_> {
fn clone(&self) -> Self {
Self(self.0.clone(), PhantomData)
}
}
impl Debug for Iter<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("Iter").field(&self.0).field(&self.1).finish()
}
}
impl Default for Iter<'_> {
fn default() -> Self {
Self(Default::default(), PhantomData)
}
}
// SAFETY: Iter stems from a correctly behaving `HashSet<Entity, EntityHash>`.
unsafe impl EntitySetIterator for Iter<'_> {}
/// Owning iterator over the items of an [`EntityHashSet`].
///
/// This struct is created by the [`into_iter`] method on [`EntityHashSet`] (provided by the [`IntoIterator`] trait). See its documentation for more.
///
/// [`into_iter`]: EntityHashSet::into_iter
pub struct IntoIter<S = EntityHash>(hash_set::IntoIter<Entity>, PhantomData<S>);
impl IntoIter {
/// Returns the inner [`IntoIter`](hash_set::IntoIter).
pub fn into_inner(self) -> hash_set::IntoIter<Entity> {
self.0
}
}
impl Deref for IntoIter {
type Target = hash_set::IntoIter<Entity>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Iterator for IntoIter {
type Item = Entity;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl ExactSizeIterator for IntoIter {}
impl FusedIterator for IntoIter {}
impl Debug for IntoIter {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("IntoIter")
.field(&self.0)
.field(&self.1)
.finish()
}
}
impl Default for IntoIter {
fn default() -> Self {
Self(Default::default(), PhantomData)
}
}
// SAFETY: IntoIter stems from a correctly behaving `HashSet<Entity, EntityHash>`.
unsafe impl EntitySetIterator for IntoIter {}
/// A draining iterator over the items of an [`EntityHashSet`].
///
/// This struct is created by the [`drain`] method on [`EntityHashSet`]. See its documentation for more.
///
/// [`drain`]: EntityHashSet::drain
pub struct Drain<'a, S = EntityHash>(hash_set::Drain<'a, Entity>, PhantomData<S>);
impl<'a> Drain<'a> {
/// Returns the inner [`Drain`](hash_set::Drain).
pub fn into_inner(self) -> hash_set::Drain<'a, Entity> {
self.0
}
}
impl<'a> Deref for Drain<'a> {
type Target = hash_set::Drain<'a, Entity>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a> Iterator for Drain<'a> {
type Item = Entity;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl ExactSizeIterator for Drain<'_> {}
impl FusedIterator for Drain<'_> {}
impl Debug for Drain<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("Drain")
.field(&self.0)
.field(&self.1)
.finish()
}
}
// SAFETY: Drain stems from a correctly behaving `HashSet<Entity, EntityHash>`.
unsafe impl EntitySetIterator for Drain<'_> {}
/// A draining iterator over entries of a [`EntityHashSet`] which don't satisfy the predicate `f`.
///
/// This struct is created by the [`extract_if`] method on [`EntityHashSet`]. See its documentation for more.
///
/// [`extract_if`]: EntityHashSet::extract_if
pub struct ExtractIf<'a, F: FnMut(&Entity) -> bool, S = EntityHash>(
hash_set::ExtractIf<'a, Entity, F>,
PhantomData<S>,
);
impl<'a, F: FnMut(&Entity) -> bool> ExtractIf<'a, F> {
/// Returns the inner [`ExtractIf`](hash_set::ExtractIf).
pub fn into_inner(self) -> hash_set::ExtractIf<'a, Entity, F> {
self.0
}
}
impl<'a, F: FnMut(&Entity) -> bool> Deref for ExtractIf<'a, F> {
type Target = hash_set::ExtractIf<'a, Entity, F>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a, F: FnMut(&Entity) -> bool> Iterator for ExtractIf<'a, F> {
type Item = Entity;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl<F: FnMut(&Entity) -> bool> FusedIterator for ExtractIf<'_, F> {}
impl<F: FnMut(&Entity) -> bool> Debug for ExtractIf<'_, F> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("ExtractIf").finish()
}
}
// SAFETY: ExtractIf stems from a correctly behaving `HashSet<Entity, EntityHash>`.
unsafe impl<F: FnMut(&Entity) -> bool> EntitySetIterator for ExtractIf<'_, F> {}
// SAFETY: Difference stems from two correctly behaving `HashSet<Entity, EntityHash>`s.
unsafe impl EntitySetIterator for hash_set::Difference<'_, Entity, EntityHash> {}
// SAFETY: Intersection stems from two correctly behaving `HashSet<Entity, EntityHash>`s.
unsafe impl EntitySetIterator for hash_set::Intersection<'_, Entity, EntityHash> {}
// SAFETY: SymmetricDifference stems from two correctly behaving `HashSet<Entity, EntityHash>`s.
unsafe impl EntitySetIterator for hash_set::SymmetricDifference<'_, Entity, EntityHash> {}
// SAFETY: Union stems from two correctly behaving `HashSet<Entity, EntityHash>`s.
unsafe impl EntitySetIterator for hash_set::Union<'_, Entity, EntityHash> {}
| 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/entity/mod.rs | crates/bevy_ecs/src/entity/mod.rs | //! This module contains all entity types and utilities for interacting with their ids.
//!
//! # What is an Entity?
//!
//! The ecs [docs](crate) give an overview of what entities are and generally how to use them.
//! These docs provide more detail into how they actually work.
//! In these docs [`Entity`] and "entity id" are synonymous and refer to the [`Entity`] type, which identifies an entity.
//! The term "entity" used on its own refers to the "thing"/"game object" that id references.
//!
//! # In this Module
//!
//! This module contains four main things:
//!
//! - Core ECS types like [`Entity`], [`Entities`], and [`EntityAllocator`].
//! - Utilities for [`Entity`] ids like [`MapEntities`], [`EntityHash`], and [`UniqueEntityVec`].
//! - Helpers for entity tasks like [`EntityCloner`].
//! - Entity-related error types like [`EntityNotSpawnedError`].
//!
//! # Entity Life Cycle
//!
//! Entities have life cycles.
//! They are created, used for a while, and eventually destroyed.
//! Let's start from the top:
//!
//! **Spawn:** An entity is created.
//! In bevy, this is called spawning.
//! Most commonly, this is done through [`World::spawn`](crate::world::World::spawn) or [`Commands::spawn`](crate::system::Commands::spawn).
//! This creates a fresh entity in the world and returns its [`Entity`] id, which can be used to interact with the entity it identifies.
//! These methods initialize the entity with a [`Bundle`], a group of [components](crate::component::Component) that it starts with.
//! It is also possible to use [`World::spawn_empty`](crate::world::World::spawn_empty) or [`Commands::spawn_empty`](crate::system::Commands::spawn_empty), which are similar but do not add any components to the entity.
//! In either case, the returned [`Entity`] id is used to further interact with the entity.
//!
//! **Update:** Once an entity is created, you will need its [`Entity`] id to perform further actions on it.
//! This can be done through [`World::entity_mut`](crate::world::World::entity_mut) and [`Commands::entity`](crate::system::Commands::entity).
//! Even if you don't store the id, you can still find the entity you spawned by searching for it in a [`Query`].
//! Queries are also the primary way of interacting with an entity's components.
//! You can use [`EntityWorldMut::remove`](crate::world::EntityWorldMut::remove) and [`EntityCommands::remove`](crate::system::EntityCommands::remove) to remove components,
//! and you can use [`EntityWorldMut::insert`](crate::world::EntityWorldMut::insert) and [`EntityCommands::insert`](crate::system::EntityCommands::insert) to insert more components.
//! Be aware that each entity can only have 0 or 1 values for each kind of component, so inserting a bundle may overwrite existing component values.
//! This can also be further configured based on the insert method.
//!
//! **Despawn:** Despawn an entity when it is no longer needed.
//! This destroys it and all its components.
//! The entity is no longer reachable through the [`World`], [`Commands`], or [`Query`]s.
//! Note that this means an [`Entity`] id may refer to an entity that has since been despawned!
//! Not all [`Entity`] ids refer to active entities.
//! If an [`Entity`] id is used when its entity has been despawned, an [`EntityNotSpawnedError`] is emitted.
//! Any [`System`](crate::system) could despawn any entity; even if you never share its id, it could still be despawned unexpectedly.
//! Your code should do its best to handle these errors gracefully.
//!
//! In short:
//!
//! - Entities are spawned through methods like [`World::spawn`](crate::world::World::spawn), which return an [`Entity`] id for the new entity.
//! - Once spawned, they can be accessed and modified through [`Query`]s and other apis.
//! - You can get the [`Entity`] id of an entity through [`Query`]s, so losing an [`Entity`] id is not a problem.
//! - Entities can have components inserted and removed via [`World::entity_mut`](crate::world::World::entity_mut) and [`Commands::entity`](crate::system::Commands::entity).
//! - Entities are eventually despawned, destroying the entity and causing its [`Entity`] id to no longer refer to an entity.
//! - Not all [`Entity`] ids point to actual entities, which makes many entity methods fallible.
//!
//! # [`Entity`] Allocation
//!
//! Entity spawning is actually done in two stages:
//! 1. Allocate: We generate a new valid / unique [`Entity`].
//! 2. Spawn: We make the entity "exist" in the [`World`]. It will show up in queries, it can have components, etc.
//!
//! The reason for this split is that we need to be able to _allocate_ entity ids concurrently,
//! whereas spawning requires unique (non-concurrent) access to the world.
//!
//! An [`Entity`] therefore goes through the following lifecycle:
//! 1. Unallocated (and "valid"): Only the allocator has any knowledge of this [`Entity`], but it _could_ be spawned, theoretically.
//! 2. Allocated (and "valid"): The allocator has handed out the [`Entity`], but it is not yet spawned.
//! 3. Spawned: The entity now "exists" in the [`World`]. It will show up in queries, it can have components, etc.
//! 4. Despawned: The entity no longer "exist" in the [`World`].
//! 5. Freed (and "invalid"): The [`Entity`] is returned to the allocator. The [`Entity::generation`] is bumped, which makes all existing [`Entity`] references with the previous generation "invalid".
//!
//! Note that by default, most spawn and despawn APIs handle the [`Entity`] allocation and freeing process for developers.
//!
//! [`World`]: crate::world::World
//! [`Query`]: crate::system::Query
//! [`Bundle`]: crate::bundle::Bundle
//! [`Component`]: crate::component::Component
//! [`Commands`]: crate::system::Commands
mod clone_entities;
mod entity_set;
mod map_entities;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
#[cfg(all(feature = "bevy_reflect", feature = "serialize"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
pub use clone_entities::*;
use derive_more::derive::Display;
pub use entity_set::*;
pub use map_entities::*;
mod hash;
pub use hash::*;
pub mod hash_map;
pub mod hash_set;
pub use hash_map::EntityHashMap;
pub use hash_set::EntityHashSet;
pub mod index_map;
pub mod index_set;
pub use index_map::EntityIndexMap;
pub use index_set::EntityIndexSet;
pub mod unique_array;
pub mod unique_slice;
pub mod unique_vec;
use nonmax::NonMaxU32;
pub use unique_array::{UniqueEntityArray, UniqueEntityEquivalentArray};
pub use unique_slice::{UniqueEntityEquivalentSlice, UniqueEntitySlice};
pub use unique_vec::{UniqueEntityEquivalentVec, UniqueEntityVec};
use crate::{
archetype::{ArchetypeId, ArchetypeRow},
change_detection::{CheckChangeTicks, MaybeLocation, Tick},
storage::{SparseSetIndex, TableId, TableRow},
};
use alloc::vec::Vec;
use bevy_platform::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
use core::{fmt, hash::Hash, mem, num::NonZero, panic::Location};
use log::warn;
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};
/// This represents the index of an [`Entity`] within the [`Entities`] array.
/// This is a lighter weight version of [`Entity`].
///
/// This is a unique identifier for an entity in the world.
/// This differs from [`Entity`] in that [`Entity`] is unique for all entities total (unless the [`Entity::generation`] wraps),
/// but this is only unique for entities that are active.
///
/// This can be used over [`Entity`] to improve performance in some cases,
/// but improper use can cause this to identify a different entity than intended.
/// Use with caution.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "bevy_reflect", reflect(opaque))]
#[cfg_attr(feature = "bevy_reflect", reflect(Hash, PartialEq, Debug, Clone))]
#[repr(transparent)]
pub struct EntityIndex(NonMaxU32);
impl EntityIndex {
const PLACEHOLDER: Self = Self(NonMaxU32::MAX);
/// Constructs a new [`EntityIndex`] from its index.
pub const fn new(index: NonMaxU32) -> Self {
Self(index)
}
/// Equivalent to [`new`](Self::new) except that it takes a `u32` instead of a `NonMaxU32`.
///
/// Returns `None` if the index is `u32::MAX`.
pub const fn from_raw_u32(index: u32) -> Option<Self> {
match NonMaxU32::new(index) {
Some(index) => Some(Self(index)),
None => None,
}
}
/// Gets the index of the entity.
#[inline(always)]
pub const fn index(self) -> u32 {
self.0.get()
}
/// Gets some bits that represent this value.
/// The bits are opaque and should not be regarded as meaningful.
#[inline(always)]
const fn to_bits(self) -> u32 {
// SAFETY: NonMax is repr transparent.
unsafe { mem::transmute::<NonMaxU32, u32>(self.0) }
}
/// Reconstruct an [`EntityIndex`] previously destructured with [`EntityIndex::to_bits`].
///
/// Only useful when applied to results from `to_bits` in the same instance of an application.
///
/// # Panics
///
/// This method will likely panic if given `u32` values that did not come from [`EntityIndex::to_bits`].
#[inline]
const fn from_bits(bits: u32) -> Self {
Self::try_from_bits(bits).expect("Attempted to initialize invalid bits as an entity index")
}
/// Reconstruct an [`EntityIndex`] previously destructured with [`EntityIndex::to_bits`].
///
/// Only useful when applied to results from `to_bits` in the same instance of an application.
///
/// This method is the fallible counterpart to [`EntityIndex::from_bits`].
#[inline(always)]
const fn try_from_bits(bits: u32) -> Option<Self> {
match NonZero::<u32>::new(bits) {
// SAFETY: NonMax and NonZero are repr transparent.
Some(underlying) => Some(Self(unsafe {
mem::transmute::<NonZero<u32>, NonMaxU32>(underlying)
})),
None => None,
}
}
}
impl SparseSetIndex for EntityIndex {
#[inline]
fn sparse_set_index(&self) -> usize {
self.index() as usize
}
#[inline]
fn get_sparse_set_index(value: usize) -> Self {
Self::from_bits(value as u32)
}
}
/// This tracks different versions or generations of an [`EntityIndex`].
/// Importantly, this can wrap, meaning each generation is not necessarily unique per [`EntityIndex`].
///
/// This should be treated as a opaque identifier, and its internal representation may be subject to change.
///
/// # Aliasing
///
/// Internally [`EntityGeneration`] wraps a `u32`, so it can't represent *every* possible generation.
/// Eventually, generations can (and do) wrap or alias.
/// This can cause [`Entity`] and [`EntityGeneration`] values to be equal while still referring to different conceptual entities.
/// This can cause some surprising behavior:
///
/// ```
/// # use bevy_ecs::entity::EntityGeneration;
/// let (aliased, did_alias) = EntityGeneration::FIRST.after_versions(1u32 << 31).after_versions_and_could_alias(1u32 << 31);
/// assert!(did_alias);
/// assert!(EntityGeneration::FIRST == aliased);
/// ```
///
/// This can cause some unintended side effects.
/// See [`Entity`] docs for practical concerns and how to minimize any risks.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Display)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "bevy_reflect", reflect(opaque))]
#[cfg_attr(feature = "bevy_reflect", reflect(Hash, PartialEq, Debug, Clone))]
#[repr(transparent)]
pub struct EntityGeneration(u32);
impl EntityGeneration {
/// Represents the first generation of an [`EntityIndex`].
pub const FIRST: Self = Self(0);
/// Non-wrapping difference between two generations after which a signed interpretation becomes negative.
const DIFF_MAX: u32 = 1u32 << 31;
/// Gets some bits that represent this value.
/// The bits are opaque and should not be regarded as meaningful.
#[inline(always)]
pub const fn to_bits(self) -> u32 {
self.0
}
/// Reconstruct an [`EntityGeneration`] previously destructured with [`EntityGeneration::to_bits`].
///
/// Only useful when applied to results from `to_bits` in the same instance of an application.
#[inline]
pub const fn from_bits(bits: u32) -> Self {
Self(bits)
}
/// Returns the [`EntityGeneration`] that would result from this many more `versions` of the corresponding [`EntityIndex`] from passing.
#[inline]
pub const fn after_versions(self, versions: u32) -> Self {
Self(self.0.wrapping_add(versions))
}
/// Identical to [`after_versions`](Self::after_versions) but also returns a `bool` indicating if,
/// after these `versions`, one such version could conflict with a previous one.
///
/// If this happens, this will no longer uniquely identify a version of an [`EntityIndex`].
/// This is called entity aliasing.
#[inline]
pub const fn after_versions_and_could_alias(self, versions: u32) -> (Self, bool) {
let raw = self.0.overflowing_add(versions);
(Self(raw.0), raw.1)
}
/// Compares two generations.
///
/// Generations that are later will be [`Greater`](core::cmp::Ordering::Greater) than earlier ones.
///
/// ```
/// # use bevy_ecs::entity::EntityGeneration;
/// # use core::cmp::Ordering;
/// let later_generation = EntityGeneration::FIRST.after_versions(400);
/// assert_eq!(EntityGeneration::FIRST.cmp_approx(&later_generation), Ordering::Less);
///
/// let (aliased, did_alias) = EntityGeneration::FIRST.after_versions(400).after_versions_and_could_alias(u32::MAX);
/// assert!(did_alias);
/// assert_eq!(EntityGeneration::FIRST.cmp_approx(&aliased), Ordering::Less);
/// ```
///
/// Ordering will be incorrect and [non-transitive](https://en.wikipedia.org/wiki/Transitive_relation)
/// for distant generations:
///
/// ```should_panic
/// # use bevy_ecs::entity::EntityGeneration;
/// # use core::cmp::Ordering;
/// let later_generation = EntityGeneration::FIRST.after_versions(3u32 << 31);
/// let much_later_generation = later_generation.after_versions(3u32 << 31);
///
/// // while these orderings are correct and pass assertions...
/// assert_eq!(EntityGeneration::FIRST.cmp_approx(&later_generation), Ordering::Less);
/// assert_eq!(later_generation.cmp_approx(&much_later_generation), Ordering::Less);
///
/// // ... this ordering is not and the assertion fails!
/// assert_eq!(EntityGeneration::FIRST.cmp_approx(&much_later_generation), Ordering::Less);
/// ```
///
/// Because of this, `EntityGeneration` does not implement `Ord`/`PartialOrd`.
#[inline]
pub const fn cmp_approx(&self, other: &Self) -> core::cmp::Ordering {
use core::cmp::Ordering;
match self.0.wrapping_sub(other.0) {
0 => Ordering::Equal,
1..Self::DIFF_MAX => Ordering::Greater,
_ => Ordering::Less,
}
}
}
/// Unique identifier for an entity in a [`World`].
/// Note that this is just an id, not the entity itself.
/// Further, the entity this id refers to may no longer exist in the [`World`].
/// For more information about entities, their ids, and how to use them, see the module [docs](crate::entity).
///
/// # Aliasing
///
/// Once an entity is despawned, it ceases to exist.
/// However, its [`Entity`] id is still present, and may still be contained in some data.
/// This becomes problematic because it is possible for a later entity to be spawned at the exact same id!
/// If this happens, which is rare but very possible, it will be logged.
///
/// Aliasing can happen without warning.
/// Holding onto a [`Entity`] id corresponding to an entity well after that entity was despawned can cause un-intuitive behavior for both ordering, and comparing in general.
/// To prevent these bugs, it is generally best practice to stop holding an [`Entity`] or [`EntityGeneration`] value as soon as you know it has been despawned.
/// If you must do otherwise, do not assume the [`Entity`] id corresponds to the same entity it originally did.
/// See [`EntityGeneration`]'s docs for more information about aliasing and why it occurs.
///
/// # Stability warning
/// For all intents and purposes, `Entity` should be treated as an opaque identifier. The internal bit
/// representation is liable to change from release to release as are the behaviors or performance
/// characteristics of any of its trait implementations (i.e. `Ord`, `Hash`, etc.). This means that changes in
/// `Entity`'s representation, though made readable through various functions on the type, are not considered
/// breaking changes under [SemVer].
///
/// In particular, directly serializing with `Serialize` and `Deserialize` make zero guarantee of long
/// term wire format compatibility. Changes in behavior will cause serialized `Entity` values persisted
/// to long term storage (i.e. disk, databases, etc.) will fail to deserialize upon being updated.
///
/// # Usage
///
/// This data type is returned by iterating a `Query` that has `Entity` as part of its query fetch type parameter ([learn more]).
/// It can also be obtained by calling [`EntityCommands::id`] or [`EntityWorldMut::id`].
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Component)]
/// # struct SomeComponent;
/// fn setup(mut commands: Commands) {
/// // Calling `spawn` returns `EntityCommands`.
/// let entity = commands.spawn(SomeComponent).id();
/// }
///
/// fn exclusive_system(world: &mut World) {
/// // Calling `spawn` returns `EntityWorldMut`.
/// let entity = world.spawn(SomeComponent).id();
/// }
/// #
/// # bevy_ecs::system::assert_is_system(setup);
/// # bevy_ecs::system::assert_is_system(exclusive_system);
/// ```
///
/// It can be used to refer to a specific entity to apply [`EntityCommands`], or to call [`Query::get`] (or similar methods) to access its components.
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// # #[derive(Component)]
/// # struct Expired;
/// #
/// fn dispose_expired_food(mut commands: Commands, query: Query<Entity, With<Expired>>) {
/// for food_entity in &query {
/// commands.entity(food_entity).despawn();
/// }
/// }
/// #
/// # bevy_ecs::system::assert_is_system(dispose_expired_food);
/// ```
///
/// [learn more]: crate::system::Query#entity-id-access
/// [`EntityCommands::id`]: crate::system::EntityCommands::id
/// [`EntityWorldMut::id`]: crate::world::EntityWorldMut::id
/// [`EntityCommands`]: crate::system::EntityCommands
/// [`Query::get`]: crate::system::Query::get
/// [`World`]: crate::world::World
/// [SemVer]: https://semver.org/
#[derive(Clone, Copy)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "bevy_reflect", reflect(opaque))]
#[cfg_attr(feature = "bevy_reflect", reflect(Hash, PartialEq, Debug, Clone))]
#[cfg_attr(
all(feature = "bevy_reflect", feature = "serialize"),
reflect(Serialize, Deserialize)
)]
// Alignment repr necessary to allow LLVM to better output
// optimized codegen for `to_bits`, `PartialEq` and `Ord`.
#[repr(C, align(8))]
pub struct Entity {
// Do not reorder the fields here. The ordering is explicitly used by repr(C)
// to make this struct equivalent to a u64.
#[cfg(target_endian = "little")]
index: EntityIndex,
generation: EntityGeneration,
#[cfg(target_endian = "big")]
index: EntityIndex,
}
// By not short-circuiting in comparisons, we get better codegen.
// See <https://github.com/rust-lang/rust/issues/117800>
impl PartialEq for Entity {
#[inline]
fn eq(&self, other: &Entity) -> bool {
// By using `to_bits`, the codegen can be optimized out even
// further potentially. Relies on the correct alignment/field
// order of `Entity`.
self.to_bits() == other.to_bits()
}
}
impl Eq for Entity {}
// The derive macro codegen output is not optimal and can't be optimized as well
// by the compiler. This impl resolves the issue of non-optimal codegen by relying
// on comparing against the bit representation of `Entity` instead of comparing
// the fields. The result is then LLVM is able to optimize the codegen for Entity
// far beyond what the derive macro can.
// See <https://github.com/rust-lang/rust/issues/106107>
impl PartialOrd for Entity {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
// Make use of our `Ord` impl to ensure optimal codegen output
Some(self.cmp(other))
}
}
// The derive macro codegen output is not optimal and can't be optimized as well
// by the compiler. This impl resolves the issue of non-optimal codegen by relying
// on comparing against the bit representation of `Entity` instead of comparing
// the fields. The result is then LLVM is able to optimize the codegen for Entity
// far beyond what the derive macro can.
// See <https://github.com/rust-lang/rust/issues/106107>
impl Ord for Entity {
#[inline]
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
// This will result in better codegen for ordering comparisons, plus
// avoids pitfalls with regards to macro codegen relying on property
// position when we want to compare against the bit representation.
self.to_bits().cmp(&other.to_bits())
}
}
impl Hash for Entity {
#[inline]
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.to_bits().hash(state);
}
}
impl Entity {
/// Creates a new instance with the given index and generation.
#[inline(always)]
pub const fn from_index_and_generation(
index: EntityIndex,
generation: EntityGeneration,
) -> Entity {
Self { index, generation }
}
/// An entity ID with a placeholder value. This may or may not correspond to an actual entity,
/// and should be overwritten by a new value before being used.
///
/// ## Examples
///
/// Initializing a collection (e.g. `array` or `Vec`) with a known size:
///
/// ```no_run
/// # use bevy_ecs::prelude::*;
/// // Create a new array of size 10 filled with invalid entity ids.
/// let mut entities: [Entity; 10] = [Entity::PLACEHOLDER; 10];
///
/// // ... replace the entities with valid ones.
/// ```
///
/// Deriving [`Reflect`] for a component that has an `Entity` field:
///
/// ```no_run
/// # use bevy_ecs::{prelude::*, component::*};
/// # use bevy_reflect::Reflect;
/// #[derive(Reflect, Component)]
/// #[reflect(Component)]
/// pub struct MyStruct {
/// pub entity: Entity,
/// }
///
/// impl FromWorld for MyStruct {
/// fn from_world(_world: &mut World) -> Self {
/// Self {
/// entity: Entity::PLACEHOLDER,
/// }
/// }
/// }
/// ```
pub const PLACEHOLDER: Self = Self::from_index(EntityIndex::PLACEHOLDER);
/// Creates a new entity ID with the specified `index` and an unspecified generation.
///
/// # Note
///
/// Spawning a specific `entity` value is __rarely the right choice__. Most apps should favor
/// [`Commands::spawn`](crate::system::Commands::spawn). This method should generally
/// only be used for sharing entities across apps, and only when they have a scheme
/// worked out to share an index space (which doesn't happen by default).
///
/// In general, one should not try to synchronize the ECS by attempting to ensure that
/// `Entity` lines up between instances, but instead insert a secondary identifier as
/// a component.
#[inline(always)]
pub const fn from_index(index: EntityIndex) -> Entity {
Self::from_index_and_generation(index, EntityGeneration::FIRST)
}
/// This is equivalent to [`from_index`](Self::from_index) except that it takes a `u32` instead of an [`EntityIndex`].
///
/// Returns `None` if the index is `u32::MAX`.
#[inline(always)]
pub const fn from_raw_u32(index: u32) -> Option<Entity> {
match NonMaxU32::new(index) {
Some(index) => Some(Self::from_index(EntityIndex::new(index))),
None => None,
}
}
/// Convert to a form convenient for passing outside of rust.
///
/// Only useful for identifying entities within the same instance of an application. Do not use
/// for serialization between runs.
///
/// No particular structure is guaranteed for the returned bits.
#[inline(always)]
pub const fn to_bits(self) -> u64 {
self.index.to_bits() as u64 | ((self.generation.to_bits() as u64) << 32)
}
/// Reconstruct an `Entity` previously destructured with [`Entity::to_bits`].
///
/// Only useful when applied to results from `to_bits` in the same instance of an application.
///
/// # Panics
///
/// This method will likely panic if given `u64` values that did not come from [`Entity::to_bits`].
#[inline]
pub const fn from_bits(bits: u64) -> Self {
if let Some(id) = Self::try_from_bits(bits) {
id
} else {
panic!("Attempted to initialize invalid bits as an entity")
}
}
/// Reconstruct an `Entity` previously destructured with [`Entity::to_bits`].
///
/// Only useful when applied to results from `to_bits` in the same instance of an application.
///
/// This method is the fallible counterpart to [`Entity::from_bits`].
#[inline(always)]
pub const fn try_from_bits(bits: u64) -> Option<Self> {
let raw_index = bits as u32;
let raw_gen = (bits >> 32) as u32;
if let Some(index) = EntityIndex::try_from_bits(raw_index) {
Some(Self {
index,
generation: EntityGeneration::from_bits(raw_gen),
})
} else {
None
}
}
/// Return a transiently unique identifier.
/// See also [`EntityIndex`].
///
/// No two simultaneously-live entities share the same index, but dead entities' indices may collide
/// with both live and dead entities. Useful for compactly representing entities within a
/// specific snapshot of the world, such as when serializing.
#[inline]
pub const fn index(self) -> EntityIndex {
self.index
}
/// Equivalent to `self.index().index()`. See [`Self::index`] for details.
#[inline]
pub const fn index_u32(self) -> u32 {
self.index.index()
}
/// Returns the generation of this Entity's index. The generation is incremented each time an
/// entity with a given index is despawned. This serves as a "count" of the number of times a
/// given index has been reused (index, generation) pairs uniquely identify a given Entity.
#[inline]
pub const fn generation(self) -> EntityGeneration {
self.generation
}
}
#[cfg(feature = "serialize")]
impl Serialize for Entity {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_u64(self.to_bits())
}
}
#[cfg(feature = "serialize")]
impl<'de> Deserialize<'de> for Entity {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
let id: u64 = Deserialize::deserialize(deserializer)?;
Entity::try_from_bits(id)
.ok_or_else(|| D::Error::custom("Attempting to deserialize an invalid entity."))
}
}
/// Outputs the short entity identifier, including the index and generation.
///
/// This takes the format: `{index}v{generation}`.
///
/// For [`Entity::PLACEHOLDER`], this outputs `PLACEHOLDER`.
///
/// For a unique [`u64`] representation, use [`Entity::to_bits`].
impl fmt::Debug for Entity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
/// Outputs the short entity identifier, including the index and generation.
///
/// This takes the format: `{index}v{generation}`.
///
/// For [`Entity::PLACEHOLDER`], this outputs `PLACEHOLDER`.
impl fmt::Display for Entity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self == &Self::PLACEHOLDER {
f.pad("PLACEHOLDER")
} else {
f.pad(&alloc::fmt::format(format_args!(
"{}v{}",
self.index(),
self.generation()
)))
}
}
}
impl SparseSetIndex for Entity {
#[inline]
fn sparse_set_index(&self) -> usize {
self.index().sparse_set_index()
}
#[inline]
fn get_sparse_set_index(value: usize) -> Self {
Entity::from_index(EntityIndex::get_sparse_set_index(value))
}
}
/// Allocates [`Entity`] ids uniquely.
/// This is used in [`World::spawn_at`](crate::world::World::spawn_at) and [`World::despawn_no_free`](crate::world::World::despawn_no_free) to track entity ids no longer in use.
/// Allocating is fully concurrent and can be done from multiple threads.
///
/// Conceptually, this is a collection of [`Entity`] ids who's [`EntityIndex`] is despawned and who's [`EntityGeneration`] is the most recent.
/// See the module docs for how these ids and this allocator participate in the life cycle of an entity.
#[derive(Default, Debug)]
pub struct EntityAllocator {
/// All the entities to reuse.
/// This is a buffer, which contains an array of [`Entity`] ids to hand out.
/// The next id to hand out is tracked by `free_len`.
free: Vec<Entity>,
/// This is continually subtracted from.
/// If it wraps to a very large number, it will be outside the bounds of `free`,
/// and a new index will be needed.
free_len: AtomicUsize,
/// This is the next "fresh" index to hand out.
/// If there are no indices to reuse, this index, which has a generation of 0, is the next to return.
next_index: AtomicU32,
}
impl EntityAllocator {
/// Restarts the allocator.
pub(crate) fn restart(&mut self) {
self.free.clear();
*self.free_len.get_mut() = 0;
*self.next_index.get_mut() = 0;
}
/// This allows `freed` to be retrieved from [`alloc`](Self::alloc), etc.
/// Freeing an [`Entity`] such that one [`EntityIndex`] is in the allocator in multiple places can cause panics when spawning the allocated entity.
/// Additionally, to differentiate versions of an [`Entity`], updating the [`EntityGeneration`] before freeing is a good idea
/// (but not strictly necessary if you don't mind [`Entity`] id aliasing.)
pub fn free(&mut self, freed: Entity) {
let expected_len = *self.free_len.get_mut();
if expected_len > self.free.len() {
self.free.clear();
} else {
self.free.truncate(expected_len);
}
self.free.push(freed);
*self.free_len.get_mut() = self.free.len();
}
/// Allocates some [`Entity`].
/// The result could have come from a [`free`](Self::free) or be a brand new [`EntityIndex`].
///
/// The returned entity is valid and unique, but it is not yet spawned.
/// Using the id as if it were spawned may produce errors.
/// It can not be queried, and it has no [`EntityLocation`].
/// See module [docs](crate::entity) for more information about entity validity vs spawning.
///
/// This is different from empty entities, which are spawned and
/// just happen to have no components.
///
/// These ids must be used; otherwise, they will be forgotten.
/// For example, the result must be eventually used to either spawn an entity or be [`free`](Self::free)d.
///
/// # Panics
///
/// If there are no more entities available, this panics.
///
///
/// # Example
///
/// This is particularly useful when spawning entities in special ways.
/// For example, [`Commands`](crate::system::Commands) uses this to allocate an entity and [`spawn_at`](crate::world::World::spawn_at) it later.
/// But remember, since this entity is not queryable and is not discoverable, losing the returned [`Entity`] effectively leaks it, never to be used again!
///
/// ```
/// # use bevy_ecs::{prelude::*};
/// let mut world = World::new();
/// let entity = world.entities_allocator().alloc();
/// // wait as long as you like
/// let entity_access = world.spawn_empty_at(entity).unwrap(); // or spawn_at(entity, my_bundle)
/// // treat it as a normal entity
/// entity_access.despawn();
/// ```
///
| 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/map_entities.rs | crates/bevy_ecs/src/entity/map_entities.rs | pub use bevy_ecs_macros::MapEntities;
use indexmap::{IndexMap, IndexSet};
use crate::{
entity::{hash_map::EntityHashMap, Entity},
world::World,
};
use alloc::{
collections::{BTreeMap, BTreeSet, VecDeque},
vec::Vec,
};
use bevy_platform::collections::{HashMap, HashSet};
use core::{
hash::{BuildHasher, Hash},
mem,
};
use smallvec::SmallVec;
use super::EntityIndexSet;
/// Operation to map all contained [`Entity`] fields in a type to new values.
///
/// As entity IDs are valid only for the [`World`] they're sourced from, using [`Entity`]
/// as references in components copied from another world will be invalid. This trait
/// allows defining custom mappings for these references via [`EntityMappers`](EntityMapper), which
/// inject the entity mapping strategy between your `MapEntities` type and the current world
/// (usually by using an [`EntityHashMap<Entity>`] between source entities and entities in the
/// current world).
///
/// Components use [`Component::map_entities`](crate::component::Component::map_entities) to map
/// entities in the context of scenes and entity cloning, which generally uses [`MapEntities`] internally
/// to map each field (see those docs for usage).
///
/// [`HashSet<Entity>`]: bevy_platform::collections::HashSet
///
/// ## Example
///
/// ```
/// use bevy_ecs::prelude::*;
/// use bevy_ecs::entity::MapEntities;
///
/// #[derive(Component)]
/// struct Spring {
/// a: Entity,
/// b: Entity,
/// }
///
/// impl MapEntities for Spring {
/// fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) {
/// self.a = entity_mapper.get_mapped(self.a);
/// self.b = entity_mapper.get_mapped(self.b);
/// }
/// }
/// ```
pub trait MapEntities {
/// Updates all [`Entity`] references stored inside using `entity_mapper`.
///
/// Implementers should look up any and all [`Entity`] values stored within `self` and
/// update them to the mapped values via `entity_mapper`.
fn map_entities<E: EntityMapper>(&mut self, entity_mapper: &mut E);
}
impl MapEntities for Entity {
fn map_entities<E: EntityMapper>(&mut self, entity_mapper: &mut E) {
*self = entity_mapper.get_mapped(*self);
}
}
impl<T: MapEntities> MapEntities for Option<T> {
fn map_entities<E: EntityMapper>(&mut self, entity_mapper: &mut E) {
if let Some(entities) = self {
entities.map_entities(entity_mapper);
}
}
}
impl<K: MapEntities + Eq + Hash, V: MapEntities, S: BuildHasher + Default> MapEntities
for HashMap<K, V, S>
{
fn map_entities<E: EntityMapper>(&mut self, entity_mapper: &mut E) {
*self = self
.drain()
.map(|(mut key_entities, mut value_entities)| {
key_entities.map_entities(entity_mapper);
value_entities.map_entities(entity_mapper);
(key_entities, value_entities)
})
.collect();
}
}
impl<T: MapEntities + Eq + Hash, S: BuildHasher + Default> MapEntities for HashSet<T, S> {
fn map_entities<E: EntityMapper>(&mut self, entity_mapper: &mut E) {
*self = self
.drain()
.map(|mut entities| {
entities.map_entities(entity_mapper);
entities
})
.collect();
}
}
impl<K: MapEntities + Eq + Hash, V: MapEntities, S: BuildHasher + Default> MapEntities
for IndexMap<K, V, S>
{
fn map_entities<E: EntityMapper>(&mut self, entity_mapper: &mut E) {
*self = self
.drain(..)
.map(|(mut key_entities, mut value_entities)| {
key_entities.map_entities(entity_mapper);
value_entities.map_entities(entity_mapper);
(key_entities, value_entities)
})
.collect();
}
}
impl<T: MapEntities + Eq + Hash, S: BuildHasher + Default> MapEntities for IndexSet<T, S> {
fn map_entities<E: EntityMapper>(&mut self, entity_mapper: &mut E) {
*self = self
.drain(..)
.map(|mut entities| {
entities.map_entities(entity_mapper);
entities
})
.collect();
}
}
impl MapEntities for EntityIndexSet {
fn map_entities<E: EntityMapper>(&mut self, entity_mapper: &mut E) {
*self = self
.drain(..)
.map(|e| entity_mapper.get_mapped(e))
.collect();
}
}
impl<K: MapEntities + Ord, V: MapEntities> MapEntities for BTreeMap<K, V> {
fn map_entities<E: EntityMapper>(&mut self, entity_mapper: &mut E) {
*self = mem::take(self)
.into_iter()
.map(|(mut key_entities, mut value_entities)| {
key_entities.map_entities(entity_mapper);
value_entities.map_entities(entity_mapper);
(key_entities, value_entities)
})
.collect();
}
}
impl<T: MapEntities + Ord> MapEntities for BTreeSet<T> {
fn map_entities<E: EntityMapper>(&mut self, entity_mapper: &mut E) {
*self = mem::take(self)
.into_iter()
.map(|mut entities| {
entities.map_entities(entity_mapper);
entities
})
.collect();
}
}
impl<T: MapEntities, const N: usize> MapEntities for [T; N] {
fn map_entities<E: EntityMapper>(&mut self, entity_mapper: &mut E) {
for entities in self.iter_mut() {
entities.map_entities(entity_mapper);
}
}
}
impl<T: MapEntities> MapEntities for Vec<T> {
fn map_entities<E: EntityMapper>(&mut self, entity_mapper: &mut E) {
for entities in self.iter_mut() {
entities.map_entities(entity_mapper);
}
}
}
impl<T: MapEntities> MapEntities for VecDeque<T> {
fn map_entities<E: EntityMapper>(&mut self, entity_mapper: &mut E) {
for entities in self.iter_mut() {
entities.map_entities(entity_mapper);
}
}
}
impl<T: MapEntities, A: smallvec::Array<Item = T>> MapEntities for SmallVec<A> {
fn map_entities<E: EntityMapper>(&mut self, entity_mapper: &mut E) {
for entities in self.iter_mut() {
entities.map_entities(entity_mapper);
}
}
}
/// An implementor of this trait knows how to map an [`Entity`] into another [`Entity`].
///
/// Usually this is done by using an [`EntityHashMap<Entity>`] to map source entities
/// (mapper inputs) to the current world's entities (mapper outputs).
///
/// More generally, this can be used to map [`Entity`] references between any two [`Worlds`](World).
///
/// This is used by [`MapEntities`] implementers.
///
/// ## Example
///
/// ```
/// # use bevy_ecs::entity::{Entity, EntityMapper};
/// # use bevy_ecs::entity::EntityHashMap;
/// #
/// pub struct SimpleEntityMapper {
/// map: EntityHashMap<Entity>,
/// }
///
/// // Example implementation of EntityMapper where we map an entity to another entity if it exists
/// // in the underlying `EntityHashMap`, otherwise we just return the original entity.
/// impl EntityMapper for SimpleEntityMapper {
/// fn get_mapped(&mut self, entity: Entity) -> Entity {
/// self.map.get(&entity).copied().unwrap_or(entity)
/// }
///
/// fn set_mapped(&mut self, source: Entity, target: Entity) {
/// self.map.insert(source, target);
/// }
/// }
/// ```
pub trait EntityMapper {
/// Returns the "target" entity that maps to the given `source`.
fn get_mapped(&mut self, source: Entity) -> Entity;
/// Maps the `target` entity to the given `source`. For some implementations this might not actually determine the result
/// of [`EntityMapper::get_mapped`].
fn set_mapped(&mut self, source: Entity, target: Entity);
}
impl EntityMapper for () {
#[inline]
fn get_mapped(&mut self, source: Entity) -> Entity {
source
}
#[inline]
fn set_mapped(&mut self, _source: Entity, _target: Entity) {}
}
impl EntityMapper for (Entity, Entity) {
#[inline]
fn get_mapped(&mut self, source: Entity) -> Entity {
if source == self.0 {
self.1
} else {
source
}
}
fn set_mapped(&mut self, _source: Entity, _target: Entity) {}
}
impl EntityMapper for &mut dyn EntityMapper {
fn get_mapped(&mut self, source: Entity) -> Entity {
(*self).get_mapped(source)
}
fn set_mapped(&mut self, source: Entity, target: Entity) {
(*self).set_mapped(source, target);
}
}
impl EntityMapper for SceneEntityMapper<'_> {
/// Returns the corresponding mapped entity or reserves a new dead entity ID in the current world if it is absent.
fn get_mapped(&mut self, source: Entity) -> Entity {
if let Some(&mapped) = self.map.get(&source) {
return mapped;
}
// this new entity reference is specifically designed to never represent any living entity
let new = Entity::from_index_and_generation(
self.dead_start.index(),
self.dead_start.generation.after_versions(self.generations),
);
self.generations = self.generations.wrapping_add(1);
self.map.insert(source, new);
new
}
fn set_mapped(&mut self, source: Entity, target: Entity) {
self.map.insert(source, target);
}
}
impl EntityMapper for EntityHashMap<Entity> {
/// Returns the corresponding mapped entity or returns `entity` if there is no mapped entity
fn get_mapped(&mut self, source: Entity) -> Entity {
self.get(&source).cloned().unwrap_or(source)
}
fn set_mapped(&mut self, source: Entity, target: Entity) {
self.insert(source, target);
}
}
/// A wrapper for [`EntityHashMap<Entity>`], augmenting it with the ability to allocate new [`Entity`] references in a destination
/// world. These newly allocated references are guaranteed to never point to any living entity in that world.
///
/// References are allocated by returning increasing generations starting from an internally initialized base
/// [`Entity`]. After it is finished being used, this entity is despawned and the requisite number of generations reserved.
pub struct SceneEntityMapper<'m> {
/// A mapping from one set of entities to another.
///
/// This is typically used to coordinate data transfer between sets of entities, such as between a scene and the world
/// or over the network. This is required as [`Entity`] identifiers are opaque; you cannot and do not want to reuse
/// identifiers directly.
///
/// On its own, a [`EntityHashMap<Entity>`] is not capable of allocating new entity identifiers, which is needed to map references
/// to entities that lie outside the source entity set. This functionality can be accessed through [`SceneEntityMapper::world_scope()`].
map: &'m mut EntityHashMap<Entity>,
/// A base [`Entity`] used to allocate new references.
dead_start: Entity,
/// The number of generations this mapper has allocated thus far.
generations: u32,
}
impl<'m> SceneEntityMapper<'m> {
/// Gets a reference to the underlying [`EntityHashMap<Entity>`].
pub fn get_map(&'m self) -> &'m EntityHashMap<Entity> {
self.map
}
/// Gets a mutable reference to the underlying [`EntityHashMap<Entity>`].
pub fn get_map_mut(&'m mut self) -> &'m mut EntityHashMap<Entity> {
self.map
}
/// Creates a new [`SceneEntityMapper`], spawning a temporary base [`Entity`] in the provided [`World`]
pub fn new(map: &'m mut EntityHashMap<Entity>, world: &World) -> Self {
Self {
map,
dead_start: world.allocator.alloc(),
generations: 0,
}
}
/// Reserves the allocated references to dead entities within the world. This frees the temporary base
/// [`Entity`] while reserving extra generations. Because this makes the [`SceneEntityMapper`] unable to
/// safely allocate any more references, this method takes ownership of `self` in order to render it unusable.
pub fn finish(self, world: &mut World) {
// SAFETY: We never constructed the entity and never released it for something else to construct.
let reuse_row = unsafe {
world
.entities
.mark_free(self.dead_start.index(), self.generations)
};
world.allocator.free(reuse_row);
}
/// Creates an [`SceneEntityMapper`] from a provided [`World`] and [`EntityHashMap<Entity>`], then calls the
/// provided function with it. This allows one to allocate new entity references in this [`World`] that are
/// guaranteed to never point at a living entity now or in the future. This functionality is useful for safely
/// mapping entity identifiers that point at entities outside the source world. The passed function, `f`, is called
/// within the scope of this world. Its return value is then returned from `world_scope` as the generic type
/// parameter `R`.
pub fn world_scope<R>(
entity_map: &'m mut EntityHashMap<Entity>,
world: &mut World,
f: impl FnOnce(&mut World, &mut Self) -> R,
) -> R {
let mut mapper = Self::new(entity_map, world);
let result = f(world, &mut mapper);
mapper.finish(world);
result
}
}
#[cfg(test)]
mod tests {
use crate::{
entity::{Entity, EntityHashMap, EntityMapper, SceneEntityMapper},
world::World,
};
#[test]
fn entity_mapper() {
let mut map = EntityHashMap::default();
let mut world = World::new();
let mut mapper = SceneEntityMapper::new(&mut map, &world);
let mapped_ent = Entity::from_raw_u32(1).unwrap();
let dead_ref = mapper.get_mapped(mapped_ent);
assert_eq!(
dead_ref,
mapper.get_mapped(mapped_ent),
"should persist the allocated mapping from the previous line"
);
assert_eq!(
mapper.get_mapped(Entity::from_raw_u32(2).unwrap()).index(),
dead_ref.index(),
"should re-use the same index for further dead refs"
);
mapper.finish(&mut world);
// Next allocated entity should be a further generation on the same index
let entity = world.spawn_empty().id();
assert_eq!(entity.index(), dead_ref.index());
assert!(entity
.generation()
.cmp_approx(&dead_ref.generation())
.is_gt());
}
#[test]
fn world_scope_reserves_generations() {
let mut map = EntityHashMap::default();
let mut world = World::new();
let dead_ref = SceneEntityMapper::world_scope(&mut map, &mut world, |_, mapper| {
mapper.get_mapped(Entity::from_raw_u32(0).unwrap())
});
// Next allocated entity should be a further generation on the same index
let entity = world.spawn_empty().id();
assert_eq!(entity.index(), dead_ref.index());
assert!(entity
.generation()
.cmp_approx(&dead_ref.generation())
.is_gt());
}
}
| 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/entity/hash.rs | crates/bevy_ecs/src/entity/hash.rs | use core::hash::{BuildHasher, Hasher};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
/// A [`BuildHasher`] that results in a [`EntityHasher`].
#[derive(Debug, Default, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Default, Clone))]
pub struct EntityHash;
impl BuildHasher for EntityHash {
type Hasher = EntityHasher;
fn build_hasher(&self) -> Self::Hasher {
Self::Hasher::default()
}
}
/// A very fast hash that is only designed to work on generational indices
/// like [`Entity`](super::Entity). It will panic if attempting to hash a type containing
/// non-u64 fields.
///
/// This is heavily optimized for typical cases, where you have mostly live
/// entities, and works particularly well for contiguous indices.
///
/// If you have an unusual case -- say all your indices are multiples of 256
/// or most of the entities are dead generations -- then you might want also to
/// try [`DefaultHasher`](bevy_platform::hash::DefaultHasher) for a slower hash
/// computation but fewer lookup conflicts.
#[derive(Debug, Default)]
pub struct EntityHasher {
hash: u64,
}
impl Hasher for EntityHasher {
#[inline]
fn finish(&self) -> u64 {
self.hash
}
fn write(&mut self, _bytes: &[u8]) {
panic!("EntityHasher can only hash u64 fields.");
}
#[inline]
fn write_u64(&mut self, bits: u64) {
// SwissTable (and thus `hashbrown`) cares about two things from the hash:
// - H1: low bits (masked by `2βΏ-1`) to pick the slot in which to store the item
// - H2: high 7 bits are used to SIMD optimize hash collision probing
// For more see <https://abseil.io/about/design/swisstables#metadata-layout>
// This hash function assumes that the entity ids are still well-distributed,
// so for H1 leaves the entity id alone in the low bits so that id locality
// will also give memory locality for things spawned together.
// For H2, take advantage of the fact that while multiplication doesn't
// spread entropy to the low bits, it's incredibly good at spreading it
// upward, which is exactly where we need it the most.
// While this does include the generation in the output, it doesn't do so
// *usefully*. H1 won't care until you have over 3 billion entities in
// the table, and H2 won't care until something hits generation 33 million.
// Thus the comment suggesting that this is best for live entities,
// where there won't be generation conflicts where it would matter.
// The high 32 bits of this are β
Ο for Fibonacci hashing. That works
// particularly well for hashing for the same reason as described in
// <https://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/>
// It loses no information because it has a modular inverse.
// (Specifically, `0x144c_bc89_u32 * 0x9e37_79b9_u32 == 1`.)
//
// The low 32 bits make that part of the just product a pass-through.
const UPPER_PHI: u64 = 0x9e37_79b9_0000_0001;
// This is `(MAGIC * index + generation) << 32 + index`, in a single instruction.
self.hash = bits.wrapping_mul(UPPER_PHI);
}
}
| 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/entity/unique_slice.rs | crates/bevy_ecs/src/entity/unique_slice.rs | //! A wrapper around entity slices with a uniqueness invariant.
use core::{
array::TryFromSliceError,
borrow::Borrow,
cmp::Ordering,
fmt::Debug,
iter::FusedIterator,
ops::{
Bound, Deref, Index, IndexMut, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo,
RangeToInclusive,
},
ptr,
slice::{self, SliceIndex},
};
use alloc::{
borrow::{Cow, ToOwned},
boxed::Box,
collections::VecDeque,
rc::Rc,
vec::Vec,
};
use bevy_platform::sync::Arc;
use super::{
unique_vec::{self, UniqueEntityEquivalentVec},
Entity, EntityEquivalent, EntitySet, EntitySetIterator, FromEntitySetIterator,
UniqueEntityEquivalentArray, UniqueEntityIter,
};
/// A slice that contains only unique entities.
///
/// This can be obtained by slicing [`UniqueEntityEquivalentVec`].
///
/// When `T` is [`Entity`], use [`UniqueEntitySlice`].
#[repr(transparent)]
#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct UniqueEntityEquivalentSlice<T: EntityEquivalent>([T]);
/// A slice that contains only unique [`Entity`].
///
/// This is the default case of a [`UniqueEntityEquivalentSlice`].
pub type UniqueEntitySlice = UniqueEntityEquivalentSlice<Entity>;
impl<T: EntityEquivalent> UniqueEntityEquivalentSlice<T> {
/// Constructs a `UniqueEntityEquivalentSlice` from a [`&[T]`] unsafely.
///
/// # Safety
///
/// `slice` must contain only unique elements.
pub const unsafe fn from_slice_unchecked(slice: &[T]) -> &Self {
// SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
unsafe { &*(ptr::from_ref(slice) as *const Self) }
}
/// Constructs a `UniqueEntityEquivalentSlice` from a [`&mut [T]`] unsafely.
///
/// # Safety
///
/// `slice` must contain only unique elements.
pub const unsafe fn from_slice_unchecked_mut(slice: &mut [T]) -> &mut Self {
// SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
unsafe { &mut *(ptr::from_mut(slice) as *mut Self) }
}
/// Casts to `self` to a standard slice.
pub const fn as_inner(&self) -> &[T] {
&self.0
}
/// Constructs a `UniqueEntityEquivalentSlice` from a [`Box<[T]>`] unsafely.
///
/// # Safety
///
/// `slice` must contain only unique elements.
pub unsafe fn from_boxed_slice_unchecked(slice: Box<[T]>) -> Box<Self> {
// SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
unsafe { Box::from_raw(Box::into_raw(slice) as *mut Self) }
}
/// Casts `self` to the inner slice.
pub fn into_boxed_inner(self: Box<Self>) -> Box<[T]> {
// SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
unsafe { Box::from_raw(Box::into_raw(self) as *mut [T]) }
}
/// Constructs a `UniqueEntityEquivalentSlice` from a [`Arc<[T]>`] unsafely.
///
/// # Safety
///
/// `slice` must contain only unique elements.
pub unsafe fn from_arc_slice_unchecked(slice: Arc<[T]>) -> Arc<Self> {
// SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
unsafe { Arc::from_raw(Arc::into_raw(slice) as *mut Self) }
}
/// Casts `self` to the inner slice.
pub fn into_arc_inner(this: Arc<Self>) -> Arc<[T]> {
// SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
unsafe { Arc::from_raw(Arc::into_raw(this) as *mut [T]) }
}
// Constructs a `UniqueEntityEquivalentSlice` from a [`Rc<[T]>`] unsafely.
///
/// # Safety
///
/// `slice` must contain only unique elements.
pub unsafe fn from_rc_slice_unchecked(slice: Rc<[T]>) -> Rc<Self> {
// SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
unsafe { Rc::from_raw(Rc::into_raw(slice) as *mut Self) }
}
/// Casts `self` to the inner slice.
pub fn into_rc_inner(self: Rc<Self>) -> Rc<[T]> {
// SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
unsafe { Rc::from_raw(Rc::into_raw(self) as *mut [T]) }
}
/// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
///
/// Equivalent to [`[T]::split_first`](slice::split_first).
pub const fn split_first(&self) -> Option<(&T, &Self)> {
let Some((first, rest)) = self.0.split_first() else {
return None;
};
// SAFETY: All elements in the original slice are unique.
Some((first, unsafe { Self::from_slice_unchecked(rest) }))
}
/// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
///
/// Equivalent to [`[T]::split_last`](slice::split_last).
pub const fn split_last(&self) -> Option<(&T, &Self)> {
let Some((last, rest)) = self.0.split_last() else {
return None;
};
// SAFETY: All elements in the original slice are unique.
Some((last, unsafe { Self::from_slice_unchecked(rest) }))
}
/// Returns an array reference to the first `N` items in the slice.
///
/// Equivalent to [`[T]::first_chunk`](slice::first_chunk).
pub const fn first_chunk<const N: usize>(&self) -> Option<&UniqueEntityEquivalentArray<T, N>> {
let Some(chunk) = self.0.first_chunk() else {
return None;
};
// SAFETY: All elements in the original slice are unique.
Some(unsafe { UniqueEntityEquivalentArray::from_array_ref_unchecked(chunk) })
}
/// Returns an array reference to the first `N` items in the slice and the remaining slice.
///
/// Equivalent to [`[T]::split_first_chunk`](slice::split_first_chunk).
pub const fn split_first_chunk<const N: usize>(
&self,
) -> Option<(
&UniqueEntityEquivalentArray<T, N>,
&UniqueEntityEquivalentSlice<T>,
)> {
let Some((chunk, rest)) = self.0.split_first_chunk() else {
return None;
};
// SAFETY: All elements in the original slice are unique.
unsafe {
Some((
UniqueEntityEquivalentArray::from_array_ref_unchecked(chunk),
Self::from_slice_unchecked(rest),
))
}
}
/// Returns an array reference to the last `N` items in the slice and the remaining slice.
///
/// Equivalent to [`[T]::split_last_chunk`](slice::split_last_chunk).
pub const fn split_last_chunk<const N: usize>(
&self,
) -> Option<(
&UniqueEntityEquivalentSlice<T>,
&UniqueEntityEquivalentArray<T, N>,
)> {
let Some((rest, chunk)) = self.0.split_last_chunk() else {
return None;
};
// SAFETY: All elements in the original slice are unique.
unsafe {
Some((
Self::from_slice_unchecked(rest),
UniqueEntityEquivalentArray::from_array_ref_unchecked(chunk),
))
}
}
/// Returns an array reference to the last `N` items in the slice.
///
/// Equivalent to [`[T]::last_chunk`](slice::last_chunk).
pub const fn last_chunk<const N: usize>(&self) -> Option<&UniqueEntityEquivalentArray<T, N>> {
let Some(chunk) = self.0.last_chunk() else {
return None;
};
// SAFETY: All elements in the original slice are unique.
Some(unsafe { UniqueEntityEquivalentArray::from_array_ref_unchecked(chunk) })
}
/// Returns a reference to a subslice.
///
/// Equivalent to the range functionality of [`[T]::get`].
///
/// Note that only the inner [`[T]::get`] supports indexing with a [`usize`].
///
/// [`[T]::get`]: `slice::get`
pub fn get<I>(&self, index: I) -> Option<&Self>
where
Self: Index<I>,
I: SliceIndex<[T], Output = [T]>,
{
self.0.get(index).map(|slice|
// SAFETY: All elements in the original slice are unique.
unsafe { Self::from_slice_unchecked(slice) })
}
/// Returns a mutable reference to a subslice.
///
/// Equivalent to the range functionality of [`[T]::get_mut`].
///
/// Note that `UniqueEntityEquivalentSlice::get_mut` cannot be called with a [`usize`].
///
/// [`[T]::get_mut`]: `slice::get_mut`s
pub fn get_mut<I>(&mut self, index: I) -> Option<&mut Self>
where
Self: Index<I>,
I: SliceIndex<[T], Output = [T]>,
{
self.0.get_mut(index).map(|slice|
// SAFETY: All elements in the original slice are unique.
unsafe { Self::from_slice_unchecked_mut(slice) })
}
/// Returns a reference to a subslice, without doing bounds checking.
///
/// Equivalent to the range functionality of [`[T]::get_unchecked`].
///
/// Note that only the inner [`[T]::get_unchecked`] supports indexing with a [`usize`].
///
/// # Safety
///
/// `index` must be safe to use with [`[T]::get_unchecked`]
///
/// [`[T]::get_unchecked`]: `slice::get_unchecked`
pub unsafe fn get_unchecked<I>(&self, index: I) -> &Self
where
Self: Index<I>,
I: SliceIndex<[T], Output = [T]>,
{
// SAFETY: All elements in the original slice are unique.
unsafe { Self::from_slice_unchecked(self.0.get_unchecked(index)) }
}
/// Returns a mutable reference to a subslice, without doing bounds checking.
///
/// Equivalent to the range functionality of [`[T]::get_unchecked_mut`].
///
/// Note that `UniqueEntityEquivalentSlice::get_unchecked_mut` cannot be called with an index.
///
/// # Safety
///
/// `index` must be safe to use with [`[T]::get_unchecked_mut`]
///
/// [`[T]::get_unchecked_mut`]: `slice::get_unchecked_mut`
pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut Self
where
Self: Index<I>,
I: SliceIndex<[T], Output = [T]>,
{
// SAFETY: All elements in the original slice are unique.
unsafe { Self::from_slice_unchecked_mut(self.0.get_unchecked_mut(index)) }
}
/// Returns an unsafe mutable pointer to the slice's buffer.
pub const fn as_mut_ptr(&mut self) -> *mut T {
self.0.as_mut_ptr()
}
/// Returns the two unsafe mutable pointers spanning the slice.
pub const fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
self.0.as_mut_ptr_range()
}
/// Swaps two elements in the slice.
pub fn swap(&mut self, a: usize, b: usize) {
self.0.swap(a, b);
}
/// Reverses the order of elements in the slice, in place.
pub fn reverse(&mut self) {
self.0.reverse();
}
/// Returns an iterator over the slice.
pub fn iter(&self) -> Iter<'_, T> {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityIter::from_iterator_unchecked(self.0.iter()) }
}
/// Returns an iterator over all contiguous windows of length
/// `size`.
///
/// Equivalent to [`[T]::windows`].
///
/// [`[T]::windows`]: `slice::windows`
pub fn windows(&self, size: usize) -> Windows<'_, T> {
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIter::from_slice_iterator_unchecked(self.0.windows(size))
}
}
/// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
/// beginning of the slice.
///
/// Equivalent to [`[T]::chunks`].
///
/// [`[T]::chunks`]: `slice::chunks`
pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIter::from_slice_iterator_unchecked(
self.0.chunks(chunk_size),
)
}
}
/// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
/// beginning of the slice.
///
/// Equivalent to [`[T]::chunks_mut`].
///
/// [`[T]::chunks_mut`]: `slice::chunks_mut`
pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIterMut::from_mut_slice_iterator_unchecked(
self.0.chunks_mut(chunk_size),
)
}
}
///
///
/// Equivalent to [`[T]::chunks_exact`].
///
/// [`[T]::chunks_exact`]: `slice::chunks_exact`
pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIter::from_slice_iterator_unchecked(
self.0.chunks_exact(chunk_size),
)
}
}
/// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
/// beginning of the slice.
///
/// Equivalent to [`[T]::chunks_exact_mut`].
///
/// [`[T]::chunks_exact_mut`]: `slice::chunks_exact_mut`
pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIterMut::from_mut_slice_iterator_unchecked(
self.0.chunks_exact_mut(chunk_size),
)
}
}
/// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
/// of the slice.
///
/// Equivalent to [`[T]::rchunks`].
///
/// [`[T]::rchunks`]: `slice::rchunks`
pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIter::from_slice_iterator_unchecked(
self.0.rchunks(chunk_size),
)
}
}
/// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
/// of the slice.
///
/// Equivalent to [`[T]::rchunks_mut`].
///
/// [`[T]::rchunks_mut`]: `slice::rchunks_mut`
pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIterMut::from_mut_slice_iterator_unchecked(
self.0.rchunks_mut(chunk_size),
)
}
}
/// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
/// end of the slice.
///
/// Equivalent to [`[T]::rchunks_exact`].
///
/// [`[T]::rchunks_exact`]: `slice::rchunks_exact`
pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIter::from_slice_iterator_unchecked(
self.0.rchunks_exact(chunk_size),
)
}
}
/// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
/// of the slice.
///
/// Equivalent to [`[T]::rchunks_exact_mut`].
///
/// [`[T]::rchunks_exact_mut`]: `slice::rchunks_exact_mut`
pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIterMut::from_mut_slice_iterator_unchecked(
self.0.rchunks_exact_mut(chunk_size),
)
}
}
/// Returns an iterator over the slice producing non-overlapping runs
/// of elements using the predicate to separate them.
///
/// Equivalent to [`[T]::chunk_by`].
///
/// [`[T]::chunk_by`]: `slice::chunk_by`
pub fn chunk_by<F>(&self, pred: F) -> ChunkBy<'_, F, T>
where
F: FnMut(&T, &T) -> bool,
{
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIter::from_slice_iterator_unchecked(self.0.chunk_by(pred))
}
}
/// Returns an iterator over the slice producing non-overlapping mutable
/// runs of elements using the predicate to separate them.
///
/// Equivalent to [`[T]::chunk_by_mut`].
///
/// [`[T]::chunk_by_mut`]: `slice::chunk_by_mut`
pub fn chunk_by_mut<F>(&mut self, pred: F) -> ChunkByMut<'_, F, T>
where
F: FnMut(&T, &T) -> bool,
{
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIterMut::from_mut_slice_iterator_unchecked(
self.0.chunk_by_mut(pred),
)
}
}
/// Divides one slice into two at an index.
///
/// Equivalent to [`[T]::split_at`](slice::split_at).
pub const fn split_at(&self, mid: usize) -> (&Self, &Self) {
let (left, right) = self.0.split_at(mid);
// SAFETY: All elements in the original slice are unique.
unsafe {
(
Self::from_slice_unchecked(left),
Self::from_slice_unchecked(right),
)
}
}
/// Divides one mutable slice into two at an index.
///
/// Equivalent to [`[T]::split_at_mut`](slice::split_at_mut).
pub const fn split_at_mut(&mut self, mid: usize) -> (&mut Self, &mut Self) {
let (left, right) = self.0.split_at_mut(mid);
// SAFETY: All elements in the original slice are unique.
unsafe {
(
Self::from_slice_unchecked_mut(left),
Self::from_slice_unchecked_mut(right),
)
}
}
/// Divides one slice into two at an index, without doing bounds checking.
///
/// Equivalent to [`[T]::split_at_unchecked`](slice::split_at_unchecked).
///
/// # Safety
///
/// `mid` must be safe to use in [`[T]::split_at_unchecked`].
///
/// [`[T]::split_at_unchecked`]: `slice::split_at_unchecked`
pub const unsafe fn split_at_unchecked(&self, mid: usize) -> (&Self, &Self) {
// SAFETY: The safety contract is upheld by the caller.
let (left, right) = unsafe { self.0.split_at_unchecked(mid) };
// SAFETY: All elements in the original slice are unique.
unsafe {
(
Self::from_slice_unchecked(left),
Self::from_slice_unchecked(right),
)
}
}
/// Divides one mutable slice into two at an index, without doing bounds checking.
///
/// Equivalent to [`[T]::split_at_mut_unchecked`](slice::split_at_mut_unchecked).
///
/// # Safety
///
/// `mid` must be safe to use in [`[T]::split_at_mut_unchecked`].
///
/// [`[T]::split_at_mut_unchecked`]: `slice::split_at_mut_unchecked`
pub const unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut Self, &mut Self) {
// SAFETY: The safety contract is upheld by the caller.
let (left, right) = unsafe { self.0.split_at_mut_unchecked(mid) };
// SAFETY: All elements in the original slice are unique.
unsafe {
(
Self::from_slice_unchecked_mut(left),
Self::from_slice_unchecked_mut(right),
)
}
}
/// Divides one slice into two at an index, returning `None` if the slice is
/// too short.
///
/// Equivalent to [`[T]::split_at_checked`](slice::split_at_checked).
pub const fn split_at_checked(&self, mid: usize) -> Option<(&Self, &Self)> {
let Some((left, right)) = self.0.split_at_checked(mid) else {
return None;
};
// SAFETY: All elements in the original slice are unique.
unsafe {
Some((
Self::from_slice_unchecked(left),
Self::from_slice_unchecked(right),
))
}
}
/// Divides one mutable slice into two at an index, returning `None` if the
/// slice is too short.
///
/// Equivalent to [`[T]::split_at_mut_checked`](slice::split_at_mut_checked).
pub const fn split_at_mut_checked(&mut self, mid: usize) -> Option<(&mut Self, &mut Self)> {
let Some((left, right)) = self.0.split_at_mut_checked(mid) else {
return None;
};
// SAFETY: All elements in the original slice are unique.
unsafe {
Some((
Self::from_slice_unchecked_mut(left),
Self::from_slice_unchecked_mut(right),
))
}
}
/// Returns an iterator over subslices separated by elements that match
/// `pred`.
///
/// Equivalent to [`[T]::split`].
///
/// [`[T]::split`]: `slice::split`
pub fn split<F>(&self, pred: F) -> Split<'_, F, T>
where
F: FnMut(&T) -> bool,
{
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIter::from_slice_iterator_unchecked(self.0.split(pred))
}
}
/// Returns an iterator over mutable subslices separated by elements that
/// match `pred`.
///
/// Equivalent to [`[T]::split_mut`].
///
/// [`[T]::split_mut`]: `slice::split_mut`
pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, F, T>
where
F: FnMut(&T) -> bool,
{
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIterMut::from_mut_slice_iterator_unchecked(
self.0.split_mut(pred),
)
}
}
/// Returns an iterator over subslices separated by elements that match
/// `pred`.
///
/// Equivalent to [`[T]::split_inclusive`].
///
/// [`[T]::split_inclusive`]: `slice::split_inclusive`
pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, F, T>
where
F: FnMut(&T) -> bool,
{
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIter::from_slice_iterator_unchecked(
self.0.split_inclusive(pred),
)
}
}
/// Returns an iterator over mutable subslices separated by elements that
/// match `pred`.
///
/// Equivalent to [`[T]::split_inclusive_mut`].
///
/// [`[T]::split_inclusive_mut`]: `slice::split_inclusive_mut`
pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, F, T>
where
F: FnMut(&T) -> bool,
{
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIterMut::from_mut_slice_iterator_unchecked(
self.0.split_inclusive_mut(pred),
)
}
}
/// Returns an iterator over subslices separated by elements that match
/// `pred`, starting at the end of the slice and working backwards.
///
/// Equivalent to [`[T]::rsplit`].
///
/// [`[T]::rsplit`]: `slice::rsplit`
pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, F, T>
where
F: FnMut(&T) -> bool,
{
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIter::from_slice_iterator_unchecked(self.0.rsplit(pred))
}
}
/// Returns an iterator over mutable subslices separated by elements that
/// match `pred`, starting at the end of the slice and working
/// backwards.
///
/// Equivalent to [`[T]::rsplit_mut`].
///
/// [`[T]::rsplit_mut`]: `slice::rsplit_mut`
pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, F, T>
where
F: FnMut(&T) -> bool,
{
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIterMut::from_mut_slice_iterator_unchecked(
self.0.rsplit_mut(pred),
)
}
}
/// Returns an iterator over subslices separated by elements that match
/// `pred`, limited to returning at most `n` items.
///
/// Equivalent to [`[T]::splitn`].
///
/// [`[T]::splitn`]: `slice::splitn`
pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, F, T>
where
F: FnMut(&T) -> bool,
{
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIter::from_slice_iterator_unchecked(self.0.splitn(n, pred))
}
}
/// Returns an iterator over mutable subslices separated by elements that match
/// `pred`, limited to returning at most `n` items.
///
/// Equivalent to [`[T]::splitn_mut`].
///
/// [`[T]::splitn_mut`]: `slice::splitn_mut`
pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, F, T>
where
F: FnMut(&T) -> bool,
{
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIterMut::from_mut_slice_iterator_unchecked(
self.0.splitn_mut(n, pred),
)
}
}
/// Returns an iterator over subslices separated by elements that match
/// `pred` limited to returning at most `n` items.
///
/// Equivalent to [`[T]::rsplitn`].
///
/// [`[T]::rsplitn`]: `slice::rsplitn`
pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, F, T>
where
F: FnMut(&T) -> bool,
{
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIter::from_slice_iterator_unchecked(self.0.rsplitn(n, pred))
}
}
/// Returns an iterator over subslices separated by elements that match
/// `pred` limited to returning at most `n` items.
///
/// Equivalent to [`[T]::rsplitn_mut`].
///
/// [`[T]::rsplitn_mut`]: `slice::rsplitn_mut`
pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, F, T>
where
F: FnMut(&T) -> bool,
{
// SAFETY: Any subslice of a unique slice is also unique.
unsafe {
UniqueEntityEquivalentSliceIterMut::from_mut_slice_iterator_unchecked(
self.0.rsplitn_mut(n, pred),
)
}
}
/// Sorts the slice **without** preserving the initial order of equal elements.
///
/// Equivalent to [`[T]::sort_unstable`](slice::sort_unstable).
pub fn sort_unstable(&mut self)
where
T: Ord,
{
self.0.sort_unstable();
}
/// Sorts the slice with a comparison function, **without** preserving the initial order of
/// equal elements.
///
/// Equivalent to [`[T]::sort_unstable_by`](slice::sort_unstable_by).
pub fn sort_unstable_by<F>(&mut self, compare: F)
where
F: FnMut(&T, &T) -> Ordering,
{
self.0.sort_unstable_by(compare);
}
/// Sorts the slice with a key extraction function, **without** preserving the initial order of
/// equal elements.
///
/// Equivalent to [`[T]::sort_unstable_by_key`](slice::sort_unstable_by_key).
pub fn sort_unstable_by_key<K, F>(&mut self, f: F)
where
F: FnMut(&T) -> K,
K: Ord,
{
self.0.sort_unstable_by_key(f);
}
/// Rotates the slice in-place such that the first `mid` elements of the
/// slice move to the end while the last `self.len() - mid` elements move to
/// the front.
///
/// Equivalent to [`[T]::rotate_left`](slice::rotate_left).
pub fn rotate_left(&mut self, mid: usize) {
self.0.rotate_left(mid);
}
/// Rotates the slice in-place such that the first `self.len() - k`
/// elements of the slice move to the end while the last `k` elements move
/// to the front.
///
/// Equivalent to [`[T]::rotate_right`](slice::rotate_right).
pub fn rotate_right(&mut self, mid: usize) {
self.0.rotate_right(mid);
}
/// Sorts the slice, preserving initial order of equal elements.
///
/// Equivalent to [`[T]::sort`](slice::sort()).
pub fn sort(&mut self)
where
T: Ord,
{
self.0.sort();
}
/// Sorts the slice with a comparison function, preserving initial order of equal elements.
///
/// Equivalent to [`[T]::sort_by`](slice::sort_by).
pub fn sort_by<F>(&mut self, compare: F)
where
F: FnMut(&T, &T) -> Ordering,
{
self.0.sort_by(compare);
}
/// Sorts the slice with a key extraction function, preserving initial order of equal elements.
///
/// Equivalent to [`[T]::sort_by_key`](slice::sort_by_key).
pub fn sort_by_key<K, F>(&mut self, f: F)
where
F: FnMut(&T) -> K,
K: Ord,
{
self.0.sort_by_key(f);
}
// Sorts the slice with a key extraction function, preserving initial order of equal elements.
///
/// Equivalent to [`[T]::sort_by_cached_key`](slice::sort_by_cached_key).
pub fn sort_by_cached_key<K, F>(&mut self, f: F)
where
F: FnMut(&T) -> K,
K: Ord,
{
self.0.sort_by_cached_key(f);
}
/// Copies self into a new `UniqueEntityEquivalentVec`.
pub fn to_vec(&self) -> UniqueEntityEquivalentVec<T>
where
T: Clone,
{
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentVec::from_vec_unchecked(self.0.to_vec()) }
}
/// Converts `self` into a vector without clones or allocation.
///
/// Equivalent to [`[T]::into_vec`](slice::into_vec).
pub fn into_vec(self: Box<Self>) -> UniqueEntityEquivalentVec<T> {
// SAFETY:
// This matches the implementation of `slice::into_vec`.
// All elements in the original slice are unique.
unsafe {
let len = self.len();
let vec = Vec::from_raw_parts(Box::into_raw(self).cast::<T>(), len, len);
UniqueEntityEquivalentVec::from_vec_unchecked(vec)
}
}
}
/// Converts a reference to T into a slice of length 1 (without copying).
pub const fn from_ref<T: EntityEquivalent>(s: &T) -> &UniqueEntityEquivalentSlice<T> {
// SAFETY: A slice with a length of 1 is always unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(slice::from_ref(s)) }
}
/// Converts a reference to T into a slice of length 1 (without copying).
pub const fn from_mut<T: EntityEquivalent>(s: &mut T) -> &mut UniqueEntityEquivalentSlice<T> {
// SAFETY: A slice with a length of 1 is always unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(slice::from_mut(s)) }
}
/// Forms a slice from a pointer and a length.
///
/// Equivalent to [`slice::from_raw_parts`].
///
/// # Safety
///
/// [`slice::from_raw_parts`] must be safe to call with `data` and `len`.
/// Additionally, all elements in the resulting slice must be unique.
pub const unsafe fn from_raw_parts<'a, T: EntityEquivalent>(
data: *const T,
len: usize,
) -> &'a UniqueEntityEquivalentSlice<T> {
// SAFETY: The safety contract is upheld by the caller.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(slice::from_raw_parts(data, len)) }
}
/// Performs the same functionality as [`from_raw_parts`], except that a mutable slice is returned.
///
/// Equivalent to [`slice::from_raw_parts_mut`].
///
/// # Safety
///
/// [`slice::from_raw_parts_mut`] must be safe to call with `data` and `len`.
/// Additionally, all elements in the resulting slice must be unique.
pub const unsafe fn from_raw_parts_mut<'a, T: EntityEquivalent>(
data: *mut T,
len: usize,
) -> &'a mut UniqueEntityEquivalentSlice<T> {
// SAFETY: The safety contract is upheld by the caller.
unsafe {
UniqueEntityEquivalentSlice::from_slice_unchecked_mut(slice::from_raw_parts_mut(data, len))
}
}
/// Casts a slice of entity slices to a slice of [`UniqueEntityEquivalentSlice`]s.
///
/// # Safety
///
/// All elements in each of the cast slices must be unique.
pub unsafe fn cast_slice_of_unique_entity_slice<'a, 'b, T: EntityEquivalent + 'a>(
slice: &'b [&'a [T]],
) -> &'b [&'a UniqueEntityEquivalentSlice<T>] {
// SAFETY: All elements in the original iterator are unique slices.
unsafe { &*(ptr::from_ref(slice) as *const [&UniqueEntityEquivalentSlice<T>]) }
}
/// Casts a mutable slice of entity slices to a slice of [`UniqueEntityEquivalentSlice`]s.
///
/// # Safety
///
/// All elements in each of the cast slices must be unique.
pub unsafe fn cast_slice_of_unique_entity_slice_mut<'a, 'b, T: EntityEquivalent + 'a>(
slice: &'b mut [&'a [T]],
) -> &'b mut [&'a UniqueEntityEquivalentSlice<T>] {
| 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/unique_array.rs | crates/bevy_ecs/src/entity/unique_array.rs | //! A wrapper around entity arrays with a uniqueness invariant.
use core::{
array,
borrow::{Borrow, BorrowMut},
fmt::Debug,
ops::{
Bound, Deref, DerefMut, Index, IndexMut, Range, RangeFrom, RangeFull, RangeInclusive,
RangeTo, RangeToInclusive,
},
ptr,
};
use alloc::{
boxed::Box,
collections::{BTreeSet, BinaryHeap, LinkedList, VecDeque},
rc::Rc,
vec::Vec,
};
use bevy_platform::sync::Arc;
use super::{
unique_slice::{self, UniqueEntityEquivalentSlice},
Entity, EntityEquivalent, UniqueEntityIter,
};
/// An array that contains only unique entities.
///
/// It can be obtained through certain methods on [`UniqueEntityEquivalentSlice`],
/// and some [`TryFrom`] implementations.
///
/// When `T` is [`Entity`], use [`UniqueEntityArray`].
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct UniqueEntityEquivalentArray<T: EntityEquivalent, const N: usize>([T; N]);
/// An array that contains only unique [`Entity`].
///
/// This is the default case of a [`UniqueEntityEquivalentArray`].
pub type UniqueEntityArray<const N: usize> = UniqueEntityEquivalentArray<Entity, N>;
impl<T: EntityEquivalent, const N: usize> UniqueEntityEquivalentArray<T, N> {
/// Constructs a `UniqueEntityEquivalentArray` from a [`[T; N]`] unsafely.
///
/// # Safety
///
/// `array` must contain only unique elements.
pub const unsafe fn from_array_unchecked(array: [T; N]) -> Self {
Self(array)
}
/// Constructs a `&UniqueEntityEquivalentArray` from a [`&[T; N]`] unsafely.
///
/// # Safety
///
/// `array` must contain only unique elements.
pub const unsafe fn from_array_ref_unchecked(array: &[T; N]) -> &Self {
// SAFETY: UniqueEntityEquivalentArray is a transparent wrapper around [T; N].
unsafe { &*(ptr::from_ref(array).cast()) }
}
/// Constructs a `Box<UniqueEntityEquivalentArray>` from a [`Box<[T; N]>`] unsafely.
///
/// # Safety
///
/// `array` must contain only unique elements.
pub unsafe fn from_boxed_array_unchecked(array: Box<[T; N]>) -> Box<Self> {
// SAFETY: UniqueEntityEquivalentArray is a transparent wrapper around [T; N].
unsafe { Box::from_raw(Box::into_raw(array).cast()) }
}
/// Casts `self` into the inner array.
pub fn into_boxed_inner(self: Box<Self>) -> Box<[T; N]> {
// SAFETY: UniqueEntityEquivalentArray is a transparent wrapper around [T; N].
unsafe { Box::from_raw(Box::into_raw(self).cast()) }
}
/// Constructs a `Arc<UniqueEntityEquivalentArray>` from a [`Arc<[T; N]>`] unsafely.
///
/// # Safety
///
/// `slice` must contain only unique elements.
pub unsafe fn from_arc_array_unchecked(slice: Arc<[T; N]>) -> Arc<Self> {
// SAFETY: UniqueEntityEquivalentArray is a transparent wrapper around [T; N].
unsafe { Arc::from_raw(Arc::into_raw(slice).cast()) }
}
/// Casts `self` to the inner array.
pub fn into_arc_inner(this: Arc<Self>) -> Arc<[T; N]> {
// SAFETY: UniqueEntityEquivalentArray is a transparent wrapper around [T; N].
unsafe { Arc::from_raw(Arc::into_raw(this).cast()) }
}
// Constructs a `Rc<UniqueEntityEquivalentArray>` from a [`Rc<[T; N]>`] unsafely.
///
/// # Safety
///
/// `slice` must contain only unique elements.
pub unsafe fn from_rc_array_unchecked(slice: Rc<[T; N]>) -> Rc<Self> {
// SAFETY: UniqueEntityEquivalentArray is a transparent wrapper around [T; N].
unsafe { Rc::from_raw(Rc::into_raw(slice).cast()) }
}
/// Casts `self` to the inner array.
pub fn into_rc_inner(self: Rc<Self>) -> Rc<[T; N]> {
// SAFETY: UniqueEntityEquivalentArray is a transparent wrapper around [T; N].
unsafe { Rc::from_raw(Rc::into_raw(self).cast()) }
}
/// Return the inner array.
pub fn into_inner(self) -> [T; N] {
self.0
}
/// Returns a reference to the inner array.
pub fn as_inner(&self) -> &[T; N] {
&self.0
}
/// Returns a slice containing the entire array. Equivalent to `&s[..]`.
pub const fn as_slice(&self) -> &UniqueEntityEquivalentSlice<T> {
// SAFETY: All elements in the original array are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.as_slice()) }
}
/// Returns a mutable slice containing the entire array. Equivalent to
/// `&mut s[..]`.
pub fn as_mut_slice(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {
// SAFETY: All elements in the original array are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.as_mut_slice()) }
}
/// Borrows each element and returns an array of references with the same
/// size as `self`.
///
/// Equivalent to [`[T; N]::as_ref`](array::each_ref).
pub fn each_ref(&self) -> UniqueEntityEquivalentArray<&T, N> {
UniqueEntityEquivalentArray(self.0.each_ref())
}
}
impl<T: EntityEquivalent, const N: usize> Deref for UniqueEntityEquivalentArray<T, N> {
type Target = UniqueEntityEquivalentSlice<T>;
fn deref(&self) -> &Self::Target {
// SAFETY: All elements in the original array are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(&self.0) }
}
}
impl<T: EntityEquivalent, const N: usize> DerefMut for UniqueEntityEquivalentArray<T, N> {
fn deref_mut(&mut self) -> &mut Self::Target {
// SAFETY: All elements in the original array are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(&mut self.0) }
}
}
impl<T: EntityEquivalent> Default for UniqueEntityEquivalentArray<T, 0> {
fn default() -> Self {
Self([])
}
}
impl<'a, T: EntityEquivalent, const N: usize> IntoIterator
for &'a UniqueEntityEquivalentArray<T, N>
{
type Item = &'a T;
type IntoIter = unique_slice::Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
// SAFETY: All elements in the original array are unique.
unsafe { UniqueEntityIter::from_iterator_unchecked(self.0.iter()) }
}
}
impl<T: EntityEquivalent, const N: usize> IntoIterator for UniqueEntityEquivalentArray<T, N> {
type Item = T;
type IntoIter = IntoIter<N, T>;
fn into_iter(self) -> Self::IntoIter {
// SAFETY: All elements in the original array are unique.
unsafe { UniqueEntityIter::from_iterator_unchecked(self.0.into_iter()) }
}
}
impl<T: EntityEquivalent, const N: usize> AsRef<UniqueEntityEquivalentSlice<T>>
for UniqueEntityEquivalentArray<T, N>
{
fn as_ref(&self) -> &UniqueEntityEquivalentSlice<T> {
self
}
}
impl<T: EntityEquivalent, const N: usize> AsMut<UniqueEntityEquivalentSlice<T>>
for UniqueEntityEquivalentArray<T, N>
{
fn as_mut(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {
self
}
}
impl<T: EntityEquivalent, const N: usize> Borrow<UniqueEntityEquivalentSlice<T>>
for UniqueEntityEquivalentArray<T, N>
{
fn borrow(&self) -> &UniqueEntityEquivalentSlice<T> {
self
}
}
impl<T: EntityEquivalent, const N: usize> BorrowMut<UniqueEntityEquivalentSlice<T>>
for UniqueEntityEquivalentArray<T, N>
{
fn borrow_mut(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {
self
}
}
impl<T: EntityEquivalent, const N: usize> Index<(Bound<usize>, Bound<usize>)>
for UniqueEntityEquivalentArray<T, N>
{
type Output = UniqueEntityEquivalentSlice<T>;
fn index(&self, key: (Bound<usize>, Bound<usize>)) -> &Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<T: EntityEquivalent, const N: usize> Index<Range<usize>>
for UniqueEntityEquivalentArray<T, N>
{
type Output = UniqueEntityEquivalentSlice<T>;
fn index(&self, key: Range<usize>) -> &Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<T: EntityEquivalent, const N: usize> Index<RangeFrom<usize>>
for UniqueEntityEquivalentArray<T, N>
{
type Output = UniqueEntityEquivalentSlice<T>;
fn index(&self, key: RangeFrom<usize>) -> &Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<T: EntityEquivalent, const N: usize> Index<RangeFull> for UniqueEntityEquivalentArray<T, N> {
type Output = UniqueEntityEquivalentSlice<T>;
fn index(&self, key: RangeFull) -> &Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<T: EntityEquivalent, const N: usize> Index<RangeInclusive<usize>>
for UniqueEntityEquivalentArray<T, N>
{
type Output = UniqueEntityEquivalentSlice<T>;
fn index(&self, key: RangeInclusive<usize>) -> &Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<T: EntityEquivalent, const N: usize> Index<RangeTo<usize>>
for UniqueEntityEquivalentArray<T, N>
{
type Output = UniqueEntityEquivalentSlice<T>;
fn index(&self, key: RangeTo<usize>) -> &Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<T: EntityEquivalent, const N: usize> Index<RangeToInclusive<usize>>
for UniqueEntityEquivalentArray<T, N>
{
type Output = UniqueEntityEquivalentSlice<T>;
fn index(&self, key: RangeToInclusive<usize>) -> &Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
}
}
impl<T: EntityEquivalent, const N: usize> Index<usize> for UniqueEntityEquivalentArray<T, N> {
type Output = T;
fn index(&self, key: usize) -> &T {
self.0.index(key)
}
}
impl<T: EntityEquivalent, const N: usize> IndexMut<(Bound<usize>, Bound<usize>)>
for UniqueEntityEquivalentArray<T, N>
{
fn index_mut(&mut self, key: (Bound<usize>, Bound<usize>)) -> &mut Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }
}
}
impl<T: EntityEquivalent, const N: usize> IndexMut<Range<usize>>
for UniqueEntityEquivalentArray<T, N>
{
fn index_mut(&mut self, key: Range<usize>) -> &mut Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }
}
}
impl<T: EntityEquivalent, const N: usize> IndexMut<RangeFrom<usize>>
for UniqueEntityEquivalentArray<T, N>
{
fn index_mut(&mut self, key: RangeFrom<usize>) -> &mut Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }
}
}
impl<T: EntityEquivalent, const N: usize> IndexMut<RangeFull>
for UniqueEntityEquivalentArray<T, N>
{
fn index_mut(&mut self, key: RangeFull) -> &mut Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }
}
}
impl<T: EntityEquivalent, const N: usize> IndexMut<RangeInclusive<usize>>
for UniqueEntityEquivalentArray<T, N>
{
fn index_mut(&mut self, key: RangeInclusive<usize>) -> &mut Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }
}
}
impl<T: EntityEquivalent, const N: usize> IndexMut<RangeTo<usize>>
for UniqueEntityEquivalentArray<T, N>
{
fn index_mut(&mut self, key: RangeTo<usize>) -> &mut Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }
}
}
impl<T: EntityEquivalent, const N: usize> IndexMut<RangeToInclusive<usize>>
for UniqueEntityEquivalentArray<T, N>
{
fn index_mut(&mut self, key: RangeToInclusive<usize>) -> &mut Self::Output {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }
}
}
impl<T: EntityEquivalent + Clone> From<&[T; 1]> for UniqueEntityEquivalentArray<T, 1> {
fn from(value: &[T; 1]) -> Self {
Self(value.clone())
}
}
impl<T: EntityEquivalent + Clone> From<&[T; 0]> for UniqueEntityEquivalentArray<T, 0> {
fn from(value: &[T; 0]) -> Self {
Self(value.clone())
}
}
impl<T: EntityEquivalent + Clone> From<&mut [T; 1]> for UniqueEntityEquivalentArray<T, 1> {
fn from(value: &mut [T; 1]) -> Self {
Self(value.clone())
}
}
impl<T: EntityEquivalent + Clone> From<&mut [T; 0]> for UniqueEntityEquivalentArray<T, 0> {
fn from(value: &mut [T; 0]) -> Self {
Self(value.clone())
}
}
impl<T: EntityEquivalent> From<[T; 1]> for UniqueEntityEquivalentArray<T, 1> {
fn from(value: [T; 1]) -> Self {
Self(value)
}
}
impl<T: EntityEquivalent> From<[T; 0]> for UniqueEntityEquivalentArray<T, 0> {
fn from(value: [T; 0]) -> Self {
Self(value)
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentArray<T, 1>> for (T,) {
fn from(array: UniqueEntityEquivalentArray<T, 1>) -> Self {
Self::from(array.into_inner())
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentArray<T, 2>> for (T, T) {
fn from(array: UniqueEntityEquivalentArray<T, 2>) -> Self {
Self::from(array.into_inner())
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentArray<T, 3>> for (T, T, T) {
fn from(array: UniqueEntityEquivalentArray<T, 3>) -> Self {
Self::from(array.into_inner())
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentArray<T, 4>> for (T, T, T, T) {
fn from(array: UniqueEntityEquivalentArray<T, 4>) -> Self {
Self::from(array.into_inner())
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentArray<T, 5>> for (T, T, T, T, T) {
fn from(array: UniqueEntityEquivalentArray<T, 5>) -> Self {
Self::from(array.into_inner())
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentArray<T, 6>> for (T, T, T, T, T, T) {
fn from(array: UniqueEntityEquivalentArray<T, 6>) -> Self {
Self::from(array.into_inner())
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentArray<T, 7>> for (T, T, T, T, T, T, T) {
fn from(array: UniqueEntityEquivalentArray<T, 7>) -> Self {
Self::from(array.into_inner())
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentArray<T, 8>> for (T, T, T, T, T, T, T, T) {
fn from(array: UniqueEntityEquivalentArray<T, 8>) -> Self {
Self::from(array.into_inner())
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentArray<T, 9>> for (T, T, T, T, T, T, T, T, T) {
fn from(array: UniqueEntityEquivalentArray<T, 9>) -> Self {
Self::from(array.into_inner())
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentArray<T, 10>>
for (T, T, T, T, T, T, T, T, T, T)
{
fn from(array: UniqueEntityEquivalentArray<T, 10>) -> Self {
Self::from(array.into_inner())
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentArray<T, 11>>
for (T, T, T, T, T, T, T, T, T, T, T)
{
fn from(array: UniqueEntityEquivalentArray<T, 11>) -> Self {
Self::from(array.into_inner())
}
}
impl<T: EntityEquivalent> From<UniqueEntityEquivalentArray<T, 12>>
for (T, T, T, T, T, T, T, T, T, T, T, T)
{
fn from(array: UniqueEntityEquivalentArray<T, 12>) -> Self {
Self::from(array.into_inner())
}
}
impl<T: EntityEquivalent + Ord, const N: usize> From<UniqueEntityEquivalentArray<T, N>>
for BTreeSet<T>
{
fn from(value: UniqueEntityEquivalentArray<T, N>) -> Self {
BTreeSet::from(value.0)
}
}
impl<T: EntityEquivalent + Ord, const N: usize> From<UniqueEntityEquivalentArray<T, N>>
for BinaryHeap<T>
{
fn from(value: UniqueEntityEquivalentArray<T, N>) -> Self {
BinaryHeap::from(value.0)
}
}
impl<T: EntityEquivalent, const N: usize> From<UniqueEntityEquivalentArray<T, N>>
for LinkedList<T>
{
fn from(value: UniqueEntityEquivalentArray<T, N>) -> Self {
LinkedList::from(value.0)
}
}
impl<T: EntityEquivalent, const N: usize> From<UniqueEntityEquivalentArray<T, N>> for Vec<T> {
fn from(value: UniqueEntityEquivalentArray<T, N>) -> Self {
Vec::from(value.0)
}
}
impl<T: EntityEquivalent, const N: usize> From<UniqueEntityEquivalentArray<T, N>> for VecDeque<T> {
fn from(value: UniqueEntityEquivalentArray<T, N>) -> Self {
VecDeque::from(value.0)
}
}
impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent, const N: usize>
PartialEq<&UniqueEntityEquivalentSlice<U>> for UniqueEntityEquivalentArray<T, N>
{
fn eq(&self, other: &&UniqueEntityEquivalentSlice<U>) -> bool {
self.0.eq(&other.as_inner())
}
}
impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent, const N: usize>
PartialEq<UniqueEntityEquivalentSlice<U>> for UniqueEntityEquivalentArray<T, N>
{
fn eq(&self, other: &UniqueEntityEquivalentSlice<U>) -> bool {
self.0.eq(other.as_inner())
}
}
impl<T: PartialEq<U>, U: EntityEquivalent, const N: usize>
PartialEq<&UniqueEntityEquivalentArray<U, N>> for Vec<T>
{
fn eq(&self, other: &&UniqueEntityEquivalentArray<U, N>) -> bool {
self.eq(&other.0)
}
}
impl<T: PartialEq<U>, U: EntityEquivalent, const N: usize>
PartialEq<&UniqueEntityEquivalentArray<U, N>> for VecDeque<T>
{
fn eq(&self, other: &&UniqueEntityEquivalentArray<U, N>) -> bool {
self.eq(&other.0)
}
}
impl<T: PartialEq<U>, U: EntityEquivalent, const N: usize>
PartialEq<&mut UniqueEntityEquivalentArray<U, N>> for VecDeque<T>
{
fn eq(&self, other: &&mut UniqueEntityEquivalentArray<U, N>) -> bool {
self.eq(&other.0)
}
}
impl<T: PartialEq<U>, U: EntityEquivalent, const N: usize>
PartialEq<UniqueEntityEquivalentArray<U, N>> for Vec<T>
{
fn eq(&self, other: &UniqueEntityEquivalentArray<U, N>) -> bool {
self.eq(&other.0)
}
}
impl<T: PartialEq<U>, U: EntityEquivalent, const N: usize>
PartialEq<UniqueEntityEquivalentArray<U, N>> for VecDeque<T>
{
fn eq(&self, other: &UniqueEntityEquivalentArray<U, N>) -> bool {
self.eq(&other.0)
}
}
/// A by-value array iterator.
///
/// Equivalent to [`array::IntoIter`].
pub type IntoIter<const N: usize, T = Entity> = UniqueEntityIter<array::IntoIter<T, N>>;
impl<T: EntityEquivalent, const N: usize> UniqueEntityIter<array::IntoIter<T, N>> {
/// Returns an immutable slice of all elements that have not been yielded
/// yet.
///
/// Equivalent to [`array::IntoIter::as_slice`].
pub fn as_slice(&self) -> &UniqueEntityEquivalentSlice<T> {
// SAFETY: All elements in the original slice are unique.
unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.as_inner().as_slice()) }
}
/// Returns a mutable slice of all elements that have not been yielded yet.
///
/// Equivalent to [`array::IntoIter::as_mut_slice`].
pub fn as_mut_slice(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {
// SAFETY: All elements in the original slice are unique.
unsafe {
UniqueEntityEquivalentSlice::from_slice_unchecked_mut(
self.as_mut_inner().as_mut_slice(),
)
}
}
}
| 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/entity/index_set.rs | crates/bevy_ecs/src/entity/index_set.rs | //! Contains the [`EntityIndexSet`] type, a [`IndexSet`] pre-configured to use [`EntityHash`] hashing.
//!
//! This module is a lightweight wrapper around `indexmap`'ss [`IndexSet`] that is more performant for [`Entity`] keys.
use core::{
cmp::Ordering,
fmt::{self, Debug, Formatter},
hash::BuildHasher,
hash::{Hash, Hasher},
iter::FusedIterator,
marker::PhantomData,
ops::{
BitAnd, BitOr, BitXor, Bound, Deref, DerefMut, Index, Range, RangeBounds, RangeFrom,
RangeFull, RangeInclusive, RangeTo, RangeToInclusive, Sub,
},
ptr,
};
use indexmap::set::{self, IndexSet};
use super::{Entity, EntityHash, EntitySetIterator};
use bevy_platform::prelude::Box;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
/// An [`IndexSet`] pre-configured to use [`EntityHash`] hashing.
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serialize", derive(serde::Deserialize, serde::Serialize))]
#[derive(Debug, Clone, Default)]
pub struct EntityIndexSet(pub(crate) IndexSet<Entity, EntityHash>);
impl EntityIndexSet {
/// Creates an empty `EntityIndexSet`.
///
/// Equivalent to [`IndexSet::with_hasher(EntityHash)`].
///
/// [`IndexSet::with_hasher(EntityHash)`]: IndexSet::with_hasher
pub const fn new() -> Self {
Self(IndexSet::with_hasher(EntityHash))
}
/// Creates an empty `EntityIndexSet` with the specified capacity.
///
/// Equivalent to [`IndexSet::with_capacity_and_hasher(n, EntityHash)`].
///
/// [`IndexSet::with_capacity_and_hasher(n, EntityHash)`]: IndexSet::with_capacity_and_hasher
pub fn with_capacity(n: usize) -> Self {
Self(IndexSet::with_capacity_and_hasher(n, EntityHash))
}
/// Returns the inner [`IndexSet`].
pub fn into_inner(self) -> IndexSet<Entity, EntityHash> {
self.0
}
/// Returns a slice of all the values in the set.
///
/// Equivalent to [`IndexSet::as_slice`].
pub fn as_slice(&self) -> &Slice {
// SAFETY: Slice is a transparent wrapper around indexmap::set::Slice.
unsafe { Slice::from_slice_unchecked(self.0.as_slice()) }
}
/// Clears the `IndexSet` in the given index range, returning those values
/// as a drain iterator.
///
/// Equivalent to [`IndexSet::drain`].
pub fn drain<R: RangeBounds<usize>>(&mut self, range: R) -> Drain<'_> {
Drain(self.0.drain(range), PhantomData)
}
/// Returns a slice of values in the given range of indices.
///
/// Equivalent to [`IndexSet::get_range`].
pub fn get_range<R: RangeBounds<usize>>(&self, range: R) -> Option<&Slice> {
self.0.get_range(range).map(|slice|
// SAFETY: The source IndexSet uses EntityHash.
unsafe { Slice::from_slice_unchecked(slice) })
}
/// Return an iterator over the values of the set, in their order.
///
/// Equivalent to [`IndexSet::iter`].
pub fn iter(&self) -> Iter<'_> {
Iter(self.0.iter(), PhantomData)
}
/// Converts into a boxed slice of all the values in the set.
///
/// Equivalent to [`IndexSet::into_boxed_slice`].
pub fn into_boxed_slice(self) -> Box<Slice> {
// SAFETY: Slice is a transparent wrapper around indexmap::set::Slice.
unsafe { Slice::from_boxed_slice_unchecked(self.0.into_boxed_slice()) }
}
}
impl Deref for EntityIndexSet {
type Target = IndexSet<Entity, EntityHash>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for EntityIndexSet {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<'a> IntoIterator for &'a EntityIndexSet {
type Item = &'a Entity;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Self::IntoIter {
Iter((&self.0).into_iter(), PhantomData)
}
}
impl IntoIterator for EntityIndexSet {
type Item = Entity;
type IntoIter = IntoIter;
fn into_iter(self) -> Self::IntoIter {
IntoIter(self.0.into_iter(), PhantomData)
}
}
impl BitAnd for &EntityIndexSet {
type Output = EntityIndexSet;
fn bitand(self, rhs: Self) -> Self::Output {
EntityIndexSet(self.0.bitand(&rhs.0))
}
}
impl BitOr for &EntityIndexSet {
type Output = EntityIndexSet;
fn bitor(self, rhs: Self) -> Self::Output {
EntityIndexSet(self.0.bitor(&rhs.0))
}
}
impl BitXor for &EntityIndexSet {
type Output = EntityIndexSet;
fn bitxor(self, rhs: Self) -> Self::Output {
EntityIndexSet(self.0.bitxor(&rhs.0))
}
}
impl Sub for &EntityIndexSet {
type Output = EntityIndexSet;
fn sub(self, rhs: Self) -> Self::Output {
EntityIndexSet(self.0.sub(&rhs.0))
}
}
impl<'a> Extend<&'a Entity> for EntityIndexSet {
fn extend<T: IntoIterator<Item = &'a Entity>>(&mut self, iter: T) {
self.0.extend(iter);
}
}
impl Extend<Entity> for EntityIndexSet {
fn extend<T: IntoIterator<Item = Entity>>(&mut self, iter: T) {
self.0.extend(iter);
}
}
impl<const N: usize> From<[Entity; N]> for EntityIndexSet {
fn from(value: [Entity; N]) -> Self {
Self(IndexSet::from_iter(value))
}
}
impl FromIterator<Entity> for EntityIndexSet {
fn from_iter<I: IntoIterator<Item = Entity>>(iterable: I) -> Self {
Self(IndexSet::from_iter(iterable))
}
}
impl<S2> PartialEq<IndexSet<Entity, S2>> for EntityIndexSet
where
S2: BuildHasher,
{
fn eq(&self, other: &IndexSet<Entity, S2>) -> bool {
self.0.eq(other)
}
}
impl PartialEq for EntityIndexSet {
fn eq(&self, other: &EntityIndexSet) -> bool {
self.0.eq(other)
}
}
impl Eq for EntityIndexSet {}
impl Index<(Bound<usize>, Bound<usize>)> for EntityIndexSet {
type Output = Slice;
fn index(&self, key: (Bound<usize>, Bound<usize>)) -> &Self::Output {
// SAFETY: The source IndexSet uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
}
}
impl Index<Range<usize>> for EntityIndexSet {
type Output = Slice;
fn index(&self, key: Range<usize>) -> &Self::Output {
// SAFETY: The source IndexSet uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
}
}
impl Index<RangeFrom<usize>> for EntityIndexSet {
type Output = Slice;
fn index(&self, key: RangeFrom<usize>) -> &Self::Output {
// SAFETY: The source IndexSet uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
}
}
impl Index<RangeFull> for EntityIndexSet {
type Output = Slice;
fn index(&self, key: RangeFull) -> &Self::Output {
// SAFETY: The source IndexSet uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
}
}
impl Index<RangeInclusive<usize>> for EntityIndexSet {
type Output = Slice;
fn index(&self, key: RangeInclusive<usize>) -> &Self::Output {
// SAFETY: The source IndexSet uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
}
}
impl Index<RangeTo<usize>> for EntityIndexSet {
type Output = Slice;
fn index(&self, key: RangeTo<usize>) -> &Self::Output {
// SAFETY: The source IndexSet uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
}
}
impl Index<RangeToInclusive<usize>> for EntityIndexSet {
type Output = Slice;
fn index(&self, key: RangeToInclusive<usize>) -> &Self::Output {
// SAFETY: The source IndexSet uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
}
}
impl Index<usize> for EntityIndexSet {
type Output = Entity;
fn index(&self, key: usize) -> &Entity {
self.0.index(key)
}
}
/// A dynamically-sized slice of values in an [`EntityIndexSet`].
///
/// Equivalent to an [`indexmap::set::Slice<V>`] whose source [`IndexSet`]
/// uses [`EntityHash`].
#[repr(transparent)]
pub struct Slice<S = EntityHash>(PhantomData<S>, set::Slice<Entity>);
impl Slice {
/// Returns an empty slice.
///
/// Equivalent to [`set::Slice::new`].
pub const fn new<'a>() -> &'a Self {
// SAFETY: The source slice is empty.
unsafe { Self::from_slice_unchecked(set::Slice::new()) }
}
/// Constructs a [`entity::index_set::Slice`] from a [`indexmap::set::Slice`] unsafely.
///
/// # Safety
///
/// `slice` must stem from an [`IndexSet`] using [`EntityHash`].
///
/// [`entity::index_set::Slice`]: `crate::entity::index_set::Slice`
pub const unsafe fn from_slice_unchecked(slice: &set::Slice<Entity>) -> &Self {
// SAFETY: Slice is a transparent wrapper around indexmap::set::Slice.
unsafe { &*(ptr::from_ref(slice) as *const Self) }
}
/// Constructs a [`entity::index_set::Slice`] from a [`indexmap::set::Slice`] unsafely.
///
/// # Safety
///
/// `slice` must stem from an [`IndexSet`] using [`EntityHash`].
///
/// [`entity::index_set::Slice`]: `crate::entity::index_set::Slice`
pub const unsafe fn from_slice_unchecked_mut(slice: &mut set::Slice<Entity>) -> &mut Self {
// SAFETY: Slice is a transparent wrapper around indexmap::set::Slice.
unsafe { &mut *(ptr::from_mut(slice) as *mut Self) }
}
/// Casts `self` to the inner slice.
pub const fn as_inner(&self) -> &set::Slice<Entity> {
&self.1
}
/// Constructs a boxed [`entity::index_set::Slice`] from a boxed [`indexmap::set::Slice`] unsafely.
///
/// # Safety
///
/// `slice` must stem from an [`IndexSet`] using [`EntityHash`].
///
/// [`entity::index_set::Slice`]: `crate::entity::index_set::Slice`
pub unsafe fn from_boxed_slice_unchecked(slice: Box<set::Slice<Entity>>) -> Box<Self> {
// SAFETY: Slice is a transparent wrapper around indexmap::set::Slice.
unsafe { Box::from_raw(Box::into_raw(slice) as *mut Self) }
}
/// Casts a reference to `self` to the inner slice.
#[expect(
clippy::borrowed_box,
reason = "We wish to access the Box API of the inner type, without consuming it."
)]
pub fn as_boxed_inner(self: &Box<Self>) -> &Box<set::Slice<Entity>> {
// SAFETY: Slice is a transparent wrapper around indexmap::set::Slice.
unsafe { &*(ptr::from_ref(self).cast::<Box<set::Slice<Entity>>>()) }
}
/// Casts `self` to the inner slice.
pub fn into_boxed_inner(self: Box<Self>) -> Box<set::Slice<Entity>> {
// SAFETY: Slice is a transparent wrapper around indexmap::set::Slice.
unsafe { Box::from_raw(Box::into_raw(self) as *mut set::Slice<Entity>) }
}
/// Returns a slice of values in the given range of indices.
///
/// Equivalent to [`set::Slice::get_range`].
pub fn get_range<R: RangeBounds<usize>>(&self, range: R) -> Option<&Self> {
self.1.get_range(range).map(|slice|
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(slice) })
}
/// Divides one slice into two at an index.
///
/// Equivalent to [`set::Slice::split_at`].
pub fn split_at(&self, index: usize) -> (&Self, &Self) {
let (slice_1, slice_2) = self.1.split_at(index);
// SAFETY: These are subslices of a valid slice.
unsafe {
(
Self::from_slice_unchecked(slice_1),
Self::from_slice_unchecked(slice_2),
)
}
}
/// Returns the first value and the rest of the slice,
/// or `None` if it is empty.
///
/// Equivalent to [`set::Slice::split_first`].
pub fn split_first(&self) -> Option<(&Entity, &Self)> {
self.1.split_first().map(|(first, rest)| {
(
first,
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(rest) },
)
})
}
/// Returns the last value and the rest of the slice,
/// or `None` if it is empty.
///
/// Equivalent to [`set::Slice::split_last`].
pub fn split_last(&self) -> Option<(&Entity, &Self)> {
self.1.split_last().map(|(last, rest)| {
(
last,
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(rest) },
)
})
}
/// Return an iterator over the values of the set slice.
///
/// Equivalent to [`set::Slice::iter`].
pub fn iter(&self) -> Iter<'_> {
Iter(self.1.iter(), PhantomData)
}
}
impl Deref for Slice {
type Target = set::Slice<Entity>;
fn deref(&self) -> &Self::Target {
&self.1
}
}
impl<'a> IntoIterator for &'a Slice {
type IntoIter = Iter<'a>;
type Item = &'a Entity;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl IntoIterator for Box<Slice> {
type IntoIter = IntoIter;
type Item = Entity;
fn into_iter(self) -> Self::IntoIter {
IntoIter(self.into_boxed_inner().into_iter(), PhantomData)
}
}
impl Clone for Box<Slice> {
fn clone(&self) -> Self {
// SAFETY: This is a clone of a valid slice.
unsafe { Slice::from_boxed_slice_unchecked(self.as_boxed_inner().clone()) }
}
}
impl Default for &Slice {
fn default() -> Self {
// SAFETY: The source slice is empty.
unsafe { Slice::from_slice_unchecked(<&set::Slice<Entity>>::default()) }
}
}
impl Default for Box<Slice> {
fn default() -> Self {
// SAFETY: The source slice is empty.
unsafe { Slice::from_boxed_slice_unchecked(<Box<set::Slice<Entity>>>::default()) }
}
}
impl<V: Debug> Debug for Slice<V> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("Slice")
.field(&self.0)
.field(&&self.1)
.finish()
}
}
impl From<&Slice> for Box<Slice> {
fn from(value: &Slice) -> Self {
// SAFETY: This slice is a copy of a valid slice.
unsafe { Slice::from_boxed_slice_unchecked(value.1.into()) }
}
}
impl Hash for Slice {
fn hash<H: Hasher>(&self, state: &mut H) {
self.1.hash(state);
}
}
impl PartialOrd for Slice {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Slice {
fn cmp(&self, other: &Self) -> Ordering {
self.1.cmp(other)
}
}
impl PartialEq for Slice {
fn eq(&self, other: &Self) -> bool {
self.1 == other.1
}
}
impl Eq for Slice {}
impl Index<(Bound<usize>, Bound<usize>)> for Slice {
type Output = Self;
fn index(&self, key: (Bound<usize>, Bound<usize>)) -> &Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(self.1.index(key)) }
}
}
impl Index<Range<usize>> for Slice {
type Output = Self;
fn index(&self, key: Range<usize>) -> &Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(self.1.index(key)) }
}
}
impl Index<RangeFrom<usize>> for Slice {
type Output = Slice;
fn index(&self, key: RangeFrom<usize>) -> &Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(self.1.index(key)) }
}
}
impl Index<RangeFull> for Slice {
type Output = Self;
fn index(&self, key: RangeFull) -> &Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(self.1.index(key)) }
}
}
impl Index<RangeInclusive<usize>> for Slice {
type Output = Self;
fn index(&self, key: RangeInclusive<usize>) -> &Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(self.1.index(key)) }
}
}
impl Index<RangeTo<usize>> for Slice {
type Output = Self;
fn index(&self, key: RangeTo<usize>) -> &Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(self.1.index(key)) }
}
}
impl Index<RangeToInclusive<usize>> for Slice {
type Output = Self;
fn index(&self, key: RangeToInclusive<usize>) -> &Self {
// SAFETY: This a subslice of a valid slice.
unsafe { Self::from_slice_unchecked(self.1.index(key)) }
}
}
impl Index<usize> for Slice {
type Output = Entity;
fn index(&self, key: usize) -> &Entity {
self.1.index(key)
}
}
/// An iterator over the items of an [`EntityIndexSet`].
///
/// This struct is created by the [`iter`] method on [`EntityIndexSet`]. See its documentation for more.
///
/// [`iter`]: EntityIndexSet::iter
pub struct Iter<'a, S = EntityHash>(set::Iter<'a, Entity>, PhantomData<S>);
impl<'a> Iter<'a> {
/// Returns the inner [`Iter`](set::Iter).
pub fn into_inner(self) -> set::Iter<'a, Entity> {
self.0
}
/// Returns a slice of the remaining entries in the iterator.
///
/// Equivalent to [`set::Iter::as_slice`].
pub fn as_slice(&self) -> &Slice {
// SAFETY: The source IndexSet uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.as_slice()) }
}
}
impl<'a> Deref for Iter<'a> {
type Target = set::Iter<'a, Entity>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a> Iterator for Iter<'a> {
type Item = &'a Entity;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl DoubleEndedIterator for Iter<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
self.0.next_back()
}
}
impl ExactSizeIterator for Iter<'_> {}
impl FusedIterator for Iter<'_> {}
impl Clone for Iter<'_> {
fn clone(&self) -> Self {
Self(self.0.clone(), PhantomData)
}
}
impl Debug for Iter<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("Iter").field(&self.0).field(&self.1).finish()
}
}
impl Default for Iter<'_> {
fn default() -> Self {
Self(Default::default(), PhantomData)
}
}
// SAFETY: Iter stems from a correctly behaving `IndexSet<Entity, EntityHash>`.
unsafe impl EntitySetIterator for Iter<'_> {}
/// Owning iterator over the items of an [`EntityIndexSet`].
///
/// This struct is created by the [`into_iter`] method on [`EntityIndexSet`] (provided by the [`IntoIterator`] trait). See its documentation for more.
///
/// [`into_iter`]: EntityIndexSet::into_iter
pub struct IntoIter<S = EntityHash>(set::IntoIter<Entity>, PhantomData<S>);
impl IntoIter {
/// Returns the inner [`IntoIter`](set::IntoIter).
pub fn into_inner(self) -> set::IntoIter<Entity> {
self.0
}
/// Returns a slice of the remaining entries in the iterator.
///
/// Equivalent to [`set::IntoIter::as_slice`].
pub fn as_slice(&self) -> &Slice {
// SAFETY: The source IndexSet uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.as_slice()) }
}
}
impl Deref for IntoIter {
type Target = set::IntoIter<Entity>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Iterator for IntoIter {
type Item = Entity;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl DoubleEndedIterator for IntoIter {
fn next_back(&mut self) -> Option<Self::Item> {
self.0.next_back()
}
}
impl ExactSizeIterator for IntoIter {}
impl FusedIterator for IntoIter {}
impl Clone for IntoIter {
fn clone(&self) -> Self {
Self(self.0.clone(), PhantomData)
}
}
impl Debug for IntoIter {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("IntoIter")
.field(&self.0)
.field(&self.1)
.finish()
}
}
impl Default for IntoIter {
fn default() -> Self {
Self(Default::default(), PhantomData)
}
}
// SAFETY: IntoIter stems from a correctly behaving `IndexSet<Entity, EntityHash>`.
unsafe impl EntitySetIterator for IntoIter {}
/// A draining iterator over the items of an [`EntityIndexSet`].
///
/// This struct is created by the [`drain`] method on [`EntityIndexSet`]. See its documentation for more.
///
/// [`drain`]: EntityIndexSet::drain
pub struct Drain<'a, S = EntityHash>(set::Drain<'a, Entity>, PhantomData<S>);
impl<'a> Drain<'a> {
/// Returns the inner [`Drain`](set::Drain).
pub fn into_inner(self) -> set::Drain<'a, Entity> {
self.0
}
/// Returns a slice of the remaining entries in the iterator.$
///
/// Equivalent to [`set::Drain::as_slice`].
pub fn as_slice(&self) -> &Slice {
// SAFETY: The source IndexSet uses EntityHash.
unsafe { Slice::from_slice_unchecked(self.0.as_slice()) }
}
}
impl<'a> Deref for Drain<'a> {
type Target = set::Drain<'a, Entity>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a> Iterator for Drain<'a> {
type Item = Entity;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl DoubleEndedIterator for Drain<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
self.0.next_back()
}
}
impl ExactSizeIterator for Drain<'_> {}
impl FusedIterator for Drain<'_> {}
impl Debug for Drain<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("Drain")
.field(&self.0)
.field(&self.1)
.finish()
}
}
// SAFETY: Drain stems from a correctly behaving `IndexSet<Entity, EntityHash>`.
unsafe impl EntitySetIterator for Drain<'_> {}
// SAFETY: Difference stems from two correctly behaving `IndexSet<Entity, EntityHash>`s.
unsafe impl EntitySetIterator for set::Difference<'_, Entity, EntityHash> {}
// SAFETY: Intersection stems from two correctly behaving `IndexSet<Entity, EntityHash>`s.
unsafe impl EntitySetIterator for set::Intersection<'_, Entity, EntityHash> {}
// SAFETY: SymmetricDifference stems from two correctly behaving `IndexSet<Entity, EntityHash>`s.
unsafe impl EntitySetIterator for set::SymmetricDifference<'_, Entity, EntityHash, EntityHash> {}
// SAFETY: Union stems from two correctly behaving `IndexSet<Entity, EntityHash>`s.
unsafe impl EntitySetIterator for set::Union<'_, Entity, EntityHash> {}
// SAFETY: Splice stems from a correctly behaving `IndexSet<Entity, EntityHash>`s.
unsafe impl<I: Iterator<Item = Entity>> EntitySetIterator
for set::Splice<'_, I, Entity, EntityHash>
{
}
| 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/event/trigger.rs | crates/bevy_ecs/src/event/trigger.rs | use crate::event::SetEntityEventTarget;
use crate::{
component::ComponentId,
entity::Entity,
event::{EntityEvent, Event},
observer::{CachedObservers, TriggerContext},
traversal::Traversal,
world::DeferredWorld,
};
use bevy_ptr::PtrMut;
use core::{fmt, marker::PhantomData};
/// [`Trigger`] determines _how_ an [`Event`] is triggered when [`World::trigger`](crate::world::World::trigger) is called.
/// This decides which [`Observer`](crate::observer::Observer)s will run, what data gets passed to them, and the order they will
/// be executed in.
///
/// Implementing [`Trigger`] is "advanced-level" territory, and is generally unnecessary unless you are developing highly specialized
/// [`Event`] trigger logic.
///
/// Bevy comes with a number of built-in [`Trigger`] implementations (see their documentation for more info):
/// - [`GlobalTrigger`]: The [`Event`] derive defaults to using this
/// - [`EntityTrigger`]: The [`EntityEvent`] derive defaults to using this
/// - [`PropagateEntityTrigger`]: The [`EntityEvent`] derive uses this when propagation is enabled.
/// - [`EntityComponentsTrigger`]: Used by Bevy's [component lifecycle events](crate::lifecycle).
///
/// # Safety
///
/// Implementing this properly is _advanced_ soundness territory! Implementers must abide by the following:
///
/// - The `E`' [`Event::Trigger`] must be constrained to the implemented [`Trigger`] type, as part of the implementation.
/// This prevents other [`Trigger`] implementations from directly deferring to your implementation, which is a very easy
/// soundness misstep, as most [`Trigger`] implementations will invoke observers that are developed _for their specific [`Trigger`] type_.
/// Without this constraint, something like [`GlobalTrigger`] could be called for _any_ [`Event`] type, even one that expects a different
/// [`Trigger`] type. This would result in an unsound cast of [`GlobalTrigger`] reference.
/// This is not expressed as an explicit type constraint,, as the `for<'a> Event::Trigger<'a>` lifetime can mismatch explicit lifetimes in
/// some impls.
pub unsafe trait Trigger<E: Event> {
/// Trigger the given `event`, running every [`Observer`](crate::observer::Observer) that matches the `event`, as defined by this
/// [`Trigger`] and the state stored on `self`.
///
/// # Safety
/// - The [`CachedObservers`] `observers` must come from the [`DeferredWorld`] `world`
/// - [`TriggerContext`] must contain an [`EventKey`](crate::event::EventKey) that matches the `E` [`Event`] type
/// - `observers` must correspond to observers compatible with the event type `E`
/// - Read and abide by the "Safety" section defined in the top-level [`Trigger`] docs. Calling this function is
/// unintuitively risky. _Do not use it directly unless you know what you are doing_. Importantly, this should only
/// be called for an `event` whose [`Event::Trigger`] matches this trigger.
unsafe fn trigger(
&mut self,
world: DeferredWorld,
observers: &CachedObservers,
trigger_context: &TriggerContext,
event: &mut E,
);
}
/// A [`Trigger`] that runs _every_ "global" [`Observer`](crate::observer::Observer) (ex: registered via [`World::add_observer`](crate::world::World::add_observer))
/// that matches the given [`Event`].
///
/// The [`Event`] derive defaults to using this [`Trigger`], and it is usable for any [`Event`] type.
#[derive(Default, Debug)]
pub struct GlobalTrigger;
// SAFETY:
// - `E`'s [`Event::Trigger`] is constrained to [`GlobalTrigger`]
// - The implementation abides by the other safety constraints defined in [`Trigger`]
unsafe impl<E: for<'a> Event<Trigger<'a> = Self>> Trigger<E> for GlobalTrigger {
unsafe fn trigger(
&mut self,
world: DeferredWorld,
observers: &CachedObservers,
trigger_context: &TriggerContext,
event: &mut E,
) {
// SAFETY:
// - The caller of `trigger` ensures that `observers` come from the `world`
// - The passed in event ptr comes from `event`, which is E: Event
// - E: Event::Trigger is constrained to GlobalTrigger
// - The caller of `trigger` ensures that `TriggerContext::event_key` matches `event`
unsafe {
self.trigger_internal(world, observers, trigger_context, event.into());
}
}
}
impl GlobalTrigger {
/// # Safety
/// - `observers` must come from the `world` [`DeferredWorld`], and correspond to observers that match the `event` type
/// - `event` must point to an [`Event`]
/// - The `event` [`Event::Trigger`] must be [`GlobalTrigger`]
/// - `trigger_context`'s [`TriggerContext::event_key`] must correspond to the `event` type.
unsafe fn trigger_internal(
&mut self,
mut world: DeferredWorld,
observers: &CachedObservers,
trigger_context: &TriggerContext,
mut event: PtrMut,
) {
// SAFETY: `observers` is the only active reference to something in `world`
unsafe {
world.as_unsafe_world_cell().increment_trigger_id();
}
for (observer, runner) in observers.global_observers() {
// SAFETY:
// - `observers` come from `world` and match the `event` type, enforced by the call to `trigger_internal`
// - the passed in event pointer is an `Event`, enforced by the call to `trigger_internal`
// - `trigger` is a matching trigger type, as it comes from `self`, which is the Trigger for `event`, enforced by `trigger_internal`
// - `trigger_context`'s event_key matches `E`, enforced by the call to `trigger_internal`
// - this abides by the nuances defined in the `Trigger` safety docs
unsafe {
(runner)(
world.reborrow(),
*observer,
trigger_context,
event.reborrow(),
self.into(),
);
}
}
}
}
/// An [`EntityEvent`] [`Trigger`] that does two things:
/// - Runs all "global" [`Observer`] (ex: registered via [`World::add_observer`](crate::world::World::add_observer))
/// that matches the given [`Event`]. This is the same behavior as [`GlobalTrigger`].
/// - Runs every "entity scoped" [`Observer`] that watches the given [`EntityEvent::event_target`] entity.
///
/// The [`EntityEvent`] derive defaults to using this [`Trigger`], and it is usable for any [`EntityEvent`] type.
///
/// [`Observer`]: crate::observer::Observer
#[derive(Default, Debug)]
pub struct EntityTrigger;
// SAFETY:
// - `E`'s [`Event::Trigger`] is constrained to [`EntityTrigger`]
// - The implementation abides by the other safety constraints defined in [`Trigger`]
unsafe impl<E: EntityEvent + for<'a> Event<Trigger<'a> = Self>> Trigger<E> for EntityTrigger {
unsafe fn trigger(
&mut self,
world: DeferredWorld,
observers: &CachedObservers,
trigger_context: &TriggerContext,
event: &mut E,
) {
let entity = event.event_target();
// SAFETY:
// - `observers` come from `world` and match the event type `E`, enforced by the call to `trigger`
// - the passed in event pointer comes from `event`, which is an `Event`
// - `trigger` is a matching trigger type, as it comes from `self`, which is the Trigger for `E`
// - `trigger_context`'s event_key matches `E`, enforced by the call to `trigger`
unsafe {
trigger_entity_internal(
world,
observers,
event.into(),
self.into(),
entity,
trigger_context,
);
}
}
}
/// Trigger observers watching for the given entity event.
/// The `target_entity` should match the [`EntityEvent::event_target`] on `event` for logical correctness.
///
/// # Safety
/// - `observers` must come from the `world` [`DeferredWorld`], and correspond to observers that match the `event` type
/// - `event` must point to an [`Event`]
/// - `trigger` must correspond to the [`Event::Trigger`] type expected by the `event`
/// - `trigger_context`'s [`TriggerContext::event_key`] must correspond to the `event` type.
/// - Read, understand, and abide by the [`Trigger`] safety documentation
// Note: this is not an EntityTrigger method because we want to reuse this logic for the entity propagation trigger
#[inline(never)]
pub unsafe fn trigger_entity_internal(
mut world: DeferredWorld,
observers: &CachedObservers,
mut event: PtrMut,
mut trigger: PtrMut,
target_entity: Entity,
trigger_context: &TriggerContext,
) {
// SAFETY: there are no outstanding world references
unsafe {
world.as_unsafe_world_cell().increment_trigger_id();
}
for (observer, runner) in observers.global_observers() {
// SAFETY:
// - `observers` come from `world` and match the `event` type, enforced by the call to `trigger_entity_internal`
// - the passed in event pointer is an `Event`, enforced by the call to `trigger_entity_internal`
// - `trigger` is a matching trigger type, enforced by the call to `trigger_entity_internal`
// - `trigger_context`'s event_key matches `E`, enforced by the call to `trigger_entity_internal`
unsafe {
(runner)(
world.reborrow(),
*observer,
trigger_context,
event.reborrow(),
trigger.reborrow(),
);
}
}
if let Some(map) = observers.entity_observers().get(&target_entity) {
for (observer, runner) in map {
// SAFETY:
// - `observers` come from `world` and match the `event` type, enforced by the call to `trigger_entity_internal`
// - the passed in event pointer is an `Event`, enforced by the call to `trigger_entity_internal`
// - `trigger` is a matching trigger type, enforced by the call to `trigger_entity_internal`
// - `trigger_context`'s event_key matches `E`, enforced by the call to `trigger_entity_internal`
unsafe {
(runner)(
world.reborrow(),
*observer,
trigger_context,
event.reborrow(),
trigger.reborrow(),
);
}
}
}
}
/// An [`EntityEvent`] [`Trigger`] that behaves like [`EntityTrigger`], but "propagates" the event
/// using an [`Entity`] [`Traversal`]. At each step in the propagation, the [`EntityTrigger`] logic will
/// be run, until [`PropagateEntityTrigger::propagate`] is false, or there are no entities left to traverse.
///
/// This is used by the [`EntityEvent`] derive when `#[entity_event(propagate)]` is enabled. It is usable by every
/// [`EntityEvent`] type.
///
/// If `AUTO_PROPAGATE` is `true`, [`PropagateEntityTrigger::propagate`] will default to `true`.
pub struct PropagateEntityTrigger<const AUTO_PROPAGATE: bool, E: EntityEvent, T: Traversal<E>> {
/// The original [`Entity`] the [`Event`] was _first_ triggered for.
pub original_event_target: Entity,
/// Whether or not to continue propagating using the `T` [`Traversal`]. If this is false,
/// The [`Traversal`] will stop on the current entity.
pub propagate: bool,
_marker: PhantomData<(E, T)>,
}
impl<const AUTO_PROPAGATE: bool, E: EntityEvent, T: Traversal<E>> Default
for PropagateEntityTrigger<AUTO_PROPAGATE, E, T>
{
fn default() -> Self {
Self {
original_event_target: Entity::PLACEHOLDER,
propagate: AUTO_PROPAGATE,
_marker: Default::default(),
}
}
}
impl<const AUTO_PROPAGATE: bool, E: EntityEvent, T: Traversal<E>> fmt::Debug
for PropagateEntityTrigger<AUTO_PROPAGATE, E, T>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PropagateEntityTrigger")
.field("original_event_target", &self.original_event_target)
.field("propagate", &self.propagate)
.field("_marker", &self._marker)
.finish()
}
}
// SAFETY:
// - `E`'s [`Event::Trigger`] is constrained to [`PropagateEntityTrigger<E>`]
unsafe impl<
const AUTO_PROPAGATE: bool,
E: EntityEvent + SetEntityEventTarget + for<'a> Event<Trigger<'a> = Self>,
T: Traversal<E>,
> Trigger<E> for PropagateEntityTrigger<AUTO_PROPAGATE, E, T>
{
unsafe fn trigger(
&mut self,
mut world: DeferredWorld,
observers: &CachedObservers,
trigger_context: &TriggerContext,
event: &mut E,
) {
let mut current_entity = event.event_target();
self.original_event_target = current_entity;
// SAFETY:
// - `observers` come from `world` and match the event type `E`, enforced by the call to `trigger`
// - the passed in event pointer comes from `event`, which is an `Event`
// - `trigger` is a matching trigger type, as it comes from `self`, which is the Trigger for `E`
// - `trigger_context`'s event_key matches `E`, enforced by the call to `trigger`
unsafe {
trigger_entity_internal(
world.reborrow(),
observers,
event.into(),
self.into(),
current_entity,
trigger_context,
);
}
loop {
if !self.propagate {
return;
}
if let Ok(entity) = world.get_entity(current_entity)
&& let Ok(item) = entity.get_components::<T>()
&& let Some(traverse_to) = T::traverse(item, event)
{
current_entity = traverse_to;
} else {
break;
}
event.set_event_target(current_entity);
// SAFETY:
// - `observers` come from `world` and match the event type `E`, enforced by the call to `trigger`
// - the passed in event pointer comes from `event`, which is an `Event`
// - `trigger` is a matching trigger type, as it comes from `self`, which is the Trigger for `E`
// - `trigger_context`'s event_key matches `E`, enforced by the call to `trigger`
unsafe {
trigger_entity_internal(
world.reborrow(),
observers,
event.into(),
self.into(),
current_entity,
trigger_context,
);
}
}
}
}
/// An [`EntityEvent`] [`Trigger`] that, in addition to behaving like a normal [`EntityTrigger`], _also_ runs observers
/// that watch for components that match the slice of [`ComponentId`]s referenced in [`EntityComponentsTrigger`]. This includes
/// both _global_ observers of those components and "entity scoped" observers that watch the [`EntityEvent::event_target`].
///
/// This is used by Bevy's built-in [lifecycle events](crate::lifecycle).
#[derive(Default)]
pub struct EntityComponentsTrigger<'a> {
/// All of the components whose observers were triggered together for the target entity. For example,
/// if components `A` and `B` are added together, producing the [`Add`](crate::lifecycle::Add) event, this will
/// contain the [`ComponentId`] for both `A` and `B`.
pub components: &'a [ComponentId],
}
// SAFETY:
// - `E`'s [`Event::Trigger`] is constrained to [`EntityComponentsTrigger`]
unsafe impl<'a, E: EntityEvent + Event<Trigger<'a> = EntityComponentsTrigger<'a>>> Trigger<E>
for EntityComponentsTrigger<'a>
{
unsafe fn trigger(
&mut self,
world: DeferredWorld,
observers: &CachedObservers,
trigger_context: &TriggerContext,
event: &mut E,
) {
let entity = event.event_target();
// SAFETY:
// - `observers` come from `world` and match the event type `E`, enforced by the call to `trigger`
// - the passed in event pointer comes from `event`, which is an `Event`
// - `trigger_context`'s event_key matches `E`, enforced by the call to `trigger`
unsafe {
self.trigger_internal(world, observers, event.into(), entity, trigger_context);
}
}
}
impl<'a> EntityComponentsTrigger<'a> {
/// # Safety
/// - `observers` must come from the `world` [`DeferredWorld`]
/// - `event` must point to an [`Event`] whose [`Event::Trigger`] is [`EntityComponentsTrigger`]
/// - `trigger_context`'s [`TriggerContext::event_key`] must correspond to the `event` type.
#[inline(never)]
unsafe fn trigger_internal(
&mut self,
mut world: DeferredWorld,
observers: &CachedObservers,
mut event: PtrMut,
entity: Entity,
trigger_context: &TriggerContext,
) {
// SAFETY:
// - `observers` come from `world` and match the event type `E`, enforced by the call to `trigger`
// - the passed in event pointer comes from `event`, which is an `Event`
// - `trigger` is a matching trigger type, as it comes from `self`, which is the Trigger for `E`
// - `trigger_context`'s event_key matches `E`, enforced by the call to `trigger`
unsafe {
trigger_entity_internal(
world.reborrow(),
observers,
event.reborrow(),
self.into(),
entity,
trigger_context,
);
}
// Trigger observers watching for a specific component
for id in self.components {
if let Some(component_observers) = observers.component_observers().get(id) {
for (observer, runner) in component_observers.global_observers() {
// SAFETY:
// - `observers` come from `world` and match the `event` type, enforced by the call to `trigger_internal`
// - the passed in event pointer is an `Event`, enforced by the call to `trigger_internal`
// - `trigger` is a matching trigger type, enforced by the call to `trigger_internal`
// - `trigger_context`'s event_key matches `E`, enforced by the call to `trigger_internal`
unsafe {
(runner)(
world.reborrow(),
*observer,
trigger_context,
event.reborrow(),
self.into(),
);
}
}
if let Some(map) = component_observers
.entity_component_observers()
.get(&entity)
{
for (observer, runner) in map {
// SAFETY:
// - `observers` come from `world` and match the `event` type, enforced by the call to `trigger_internal`
// - the passed in event pointer is an `Event`, enforced by the call to `trigger_internal`
// - `trigger` is a matching trigger type, enforced by the call to `trigger_internal`
// - `trigger_context`'s event_key matches `E`, enforced by the call to `trigger_internal`
unsafe {
(runner)(
world.reborrow(),
*observer,
trigger_context,
event.reborrow(),
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_ecs/src/event/mod.rs | crates/bevy_ecs/src/event/mod.rs | //! [`Event`] functionality.
mod trigger;
pub use bevy_ecs_macros::{EntityEvent, Event};
pub use trigger::*;
use crate::{
component::{Component, ComponentId},
entity::Entity,
world::World,
};
use core::marker::PhantomData;
/// An [`Event`] is something that "happens" at a given moment.
///
/// To make an [`Event`] "happen", you "trigger" it on a [`World`] using [`World::trigger`] or via a [`Command`](crate::system::Command)
/// using [`Commands::trigger`](crate::system::Commands::trigger). This causes any [`Observer`](crate::observer::Observer) watching for that
/// [`Event`] to run _immediately_, as part of the [`World::trigger`] call.
///
/// First, we create an [`Event`] type, typically by deriving the trait.
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// #[derive(Event)]
/// struct Speak {
/// message: String,
/// }
/// ```
///
/// Then, we add an [`Observer`](crate::observer::Observer) to watch for this event type:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// # #[derive(Event)]
/// # struct Speak {
/// # message: String,
/// # }
/// #
/// # let mut world = World::new();
/// #
/// world.add_observer(|speak: On<Speak>| {
/// println!("{}", speak.message);
/// });
/// ```
///
/// Finally, we trigger the event by calling [`World::trigger`](World::trigger):
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// # #[derive(Event)]
/// # struct Speak {
/// # message: String,
/// # }
/// #
/// # let mut world = World::new();
/// #
/// # world.add_observer(|speak: On<Speak>| {
/// # println!("{}", speak.message);
/// # });
/// #
/// # world.flush();
/// #
/// world.trigger(Speak {
/// message: "Hello!".to_string(),
/// });
/// ```
///
/// # Triggers
///
/// Every [`Event`] has an associated [`Trigger`] implementation (set via [`Event::Trigger`]), which defines which observers will run,
/// what data will be passed to them, and the order they will be run in. Unless you are an internals developer or you have very specific
/// needs, you don't need to worry too much about [`Trigger`]. When you derive [`Event`] (or a more specific event trait like [`EntityEvent`]),
/// a [`Trigger`] will be provided for you.
///
/// The [`Event`] derive defaults [`Event::Trigger`] to [`GlobalTrigger`], which will run all observers that watch for the [`Event`].
///
/// # Entity Events
///
/// For events that "target" a specific [`Entity`], see [`EntityEvent`].
#[diagnostic::on_unimplemented(
message = "`{Self}` is not an `Event`",
label = "invalid `Event`",
note = "consider annotating `{Self}` with `#[derive(Event)]`"
)]
pub trait Event: Send + Sync + Sized + 'static {
/// Defines which observers will run, what data will be passed to them, and the order they will be run in. See [`Trigger`] for more info.
type Trigger<'a>: Trigger<Self>;
}
/// An [`EntityEvent`] is an [`Event`] that is triggered for a specific [`EntityEvent::event_target`] entity:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut world = World::default();
/// # let entity = world.spawn_empty().id();
/// #[derive(EntityEvent)]
/// struct Explode {
/// entity: Entity,
/// }
///
/// world.add_observer(|event: On<Explode>, mut commands: Commands| {
/// println!("Entity {} goes BOOM!", event.entity);
/// commands.entity(event.entity).despawn();
/// });
///
/// world.trigger(Explode { entity });
/// ```
///
/// [`EntityEvent`] will set [`EntityEvent::event_target`] automatically for named structs with an `entity` field name (as seen above). It also works for tuple structs
/// whose only field is [`Entity`]:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(EntityEvent)]
/// struct Explode(Entity);
/// ```
///
/// The [`EntityEvent::event_target`] can also be manually set using the `#[event_target]` field attribute:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(EntityEvent)]
/// struct Explode {
/// #[event_target]
/// exploded_entity: Entity,
/// }
/// ```
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(EntityEvent)]
/// struct Explode(#[event_target] Entity);
/// ```
///
/// You may also use any type which implements [`ContainsEntity`](crate::entity::ContainsEntity) as the event target:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// struct Bomb(Entity);
///
/// impl ContainsEntity for Bomb {
/// fn entity(&self) -> Entity {
/// self.0
/// }
/// }
///
/// #[derive(EntityEvent)]
/// struct Explode(Bomb);
/// ```
///
/// By default, an [`EntityEvent`] is immutable. This means the event data, including the target, does not change while the event
/// is triggered. However, to support event propagation, your event must also implement the [`SetEntityEventTarget`] trait.
///
/// This trait is automatically implemented for you if you enable event propagation:
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(EntityEvent)]
/// #[entity_event(propagate)]
/// struct Explode(Entity);
/// ```
///
/// ## Trigger Behavior
///
/// When derived, [`EntityEvent`] defaults to setting [`Event::Trigger`] to [`EntityTrigger`], which will run all normal "untargeted"
/// observers added via [`World::add_observer`], just like a default [`Event`] would (see the example above).
///
/// However it will _also_ run all observers that watch _specific_ entities, which enables you to assign entity-specific logic:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Component, Debug)]
/// # struct Name(String);
/// # let mut world = World::default();
/// # let e1 = world.spawn_empty().id();
/// # let e2 = world.spawn_empty().id();
/// # #[derive(EntityEvent)]
/// # struct Explode {
/// # entity: Entity,
/// # }
/// world.entity_mut(e1).observe(|event: On<Explode>, mut commands: Commands| {
/// println!("Boom!");
/// commands.entity(event.entity).despawn();
/// });
///
/// world.entity_mut(e2).observe(|event: On<Explode>, mut commands: Commands| {
/// println!("The explosion fizzles! This entity is immune!");
/// });
/// ```
///
/// ## [`EntityEvent`] Propagation
///
/// When deriving [`EntityEvent`], you can enable "event propagation" (also known as "event bubbling") by
/// specifying the `#[entity_event(propagate)]` attribute:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(EntityEvent)]
/// #[entity_event(propagate)]
/// struct Click {
/// entity: Entity,
/// }
/// ```
///
/// This will default to using the [`ChildOf`](crate::hierarchy::ChildOf) component to propagate the [`Event`] "up"
/// the hierarchy (from child to parent).
///
/// You can also specify your own [`Traversal`](crate::traversal::Traversal) implementation. A common pattern is to use
/// [`Relationship`](crate::relationship::Relationship) components, which will follow the relationships to their root
/// (just be sure to avoid cycles ... these aren't detected for performance reasons):
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// #[relationship(relationship_target = ClickableBy)]
/// struct Clickable(Entity);
///
/// #[derive(Component)]
/// #[relationship_target(relationship = Clickable)]
/// struct ClickableBy(Vec<Entity>);
///
/// #[derive(EntityEvent)]
/// #[entity_event(propagate = &'static Clickable)]
/// struct Click {
/// entity: Entity,
/// }
/// ```
///
/// By default, propagation requires observers to opt-in:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(EntityEvent)]
/// #[entity_event(propagate)]
/// struct Click {
/// entity: Entity,
/// }
///
/// # let mut world = World::default();
/// world.add_observer(|mut click: On<Click>| {
/// // this will propagate the event up to the parent, using `ChildOf`
/// click.propagate(true);
/// });
/// ```
///
/// But you can enable auto propagation using the `#[entity_event(auto_propagate)]` attribute:
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(EntityEvent)]
/// #[entity_event(propagate, auto_propagate)]
/// struct Click {
/// entity: Entity,
/// }
/// ```
///
/// You can also _stop_ propagation like this:
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(EntityEvent)]
/// # #[entity_event(propagate)]
/// # struct Click {
/// # entity: Entity,
/// # }
/// # fn is_finished_propagating() -> bool { true }
/// # let mut world = World::default();
/// world.add_observer(|mut click: On<Click>| {
/// if is_finished_propagating() {
/// click.propagate(false);
/// }
/// });
/// ```
///
/// ## Naming and Usage Conventions
///
/// In most cases, it is recommended to use a named struct field for the "event target" entity, and to use
/// a name that is descriptive as possible, as this makes events easier to understand and read.
///
/// For events with only one [`Entity`] field, `entity` is often a reasonable name. But if there are multiple
/// [`Entity`] fields, it is often a good idea to use a more descriptive name.
///
/// It is also generally recommended to _consume_ "event target" entities directly via their named field, as this
/// can make the context clearer, allows for more specific documentation hints in IDEs, and it generally reads better.
///
/// ## Manually spawning [`EntityEvent`] observers
///
/// The examples above that call [`EntityWorldMut::observe`] to add entity-specific observer logic are
/// just shorthand for spawning an [`Observer`] directly and manually watching the entity:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut world = World::default();
/// # let entity = world.spawn_empty().id();
/// # #[derive(EntityEvent)]
/// # struct Explode(Entity);
/// let mut observer = Observer::new(|event: On<Explode>| {});
/// observer.watch_entity(entity);
/// world.spawn(observer);
/// ```
///
/// Note that the [`Observer`] component is not added to the entity it is observing. Observers should always be their own entities, as there
/// can be multiple observers of the same entity!
///
/// You can call [`Observer::watch_entity`] more than once or [`Observer::watch_entities`] to watch multiple entities with the same [`Observer`].
///
/// [`EntityWorldMut::observe`]: crate::world::EntityWorldMut::observe
/// [`Observer`]: crate::observer::Observer
/// [`Observer::watch_entity`]: crate::observer::Observer::watch_entity
/// [`Observer::watch_entities`]: crate::observer::Observer::watch_entities
pub trait EntityEvent: Event {
/// The [`Entity`] "target" of this [`EntityEvent`]. When triggered, this will run observers that watch for this specific entity.
fn event_target(&self) -> Entity;
}
/// A trait which is used to set the target of an [`EntityEvent`].
///
/// By default, entity events are immutable; meaning their target does not change during the lifetime of the event. However, some events
/// may require mutable access to provide features such as event propagation.
///
/// You should never need to implement this trait manually if you use `#[derive(EntityEvent)]`. It is automatically implemented for you if you
/// use `#[entity_event(propagate)]`.
pub trait SetEntityEventTarget: EntityEvent {
/// Sets the [`Entity`] "target" of this [`EntityEvent`]. When triggered, this will run observers that watch for this specific entity.
///
/// Note: In general, this should not be called from within an [`Observer`](crate::observer::Observer), as this will not "retarget"
/// the event in any of Bevy's built-in [`Trigger`] implementations.
fn set_event_target(&mut self, entity: Entity);
}
impl World {
/// Generates the [`EventKey`] for this event type.
///
/// If this type has already been registered,
/// this will return the existing [`EventKey`].
///
/// This is used by various dynamically typed observer APIs,
/// such as [`DeferredWorld::trigger_raw`](crate::world::DeferredWorld::trigger_raw).
pub fn register_event_key<E: Event>(&mut self) -> EventKey {
EventKey(self.register_component::<EventWrapperComponent<E>>())
}
/// Fetches the [`EventKey`] for this event type,
/// if it has already been generated.
///
/// This is used by various dynamically typed observer APIs,
/// such as [`DeferredWorld::trigger_raw`](crate::world::DeferredWorld::trigger_raw).
pub fn event_key<E: Event>(&self) -> Option<EventKey> {
self.component_id::<EventWrapperComponent<E>>()
.map(EventKey)
}
}
/// An internal type that implements [`Component`] for a given [`Event`] type.
///
/// This exists so we can easily get access to a unique [`ComponentId`] for each [`Event`] type,
/// without requiring that [`Event`] types implement [`Component`] directly.
/// [`ComponentId`] is used internally as a unique identifier for events because they are:
///
/// - Unique to each event type.
/// - Can be quickly generated and looked up.
/// - Are compatible with dynamic event types, which aren't backed by a Rust type.
///
/// This type is an implementation detail and should never be made public.
// TODO: refactor events to store their metadata on distinct entities, rather than using `ComponentId`
#[derive(Component)]
struct EventWrapperComponent<E: Event>(PhantomData<E>);
/// A unique identifier for an [`Event`], used by [observers].
///
/// You can look up the key for your event by calling the [`World::event_key`] method.
///
/// [observers]: crate::observer
#[derive(Debug, Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq)]
pub struct EventKey(pub(crate) ComponentId);
#[cfg(test)]
mod tests {
use alloc::{vec, vec::Vec};
use bevy_ecs::{message::*, system::assert_is_read_only_system};
use bevy_ecs_macros::Message;
#[derive(Message, Copy, Clone, PartialEq, Eq, Debug)]
struct TestEvent {
i: usize,
}
#[derive(Message, Clone, PartialEq, Debug, Default)]
struct EmptyTestEvent;
fn get_events<E: Message + Clone>(
events: &Messages<E>,
cursor: &mut MessageCursor<E>,
) -> Vec<E> {
cursor.read(events).cloned().collect::<Vec<E>>()
}
#[test]
fn test_events() {
let mut events = Messages::<TestEvent>::default();
let event_0 = TestEvent { i: 0 };
let event_1 = TestEvent { i: 1 };
let event_2 = TestEvent { i: 2 };
// this reader will miss event_0 and event_1 because it wont read them over the course of
// two updates
let mut reader_missed: MessageCursor<TestEvent> = events.get_cursor();
let mut reader_a: MessageCursor<TestEvent> = events.get_cursor();
events.write(event_0);
assert_eq!(
get_events(&events, &mut reader_a),
vec![event_0],
"reader_a created before event receives event"
);
assert_eq!(
get_events(&events, &mut reader_a),
vec![],
"second iteration of reader_a created before event results in zero events"
);
let mut reader_b: MessageCursor<TestEvent> = events.get_cursor();
assert_eq!(
get_events(&events, &mut reader_b),
vec![event_0],
"reader_b created after event receives event"
);
assert_eq!(
get_events(&events, &mut reader_b),
vec![],
"second iteration of reader_b created after event results in zero events"
);
events.write(event_1);
let mut reader_c = events.get_cursor();
assert_eq!(
get_events(&events, &mut reader_c),
vec![event_0, event_1],
"reader_c created after two events receives both events"
);
assert_eq!(
get_events(&events, &mut reader_c),
vec![],
"second iteration of reader_c created after two event results in zero events"
);
assert_eq!(
get_events(&events, &mut reader_a),
vec![event_1],
"reader_a receives next unread event"
);
events.update();
let mut reader_d = events.get_cursor();
events.write(event_2);
assert_eq!(
get_events(&events, &mut reader_a),
vec![event_2],
"reader_a receives event created after update"
);
assert_eq!(
get_events(&events, &mut reader_b),
vec![event_1, event_2],
"reader_b receives events created before and after update"
);
assert_eq!(
get_events(&events, &mut reader_d),
vec![event_0, event_1, event_2],
"reader_d receives all events created before and after update"
);
events.update();
assert_eq!(
get_events(&events, &mut reader_missed),
vec![event_2],
"reader_missed missed events unread after two update() calls"
);
}
// Events Collection
fn events_clear_and_read_impl(clear_func: impl FnOnce(&mut Messages<TestEvent>)) {
let mut events = Messages::<TestEvent>::default();
let mut reader = events.get_cursor();
assert!(reader.read(&events).next().is_none());
events.write(TestEvent { i: 0 });
assert_eq!(*reader.read(&events).next().unwrap(), TestEvent { i: 0 });
assert_eq!(reader.read(&events).next(), None);
events.write(TestEvent { i: 1 });
clear_func(&mut events);
assert!(reader.read(&events).next().is_none());
events.write(TestEvent { i: 2 });
events.update();
events.write(TestEvent { i: 3 });
assert!(reader
.read(&events)
.eq([TestEvent { i: 2 }, TestEvent { i: 3 }].iter()));
}
#[test]
fn test_events_clear_and_read() {
events_clear_and_read_impl(Messages::clear);
}
#[test]
fn test_events_drain_and_read() {
events_clear_and_read_impl(|events| {
assert!(events
.drain()
.eq(vec![TestEvent { i: 0 }, TestEvent { i: 1 }].into_iter()));
});
}
#[test]
fn test_events_write_default() {
let mut events = Messages::<EmptyTestEvent>::default();
events.write_default();
let mut reader = events.get_cursor();
assert_eq!(get_events(&events, &mut reader), vec![EmptyTestEvent]);
}
#[test]
fn test_write_events_ids() {
let mut events = Messages::<TestEvent>::default();
let event_0 = TestEvent { i: 0 };
let event_1 = TestEvent { i: 1 };
let event_2 = TestEvent { i: 2 };
let event_0_id = events.write(event_0);
assert_eq!(
events.get_message(event_0_id.id),
Some((&event_0, event_0_id)),
"Getting a sent event by ID should return the original event"
);
let mut event_ids = events.write_batch([event_1, event_2]);
let event_id = event_ids.next().expect("Event 1 must have been sent");
assert_eq!(
events.get_message(event_id.id),
Some((&event_1, event_id)),
"Getting a sent event by ID should return the original event"
);
let event_id = event_ids.next().expect("Event 2 must have been sent");
assert_eq!(
events.get_message(event_id.id),
Some((&event_2, event_id)),
"Getting a sent event by ID should return the original event"
);
assert!(
event_ids.next().is_none(),
"Only sent two events; got more than two IDs"
);
}
#[test]
fn test_event_registry_can_add_and_remove_events_to_world() {
use bevy_ecs::prelude::*;
let mut world = World::new();
MessageRegistry::register_message::<TestEvent>(&mut world);
let has_events = world.get_resource::<Messages<TestEvent>>().is_some();
assert!(has_events, "Should have the events resource");
MessageRegistry::deregister_messages::<TestEvent>(&mut world);
let has_events = world.get_resource::<Messages<TestEvent>>().is_some();
assert!(!has_events, "Should not have the events resource");
}
#[test]
fn test_events_update_drain() {
let mut events = Messages::<TestEvent>::default();
let mut reader = events.get_cursor();
events.write(TestEvent { i: 0 });
events.write(TestEvent { i: 1 });
assert_eq!(reader.read(&events).count(), 2);
let mut old_events = Vec::from_iter(events.update_drain());
assert!(old_events.is_empty());
events.write(TestEvent { i: 2 });
assert_eq!(reader.read(&events).count(), 1);
old_events.extend(events.update_drain());
assert_eq!(old_events.len(), 2);
old_events.extend(events.update_drain());
assert_eq!(
old_events,
&[TestEvent { i: 0 }, TestEvent { i: 1 }, TestEvent { i: 2 }]
);
}
#[test]
fn test_events_empty() {
let mut events = Messages::<TestEvent>::default();
assert!(events.is_empty());
events.write(TestEvent { i: 0 });
assert!(!events.is_empty());
events.update();
assert!(!events.is_empty());
// events are only empty after the second call to update
// due to double buffering.
events.update();
assert!(events.is_empty());
}
#[test]
fn test_events_extend_impl() {
let mut events = Messages::<TestEvent>::default();
let mut reader = events.get_cursor();
events.extend(vec![TestEvent { i: 0 }, TestEvent { i: 1 }]);
assert!(reader
.read(&events)
.eq([TestEvent { i: 0 }, TestEvent { i: 1 }].iter()));
}
// Cursor
#[test]
fn test_event_cursor_read() {
let mut events = Messages::<TestEvent>::default();
let mut cursor = events.get_cursor();
assert!(cursor.read(&events).next().is_none());
events.write(TestEvent { i: 0 });
let sent_event = cursor.read(&events).next().unwrap();
assert_eq!(sent_event, &TestEvent { i: 0 });
assert!(cursor.read(&events).next().is_none());
events.write(TestEvent { i: 2 });
let sent_event = cursor.read(&events).next().unwrap();
assert_eq!(sent_event, &TestEvent { i: 2 });
assert!(cursor.read(&events).next().is_none());
events.clear();
assert!(cursor.read(&events).next().is_none());
}
#[test]
fn test_event_cursor_read_mut() {
let mut events = Messages::<TestEvent>::default();
let mut write_cursor = events.get_cursor();
let mut read_cursor = events.get_cursor();
assert!(write_cursor.read_mut(&mut events).next().is_none());
assert!(read_cursor.read(&events).next().is_none());
events.write(TestEvent { i: 0 });
let sent_event = write_cursor.read_mut(&mut events).next().unwrap();
assert_eq!(sent_event, &mut TestEvent { i: 0 });
*sent_event = TestEvent { i: 1 }; // Mutate whole event
assert_eq!(
read_cursor.read(&events).next().unwrap(),
&TestEvent { i: 1 }
);
assert!(read_cursor.read(&events).next().is_none());
events.write(TestEvent { i: 2 });
let sent_event = write_cursor.read_mut(&mut events).next().unwrap();
assert_eq!(sent_event, &mut TestEvent { i: 2 });
sent_event.i = 3; // Mutate sub value
assert_eq!(
read_cursor.read(&events).next().unwrap(),
&TestEvent { i: 3 }
);
assert!(read_cursor.read(&events).next().is_none());
events.clear();
assert!(write_cursor.read(&events).next().is_none());
assert!(read_cursor.read(&events).next().is_none());
}
#[test]
fn test_event_cursor_clear() {
let mut events = Messages::<TestEvent>::default();
let mut reader = events.get_cursor();
events.write(TestEvent { i: 0 });
assert_eq!(reader.len(&events), 1);
reader.clear(&events);
assert_eq!(reader.len(&events), 0);
}
#[test]
fn test_event_cursor_len_update() {
let mut events = Messages::<TestEvent>::default();
events.write(TestEvent { i: 0 });
events.write(TestEvent { i: 0 });
let reader = events.get_cursor();
assert_eq!(reader.len(&events), 2);
events.update();
events.write(TestEvent { i: 0 });
assert_eq!(reader.len(&events), 3);
events.update();
assert_eq!(reader.len(&events), 1);
events.update();
assert!(reader.is_empty(&events));
}
#[test]
fn test_event_cursor_len_current() {
let mut events = Messages::<TestEvent>::default();
events.write(TestEvent { i: 0 });
let reader = events.get_cursor_current();
assert!(reader.is_empty(&events));
events.write(TestEvent { i: 0 });
assert_eq!(reader.len(&events), 1);
assert!(!reader.is_empty(&events));
}
#[test]
fn test_event_cursor_iter_len_updated() {
let mut events = Messages::<TestEvent>::default();
events.write(TestEvent { i: 0 });
events.write(TestEvent { i: 1 });
events.write(TestEvent { i: 2 });
let mut reader = events.get_cursor();
let mut iter = reader.read(&events);
assert_eq!(iter.len(), 3);
iter.next();
assert_eq!(iter.len(), 2);
iter.next();
assert_eq!(iter.len(), 1);
iter.next();
assert_eq!(iter.len(), 0);
}
#[test]
fn test_event_cursor_len_empty() {
let events = Messages::<TestEvent>::default();
assert_eq!(events.get_cursor().len(&events), 0);
assert!(events.get_cursor().is_empty(&events));
}
#[test]
fn test_event_cursor_len_filled() {
let mut events = Messages::<TestEvent>::default();
events.write(TestEvent { i: 0 });
assert_eq!(events.get_cursor().len(&events), 1);
assert!(!events.get_cursor().is_empty(&events));
}
#[cfg(feature = "multi_threaded")]
#[test]
fn test_event_cursor_par_read() {
use crate::prelude::*;
use core::sync::atomic::{AtomicUsize, Ordering};
#[derive(Resource)]
struct Counter(AtomicUsize);
let mut world = World::new();
world.init_resource::<Messages<TestEvent>>();
for _ in 0..100 {
world.write_message(TestEvent { i: 1 });
}
let mut schedule = Schedule::default();
schedule.add_systems(
|mut cursor: Local<MessageCursor<TestEvent>>,
events: Res<Messages<TestEvent>>,
counter: ResMut<Counter>| {
cursor.par_read(&events).for_each(|event| {
counter.0.fetch_add(event.i, Ordering::Relaxed);
});
},
);
world.insert_resource(Counter(AtomicUsize::new(0)));
schedule.run(&mut world);
let counter = world.remove_resource::<Counter>().unwrap();
assert_eq!(counter.0.into_inner(), 100);
world.insert_resource(Counter(AtomicUsize::new(0)));
schedule.run(&mut world);
let counter = world.remove_resource::<Counter>().unwrap();
assert_eq!(
counter.0.into_inner(),
0,
"par_read should have consumed events but didn't"
);
}
#[cfg(feature = "multi_threaded")]
#[test]
fn test_event_cursor_par_read_mut() {
use crate::prelude::*;
use core::sync::atomic::{AtomicUsize, Ordering};
#[derive(Resource)]
struct Counter(AtomicUsize);
let mut world = World::new();
world.init_resource::<Messages<TestEvent>>();
for _ in 0..100 {
world.write_message(TestEvent { i: 1 });
}
let mut schedule = Schedule::default();
schedule.add_systems(
|mut cursor: Local<MessageCursor<TestEvent>>,
mut events: ResMut<Messages<TestEvent>>,
counter: ResMut<Counter>| {
cursor.par_read_mut(&mut events).for_each(|event| {
event.i += 1;
counter.0.fetch_add(event.i, Ordering::Relaxed);
});
},
);
world.insert_resource(Counter(AtomicUsize::new(0)));
schedule.run(&mut world);
let counter = world.remove_resource::<Counter>().unwrap();
assert_eq!(counter.0.into_inner(), 200, "Initial run failed");
world.insert_resource(Counter(AtomicUsize::new(0)));
schedule.run(&mut world);
let counter = world.remove_resource::<Counter>().unwrap();
assert_eq!(
counter.0.into_inner(),
0,
"par_read_mut should have consumed events but didn't"
);
}
// Reader & Mutator
#[test]
fn ensure_reader_readonly() {
fn reader_system(_: MessageReader<EmptyTestEvent>) {}
assert_is_read_only_system(reader_system);
}
#[test]
fn test_event_reader_iter_last() {
use bevy_ecs::prelude::*;
let mut world = World::new();
world.init_resource::<Messages<TestEvent>>();
let mut reader = IntoSystem::into_system(
|mut events: MessageReader<TestEvent>| -> Option<TestEvent> {
events.read().last().copied()
},
);
reader.initialize(&mut world);
let last = reader.run((), &mut world).unwrap();
assert!(last.is_none(), "MessageReader should be empty");
world.write_message(TestEvent { i: 0 });
let last = reader.run((), &mut world).unwrap();
assert_eq!(last, Some(TestEvent { i: 0 }));
world.write_message(TestEvent { i: 1 });
world.write_message(TestEvent { i: 2 });
world.write_message(TestEvent { i: 3 });
let last = reader.run((), &mut world).unwrap();
assert_eq!(last, Some(TestEvent { i: 3 }));
let last = reader.run((), &mut world).unwrap();
assert!(last.is_none(), "MessageReader should be empty");
}
#[test]
fn test_event_mutator_iter_last() {
use bevy_ecs::prelude::*;
let mut world = World::new();
world.init_resource::<Messages<TestEvent>>();
let mut mutator = IntoSystem::into_system(
|mut events: MessageMutator<TestEvent>| -> Option<TestEvent> {
events.read().last().copied()
},
);
mutator.initialize(&mut world);
let last = mutator.run((), &mut world).unwrap();
assert!(last.is_none(), "EventMutator should be empty");
world.write_message(TestEvent { i: 0 });
let last = mutator.run((), &mut world).unwrap();
assert_eq!(last, Some(TestEvent { i: 0 }));
world.write_message(TestEvent { i: 1 });
world.write_message(TestEvent { i: 2 });
world.write_message(TestEvent { i: 3 });
let last = mutator.run((), &mut world).unwrap();
assert_eq!(last, Some(TestEvent { i: 3 }));
let last = mutator.run((), &mut world).unwrap();
assert!(last.is_none(), "EventMutator should be empty");
}
#[test]
fn test_event_reader_iter_nth() {
use bevy_ecs::prelude::*;
let mut world = World::new();
world.init_resource::<Messages<TestEvent>>();
world.write_message(TestEvent { i: 0 });
world.write_message(TestEvent { i: 1 });
world.write_message(TestEvent { i: 2 });
world.write_message(TestEvent { i: 3 });
world.write_message(TestEvent { i: 4 });
let mut schedule = Schedule::default();
schedule.add_systems(|mut events: MessageReader<TestEvent>| {
let mut iter = events.read();
assert_eq!(iter.next(), Some(&TestEvent { i: 0 }));
assert_eq!(iter.nth(2), Some(&TestEvent { i: 3 }));
assert_eq!(iter.nth(1), None);
assert!(events.is_empty());
});
schedule.run(&mut world);
}
#[test]
fn test_event_mutator_iter_nth() {
use bevy_ecs::prelude::*;
let mut world = World::new();
world.init_resource::<Messages<TestEvent>>();
world.write_message(TestEvent { i: 0 });
world.write_message(TestEvent { i: 1 });
world.write_message(TestEvent { i: 2 });
world.write_message(TestEvent { i: 3 });
world.write_message(TestEvent { i: 4 });
let mut schedule = Schedule::default();
schedule.add_systems(|mut events: MessageReader<TestEvent>| {
let mut iter = events.read();
assert_eq!(iter.next(), Some(&TestEvent { i: 0 }));
assert_eq!(iter.nth(2), Some(&TestEvent { i: 3 }));
assert_eq!(iter.nth(1), None);
assert!(events.is_empty());
});
schedule.run(&mut world);
}
#[test]
| 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/message/messages.rs | crates/bevy_ecs/src/message/messages.rs | use crate::{
change_detection::MaybeLocation,
message::{Message, MessageCursor, MessageId, MessageInstance},
resource::Resource,
};
use alloc::vec::Vec;
use core::{
marker::PhantomData,
ops::{Deref, DerefMut},
};
#[cfg(feature = "bevy_reflect")]
use {
crate::reflect::ReflectResource,
bevy_reflect::{std_traits::ReflectDefault, Reflect},
};
/// A message collection that represents the messages that occurred within the last two
/// [`Messages::update`] calls.
/// Messages can be written to using a [`MessageWriter`]
/// and are typically cheaply read using a [`MessageReader`].
///
/// Each message can be consumed by multiple systems, in parallel,
/// with consumption tracked by the [`MessageReader`] on a per-system basis.
///
/// If no [ordering](https://github.com/bevyengine/bevy/blob/main/examples/ecs/ecs_guide.rs)
/// is applied between writing and reading systems, there is a risk of a race condition.
/// This means that whether the messages arrive before or after the next [`Messages::update`] is unpredictable.
///
/// This collection is meant to be paired with a system that calls
/// [`Messages::update`] exactly once per update/frame.
///
/// [`message_update_system`] is a system that does this, typically initialized automatically using
/// [`add_message`](https://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_message).
/// [`MessageReader`]s are expected to read messages from this collection at least once per loop/frame.
/// Messages will persist across a single frame boundary and so ordering of message producers and
/// consumers is not critical (although poorly-planned ordering may cause accumulating lag).
/// If messages are not handled by the end of the frame after they are updated, they will be
/// dropped silently.
///
/// # Example
///
/// ```
/// use bevy_ecs::message::{Message, Messages};
///
/// #[derive(Message)]
/// struct MyMessage {
/// value: usize
/// }
///
/// // setup
/// let mut messages = Messages::<MyMessage>::default();
/// let mut cursor = messages.get_cursor();
///
/// // run this once per update/frame
/// messages.update();
///
/// // somewhere else: write a message
/// messages.write(MyMessage { value: 1 });
///
/// // somewhere else: read the messages
/// for message in cursor.read(&messages) {
/// assert_eq!(message.value, 1)
/// }
///
/// // messages are only processed once per reader
/// assert_eq!(cursor.read(&messages).count(), 0);
/// ```
///
/// # Details
///
/// [`Messages`] is implemented using a variation of a double buffer strategy.
/// Each call to [`update`](Messages::update) swaps buffers and clears out the oldest one.
/// - [`MessageReader`]s will read messages from both buffers.
/// - [`MessageReader`]s that read at least once per update will never drop messages.
/// - [`MessageReader`]s that read once within two updates might still receive some messages
/// - [`MessageReader`]s that read after two updates are guaranteed to drop all messages that occurred
/// before those updates.
///
/// The buffers in [`Messages`] will grow indefinitely if [`update`](Messages::update) is never called.
///
/// An alternative call pattern would be to call [`update`](Messages::update)
/// manually across frames to control when messages are cleared.
/// This complicates consumption and risks ever-expanding memory usage if not cleaned up,
/// but can be done by adding your message as a resource instead of using
/// [`add_message`](https://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_message).
///
/// [Example usage.](https://github.com/bevyengine/bevy/blob/latest/examples/ecs/message.rs)
/// [Example usage standalone.](https://github.com/bevyengine/bevy/blob/latest/crates/bevy_ecs/examples/messages.rs)
///
/// [`MessageReader`]: super::MessageReader
/// [`MessageWriter`]: super::MessageWriter
/// [`message_update_system`]: super::message_update_system
#[derive(Debug, Resource)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Resource, Default))]
pub struct Messages<E: Message> {
/// Holds the oldest still active messages.
/// Note that `a.start_message_count + a.len()` should always be equal to `messages_b.start_message_count`.
pub(crate) messages_a: MessageSequence<E>,
/// Holds the newer messages.
pub(crate) messages_b: MessageSequence<E>,
pub(crate) message_count: usize,
}
// Derived Default impl would incorrectly require E: Default
impl<E: Message> Default for Messages<E> {
fn default() -> Self {
Self {
messages_a: Default::default(),
messages_b: Default::default(),
message_count: Default::default(),
}
}
}
impl<M: Message> Messages<M> {
/// Returns the index of the oldest message stored in the message buffer.
pub fn oldest_message_count(&self) -> usize {
self.messages_a.start_message_count
}
/// Writes an `message` to the current message buffer.
/// [`MessageReader`](super::MessageReader)s can then read the message.
/// This method returns the [ID](`MessageId`) of the written `message`.
#[track_caller]
pub fn write(&mut self, message: M) -> MessageId<M> {
self.write_with_caller(message, MaybeLocation::caller())
}
pub(crate) fn write_with_caller(&mut self, message: M, caller: MaybeLocation) -> MessageId<M> {
let message_id = MessageId {
id: self.message_count,
caller,
_marker: PhantomData,
};
#[cfg(feature = "detailed_trace")]
tracing::trace!("Messages::write() -> id: {}", message_id);
let message_instance = MessageInstance {
message_id,
message,
};
self.messages_b.push(message_instance);
self.message_count += 1;
message_id
}
/// Writes a list of `messages` all at once, which can later be read by [`MessageReader`](super::MessageReader)s.
/// This is more efficient than writing each message individually.
/// This method returns the [IDs](`MessageId`) of the written `messages`.
#[track_caller]
pub fn write_batch(&mut self, messages: impl IntoIterator<Item = M>) -> WriteBatchIds<M> {
let last_count = self.message_count;
self.extend(messages);
WriteBatchIds {
last_count,
message_count: self.message_count,
_marker: PhantomData,
}
}
/// Writes the default value of the message. Useful when the message is an empty struct.
/// This method returns the [ID](`MessageId`) of the written `message`.
#[track_caller]
pub fn write_default(&mut self) -> MessageId<M>
where
M: Default,
{
self.write(Default::default())
}
/// Gets a new [`MessageCursor`]. This will include all messages already in the message buffers.
pub fn get_cursor(&self) -> MessageCursor<M> {
MessageCursor::default()
}
/// Gets a new [`MessageCursor`]. This will ignore all messages already in the message buffers.
/// It will read all future messages.
pub fn get_cursor_current(&self) -> MessageCursor<M> {
MessageCursor {
last_message_count: self.message_count,
..Default::default()
}
}
/// Swaps the message buffers and clears the oldest message buffer. In general, this should be
/// called once per frame/update.
///
/// If you need access to the messages that were removed, consider using [`Messages::update_drain`].
pub fn update(&mut self) {
core::mem::swap(&mut self.messages_a, &mut self.messages_b);
self.messages_b.clear();
self.messages_b.start_message_count = self.message_count;
debug_assert_eq!(
self.messages_a.start_message_count + self.messages_a.len(),
self.messages_b.start_message_count
);
}
/// Swaps the message buffers and drains the oldest message buffer, returning an iterator
/// of all messages that were removed. In general, this should be called once per frame/update.
///
/// If you do not need to take ownership of the removed messages, use [`Messages::update`] instead.
#[must_use = "If you do not need the returned messages, call .update() instead."]
pub fn update_drain(&mut self) -> impl Iterator<Item = M> + '_ {
core::mem::swap(&mut self.messages_a, &mut self.messages_b);
let iter = self.messages_b.messages.drain(..);
self.messages_b.start_message_count = self.message_count;
debug_assert_eq!(
self.messages_a.start_message_count + self.messages_a.len(),
self.messages_b.start_message_count
);
iter.map(|e| e.message)
}
#[inline]
fn reset_start_message_count(&mut self) {
self.messages_a.start_message_count = self.message_count;
self.messages_b.start_message_count = self.message_count;
}
/// Removes all messages.
#[inline]
pub fn clear(&mut self) {
self.reset_start_message_count();
self.messages_a.clear();
self.messages_b.clear();
}
/// Returns the number of messages currently stored in the message buffer.
#[inline]
pub fn len(&self) -> usize {
self.messages_a.len() + self.messages_b.len()
}
/// Returns true if there are no messages currently stored in the message buffer.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Creates a draining iterator that removes all messages.
pub fn drain(&mut self) -> impl Iterator<Item = M> + '_ {
self.reset_start_message_count();
// Drain the oldest messages first, then the newest
self.messages_a
.drain(..)
.chain(self.messages_b.drain(..))
.map(|i| i.message)
}
/// Iterates over messages that happened since the last "update" call.
/// WARNING: You probably don't want to use this call. In most cases you should use an
/// [`MessageReader`]. You should only use this if you know you only need to consume messages
/// between the last `update()` call and your call to `iter_current_update_messages`.
/// If messages happen outside that window, they will not be handled. For example, any messages that
/// happen after this call and before the next `update()` call will be dropped.
///
/// [`MessageReader`]: super::MessageReader
pub fn iter_current_update_messages(&self) -> impl ExactSizeIterator<Item = &M> {
self.messages_b.iter().map(|i| &i.message)
}
/// Get a specific message by id if it still exists in the messages buffer.
pub fn get_message(&self, id: usize) -> Option<(&M, MessageId<M>)> {
if id < self.oldest_message_count() {
return None;
}
let sequence = self.sequence(id);
let index = id.saturating_sub(sequence.start_message_count);
sequence
.get(index)
.map(|instance| (&instance.message, instance.message_id))
}
/// Which message buffer is this message id a part of.
fn sequence(&self, id: usize) -> &MessageSequence<M> {
if id < self.messages_b.start_message_count {
&self.messages_a
} else {
&self.messages_b
}
}
}
impl<E: Message> Extend<E> for Messages<E> {
#[track_caller]
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = E>,
{
let old_count = self.message_count;
let mut message_count = self.message_count;
let messages = iter.into_iter().map(|message| {
let message_id = MessageId {
id: message_count,
caller: MaybeLocation::caller(),
_marker: PhantomData,
};
message_count += 1;
MessageInstance {
message_id,
message,
}
});
self.messages_b.extend(messages);
if old_count != message_count {
#[cfg(feature = "detailed_trace")]
tracing::trace!(
"Messages::extend() -> ids: ({}..{})",
self.message_count,
message_count
);
}
self.message_count = message_count;
}
}
#[derive(Debug)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Default))]
pub(crate) struct MessageSequence<E: Message> {
pub(crate) messages: Vec<MessageInstance<E>>,
pub(crate) start_message_count: usize,
}
// Derived Default impl would incorrectly require E: Default
impl<E: Message> Default for MessageSequence<E> {
fn default() -> Self {
Self {
messages: Default::default(),
start_message_count: Default::default(),
}
}
}
impl<E: Message> Deref for MessageSequence<E> {
type Target = Vec<MessageInstance<E>>;
fn deref(&self) -> &Self::Target {
&self.messages
}
}
impl<E: Message> DerefMut for MessageSequence<E> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.messages
}
}
/// [`Iterator`] over written [`MessageIds`](`MessageId`) from a batch.
pub struct WriteBatchIds<E> {
last_count: usize,
message_count: usize,
_marker: PhantomData<E>,
}
impl<E: Message> Iterator for WriteBatchIds<E> {
type Item = MessageId<E>;
fn next(&mut self) -> Option<Self::Item> {
if self.last_count >= self.message_count {
return None;
}
let result = Some(MessageId {
id: self.last_count,
caller: MaybeLocation::caller(),
_marker: PhantomData,
});
self.last_count += 1;
result
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = <Self as ExactSizeIterator>::len(self);
(len, Some(len))
}
}
impl<E: Message> ExactSizeIterator for WriteBatchIds<E> {
fn len(&self) -> usize {
self.message_count.saturating_sub(self.last_count)
}
}
#[cfg(test)]
mod tests {
use crate::message::{Message, Messages};
#[test]
fn iter_current_update_messages_iterates_over_current_messages() {
#[derive(Message, Clone)]
struct TestMessage;
let mut test_messages = Messages::<TestMessage>::default();
// Starting empty
assert_eq!(test_messages.len(), 0);
assert_eq!(test_messages.iter_current_update_messages().count(), 0);
test_messages.update();
// Writing one message
test_messages.write(TestMessage);
assert_eq!(test_messages.len(), 1);
assert_eq!(test_messages.iter_current_update_messages().count(), 1);
test_messages.update();
// Writing two messages on the next frame
test_messages.write(TestMessage);
test_messages.write(TestMessage);
assert_eq!(test_messages.len(), 3); // Messages are double-buffered, so we see 1 + 2 = 3
assert_eq!(test_messages.iter_current_update_messages().count(), 2);
test_messages.update();
// Writing zero messages
assert_eq!(test_messages.len(), 2); // Messages are double-buffered, so we see 2 + 0 = 2
assert_eq!(test_messages.iter_current_update_messages().count(), 0);
}
#[test]
fn write_batch_iter_size_hint() {
#[derive(Message, Clone, Copy)]
struct TestMessage;
let mut test_messages = Messages::<TestMessage>::default();
let write_batch_ids = test_messages.write_batch([TestMessage; 4]);
let expected_len = 4;
assert_eq!(write_batch_ids.len(), expected_len);
assert_eq!(
write_batch_ids.size_hint(),
(expected_len, Some(expected_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/message/mut_iterators.rs | crates/bevy_ecs/src/message/mut_iterators.rs | #[cfg(feature = "multi_threaded")]
use crate::batching::BatchingStrategy;
use crate::message::{Message, MessageCursor, MessageId, MessageInstance, Messages};
use core::{iter::Chain, slice::IterMut};
/// An iterator that yields any unread messages from an [`MessageMutator`] or [`MessageCursor`].
///
/// [`MessageMutator`]: super::MessageMutator
#[derive(Debug)]
pub struct MessageMutIterator<'a, E: Message> {
iter: MessageMutIteratorWithId<'a, E>,
}
impl<'a, E: Message> Iterator for MessageMutIterator<'a, E> {
type Item = &'a mut E;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(message, _)| message)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
fn count(self) -> usize {
self.iter.count()
}
fn last(self) -> Option<Self::Item>
where
Self: Sized,
{
self.iter.last().map(|(message, _)| message)
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
self.iter.nth(n).map(|(message, _)| message)
}
}
impl<'a, E: Message> ExactSizeIterator for MessageMutIterator<'a, E> {
fn len(&self) -> usize {
self.iter.len()
}
}
/// An iterator that yields any unread messages (and their IDs) from an [`MessageMutator`] or [`MessageCursor`].
///
/// [`MessageMutator`]: super::MessageMutator
#[derive(Debug)]
pub struct MessageMutIteratorWithId<'a, E: Message> {
mutator: &'a mut MessageCursor<E>,
chain: Chain<IterMut<'a, MessageInstance<E>>, IterMut<'a, MessageInstance<E>>>,
unread: usize,
}
impl<'a, E: Message> MessageMutIteratorWithId<'a, E> {
/// Creates a new iterator that yields any `messages` that have not yet been seen by `mutator`.
pub fn new(mutator: &'a mut MessageCursor<E>, messages: &'a mut Messages<E>) -> Self {
let a_index = mutator
.last_message_count
.saturating_sub(messages.messages_a.start_message_count);
let b_index = mutator
.last_message_count
.saturating_sub(messages.messages_b.start_message_count);
let a = messages.messages_a.get_mut(a_index..).unwrap_or_default();
let b = messages.messages_b.get_mut(b_index..).unwrap_or_default();
let unread_count = a.len() + b.len();
mutator.last_message_count = messages.message_count - unread_count;
// Iterate the oldest first, then the newer messages
let chain = a.iter_mut().chain(b.iter_mut());
Self {
mutator,
chain,
unread: unread_count,
}
}
/// Iterate over only the messages.
pub fn without_id(self) -> MessageMutIterator<'a, E> {
MessageMutIterator { iter: self }
}
}
impl<'a, E: Message> Iterator for MessageMutIteratorWithId<'a, E> {
type Item = (&'a mut E, MessageId<E>);
fn next(&mut self) -> Option<Self::Item> {
match self
.chain
.next()
.map(|instance| (&mut instance.message, instance.message_id))
{
Some(item) => {
#[cfg(feature = "detailed_trace")]
tracing::trace!("MessageMutator::iter() -> {}", item.1);
self.mutator.last_message_count += 1;
self.unread -= 1;
Some(item)
}
None => None,
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.chain.size_hint()
}
fn count(self) -> usize {
self.mutator.last_message_count += self.unread;
self.unread
}
fn last(self) -> Option<Self::Item>
where
Self: Sized,
{
let MessageInstance {
message_id,
message,
} = self.chain.last()?;
self.mutator.last_message_count += self.unread;
Some((message, *message_id))
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
if let Some(MessageInstance {
message_id,
message,
}) = self.chain.nth(n)
{
self.mutator.last_message_count += n + 1;
self.unread -= n + 1;
Some((message, *message_id))
} else {
self.mutator.last_message_count += self.unread;
self.unread = 0;
None
}
}
}
impl<'a, E: Message> ExactSizeIterator for MessageMutIteratorWithId<'a, E> {
fn len(&self) -> usize {
self.unread
}
}
/// A parallel iterator over `Message`s.
#[derive(Debug)]
#[cfg(feature = "multi_threaded")]
pub struct MessageMutParIter<'a, E: Message> {
mutator: &'a mut MessageCursor<E>,
slices: [&'a mut [MessageInstance<E>]; 2],
batching_strategy: BatchingStrategy,
#[cfg(not(target_arch = "wasm32"))]
unread: usize,
}
#[cfg(feature = "multi_threaded")]
impl<'a, E: Message> MessageMutParIter<'a, E> {
/// Creates a new parallel iterator over `messages` that have not yet been seen by `mutator`.
pub fn new(mutator: &'a mut MessageCursor<E>, messages: &'a mut Messages<E>) -> Self {
let a_index = mutator
.last_message_count
.saturating_sub(messages.messages_a.start_message_count);
let b_index = mutator
.last_message_count
.saturating_sub(messages.messages_b.start_message_count);
let a = messages.messages_a.get_mut(a_index..).unwrap_or_default();
let b = messages.messages_b.get_mut(b_index..).unwrap_or_default();
let unread_count = a.len() + b.len();
mutator.last_message_count = messages.message_count - unread_count;
Self {
mutator,
slices: [a, b],
batching_strategy: BatchingStrategy::default(),
#[cfg(not(target_arch = "wasm32"))]
unread: unread_count,
}
}
/// 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 the provided closure for each unread message in parallel.
///
/// Unlike normal iteration, the message order is not guaranteed in any form.
///
/// # Panics
/// If the [`ComputeTaskPool`] is not initialized. If using this from a message reader that is being
/// initialized and run from the ECS scheduler, this should never panic.
///
/// [`ComputeTaskPool`]: bevy_tasks::ComputeTaskPool
pub fn for_each<FN: Fn(&'a mut E) + Send + Sync + Clone>(self, func: FN) {
self.for_each_with_id(move |e, _| func(e));
}
/// Runs the provided closure for each unread message in parallel, like [`for_each`](Self::for_each),
/// but additionally provides the `MessageId` to the closure.
///
/// Note that the order of iteration is not guaranteed, but `MessageId`s are ordered by send order.
///
/// # Panics
/// If the [`ComputeTaskPool`] is not initialized. If using this from a message reader that is being
/// initialized and run from the ECS scheduler, this should never panic.
///
/// [`ComputeTaskPool`]: bevy_tasks::ComputeTaskPool
#[cfg_attr(
target_arch = "wasm32",
expect(unused_mut, reason = "not mutated on this target")
)]
pub fn for_each_with_id<FN: Fn(&'a mut E, MessageId<E>) + Send + Sync + Clone>(
mut self,
func: FN,
) {
#[cfg(target_arch = "wasm32")]
{
self.into_iter().for_each(|(e, i)| func(e, i));
}
#[cfg(not(target_arch = "wasm32"))]
{
let pool = bevy_tasks::ComputeTaskPool::get();
let thread_count = pool.thread_num();
if thread_count <= 1 {
return self.into_iter().for_each(|(e, i)| func(e, i));
}
let batch_size = self
.batching_strategy
.calc_batch_size(|| self.len(), thread_count);
let chunks = self.slices.map(|s| s.chunks_mut(batch_size));
pool.scope(|scope| {
for batch in chunks.into_iter().flatten() {
let func = func.clone();
scope.spawn(async move {
for message_instance in batch {
func(&mut message_instance.message, message_instance.message_id);
}
});
}
});
// Messages are guaranteed to be read at this point.
self.mutator.last_message_count += self.unread;
self.unread = 0;
}
}
/// Returns the number of [`Message`]s to be iterated.
pub fn len(&self) -> usize {
self.slices.iter().map(|s| s.len()).sum()
}
/// Returns [`true`]Β if there are no messages remaining in this iterator.
pub fn is_empty(&self) -> bool {
self.slices.iter().all(|x| x.is_empty())
}
}
#[cfg(feature = "multi_threaded")]
impl<'a, E: Message> IntoIterator for MessageMutParIter<'a, E> {
type IntoIter = MessageMutIteratorWithId<'a, E>;
type Item = <Self::IntoIter as Iterator>::Item;
fn into_iter(self) -> Self::IntoIter {
let MessageMutParIter {
mutator: reader,
slices: [a, b],
..
} = self;
let unread = a.len() + b.len();
let chain = a.iter_mut().chain(b);
MessageMutIteratorWithId {
mutator: reader,
chain,
unread,
}
}
}
| 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/message/update.rs | crates/bevy_ecs/src/message/update.rs | use crate::{
change_detection::Mut,
change_detection::Tick,
message::{MessageRegistry, ShouldUpdateMessages},
system::{Local, Res, ResMut},
world::World,
};
use bevy_ecs_macros::SystemSet;
#[cfg(feature = "bevy_reflect")]
use core::hash::Hash;
#[doc(hidden)]
#[derive(SystemSet, Clone, Debug, PartialEq, Eq, Hash)]
pub struct MessageUpdateSystems;
/// Signals the [`message_update_system`] to run after `FixedUpdate` systems.
///
/// This will change the behavior of the [`MessageRegistry`] to only run after a fixed update cycle has passed.
/// Normally, this will simply run every frame.
pub fn signal_message_update_system(signal: Option<ResMut<MessageRegistry>>) {
if let Some(mut registry) = signal {
registry.should_update = ShouldUpdateMessages::Ready;
}
}
/// A system that calls [`Messages::update`](super::Messages::update) on all registered [`Messages`][super::Messages] in the world.
pub fn message_update_system(world: &mut World, mut last_change_tick: Local<Tick>) {
world.try_resource_scope(|world, mut registry: Mut<MessageRegistry>| {
registry.run_updates(world, *last_change_tick);
registry.should_update = match registry.should_update {
// If we're always updating, keep doing so.
ShouldUpdateMessages::Always => ShouldUpdateMessages::Always,
// Disable the system until signal_message_update_system runs again.
ShouldUpdateMessages::Waiting | ShouldUpdateMessages::Ready => {
ShouldUpdateMessages::Waiting
}
};
});
*last_change_tick = world.change_tick();
}
/// A run condition for [`message_update_system`].
///
/// If [`signal_message_update_system`] has been run at least once,
/// we will wait for it to be run again before updating the messages.
///
/// Otherwise, we will always update the messages.
pub fn message_update_condition(maybe_signal: Option<Res<MessageRegistry>>) -> bool {
match maybe_signal {
Some(signal) => match signal.should_update {
ShouldUpdateMessages::Always | ShouldUpdateMessages::Ready => true,
ShouldUpdateMessages::Waiting => false,
},
None => true,
}
}
| 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/message/iterators.rs | crates/bevy_ecs/src/message/iterators.rs | #[cfg(feature = "multi_threaded")]
use crate::batching::BatchingStrategy;
use crate::message::{Message, MessageCursor, MessageId, MessageInstance, Messages};
use core::{iter::Chain, slice::Iter};
/// An iterator that yields any unread messages from a [`MessageReader`](super::MessageReader) or [`MessageCursor`].
#[derive(Debug)]
pub struct MessageIterator<'a, M: Message> {
iter: MessageIteratorWithId<'a, M>,
}
impl<'a, M: Message> Iterator for MessageIterator<'a, M> {
type Item = &'a M;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(message, _)| message)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
fn count(self) -> usize {
self.iter.count()
}
fn last(self) -> Option<Self::Item>
where
Self: Sized,
{
self.iter.last().map(|(message, _)| message)
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
self.iter.nth(n).map(|(message, _)| message)
}
}
impl<'a, M: Message> ExactSizeIterator for MessageIterator<'a, M> {
fn len(&self) -> usize {
self.iter.len()
}
}
/// An iterator that yields any unread messages (and their IDs) from a [`MessageReader`](super::MessageReader) or [`MessageCursor`].
#[derive(Debug)]
pub struct MessageIteratorWithId<'a, M: Message> {
reader: &'a mut MessageCursor<M>,
chain: Chain<Iter<'a, MessageInstance<M>>, Iter<'a, MessageInstance<M>>>,
unread: usize,
}
impl<'a, M: Message> MessageIteratorWithId<'a, M> {
/// Creates a new iterator that yields any `messages` that have not yet been seen by `reader`.
pub fn new(reader: &'a mut MessageCursor<M>, messages: &'a Messages<M>) -> Self {
let a_index = reader
.last_message_count
.saturating_sub(messages.messages_a.start_message_count);
let b_index = reader
.last_message_count
.saturating_sub(messages.messages_b.start_message_count);
let a = messages.messages_a.get(a_index..).unwrap_or_default();
let b = messages.messages_b.get(b_index..).unwrap_or_default();
let unread_count = a.len() + b.len();
// Ensure `len` is implemented correctly
debug_assert_eq!(unread_count, reader.len(messages));
reader.last_message_count = messages.message_count - unread_count;
// Iterate the oldest first, then the newer messages
let chain = a.iter().chain(b.iter());
Self {
reader,
chain,
unread: unread_count,
}
}
/// Iterate over only the messages.
pub fn without_id(self) -> MessageIterator<'a, M> {
MessageIterator { iter: self }
}
}
impl<'a, M: Message> Iterator for MessageIteratorWithId<'a, M> {
type Item = (&'a M, MessageId<M>);
fn next(&mut self) -> Option<Self::Item> {
match self
.chain
.next()
.map(|instance| (&instance.message, instance.message_id))
{
Some(item) => {
#[cfg(feature = "detailed_trace")]
tracing::trace!("MessageReader::iter() -> {}", item.1);
self.reader.last_message_count += 1;
self.unread -= 1;
Some(item)
}
None => None,
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.chain.size_hint()
}
fn count(self) -> usize {
self.reader.last_message_count += self.unread;
self.unread
}
fn last(self) -> Option<Self::Item>
where
Self: Sized,
{
let MessageInstance {
message_id,
message,
} = self.chain.last()?;
self.reader.last_message_count += self.unread;
Some((message, *message_id))
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
if let Some(MessageInstance {
message_id,
message,
}) = self.chain.nth(n)
{
self.reader.last_message_count += n + 1;
self.unread -= n + 1;
Some((message, *message_id))
} else {
self.reader.last_message_count += self.unread;
self.unread = 0;
None
}
}
}
impl<'a, M: Message> ExactSizeIterator for MessageIteratorWithId<'a, M> {
fn len(&self) -> usize {
self.unread
}
}
/// A parallel iterator over `Message`s.
#[cfg(feature = "multi_threaded")]
#[derive(Debug)]
pub struct MessageParIter<'a, M: Message> {
reader: &'a mut MessageCursor<M>,
slices: [&'a [MessageInstance<M>]; 2],
batching_strategy: BatchingStrategy,
#[cfg(not(target_arch = "wasm32"))]
unread: usize,
}
#[cfg(feature = "multi_threaded")]
impl<'a, M: Message> MessageParIter<'a, M> {
/// Creates a new parallel iterator over `messages` that have not yet been seen by `reader`.
pub fn new(reader: &'a mut MessageCursor<M>, messages: &'a Messages<M>) -> Self {
let a_index = reader
.last_message_count
.saturating_sub(messages.messages_a.start_message_count);
let b_index = reader
.last_message_count
.saturating_sub(messages.messages_b.start_message_count);
let a = messages.messages_a.get(a_index..).unwrap_or_default();
let b = messages.messages_b.get(b_index..).unwrap_or_default();
let unread_count = a.len() + b.len();
// Ensure `len` is implemented correctly
debug_assert_eq!(unread_count, reader.len(messages));
reader.last_message_count = messages.message_count - unread_count;
Self {
reader,
slices: [a, b],
batching_strategy: BatchingStrategy::default(),
#[cfg(not(target_arch = "wasm32"))]
unread: unread_count,
}
}
/// 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 the provided closure for each unread message in parallel.
///
/// Unlike normal iteration, the message order is not guaranteed in any form.
///
/// # Panics
/// If the [`ComputeTaskPool`] is not initialized. If using this from a message reader that is being
/// initialized and run from the ECS scheduler, this should never panic.
///
/// [`ComputeTaskPool`]: bevy_tasks::ComputeTaskPool
pub fn for_each<FN: Fn(&'a M) + Send + Sync + Clone>(self, func: FN) {
self.for_each_with_id(move |e, _| func(e));
}
/// Runs the provided closure for each unread message in parallel, like [`for_each`](Self::for_each),
/// but additionally provides the [`MessageId`] to the closure.
///
/// Note that the order of iteration is not guaranteed, but [`MessageId`]s are ordered by send order.
///
/// # Panics
/// If the [`ComputeTaskPool`] is not initialized. If using this from a message reader that is being
/// initialized and run from the ECS scheduler, this should never panic.
///
/// [`ComputeTaskPool`]: bevy_tasks::ComputeTaskPool
#[cfg_attr(
target_arch = "wasm32",
expect(unused_mut, reason = "not mutated on this target")
)]
pub fn for_each_with_id<FN: Fn(&'a M, MessageId<M>) + Send + Sync + Clone>(mut self, func: FN) {
#[cfg(target_arch = "wasm32")]
{
self.into_iter().for_each(|(e, i)| func(e, i));
}
#[cfg(not(target_arch = "wasm32"))]
{
let pool = bevy_tasks::ComputeTaskPool::get();
let thread_count = pool.thread_num();
if thread_count <= 1 {
return self.into_iter().for_each(|(e, i)| func(e, i));
}
let batch_size = self
.batching_strategy
.calc_batch_size(|| self.len(), thread_count);
let chunks = self.slices.map(|s| s.chunks_exact(batch_size));
let remainders = chunks.each_ref().map(core::slice::ChunksExact::remainder);
pool.scope(|scope| {
for batch in chunks.into_iter().flatten().chain(remainders) {
let func = func.clone();
scope.spawn(async move {
for message_instance in batch {
func(&message_instance.message, message_instance.message_id);
}
});
}
});
// Messages are guaranteed to be read at this point.
self.reader.last_message_count += self.unread;
self.unread = 0;
}
}
/// Returns the number of [`Message`]s to be iterated.
pub fn len(&self) -> usize {
self.slices.iter().map(|s| s.len()).sum()
}
/// Returns [`true`]Β if there are no messages remaining in this iterator.
pub fn is_empty(&self) -> bool {
self.slices.iter().all(|x| x.is_empty())
}
}
#[cfg(feature = "multi_threaded")]
impl<'a, M: Message> IntoIterator for MessageParIter<'a, M> {
type IntoIter = MessageIteratorWithId<'a, M>;
type Item = <Self::IntoIter as Iterator>::Item;
fn into_iter(self) -> Self::IntoIter {
let MessageParIter {
reader,
slices: [a, b],
..
} = self;
let unread = a.len() + b.len();
let chain = a.iter().chain(b);
MessageIteratorWithId {
reader,
chain,
unread,
}
}
}
| 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/message/mod.rs | crates/bevy_ecs/src/message/mod.rs | //! [`Message`] functionality.
mod iterators;
mod message_cursor;
mod message_mutator;
mod message_reader;
mod message_registry;
mod message_writer;
mod messages;
mod mut_iterators;
mod update;
pub use iterators::*;
pub use message_cursor::*;
pub use message_mutator::*;
pub use message_reader::*;
pub use message_registry::*;
pub use message_writer::*;
pub use messages::*;
pub use mut_iterators::*;
pub use update::*;
pub use bevy_ecs_macros::Message;
use crate::change_detection::MaybeLocation;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
use core::{
cmp::Ordering,
fmt,
hash::{Hash, Hasher},
marker::PhantomData,
};
/// A buffered message for pull-based event handling.
///
/// Messages can be written with [`MessageWriter`] and read using the [`MessageReader`] system parameter.
/// Messages are stored in the [`Messages<M>`] resource, and require periodically polling the world for new messages,
/// typically in a system that runs as part of a schedule.
///
/// While the polling imposes a small overhead, messages are useful for efficiently batch processing
/// a large number of messages at once. For cases like these, messages can be more efficient than [`Event`]s (which are handled via [`Observer`]s).
///
/// Unlike [`Event`]s triggered for observers, messages are evaluated at fixed points in the schedule
/// rather than immediately when they are sent. This allows for more predictable scheduling, and deferring
/// message processing to a later point in time.
///
/// Messages must be thread-safe.
///
/// # Usage
///
/// The [`Message`] trait can be derived:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// #[derive(Message)]
/// struct Greeting(String);
/// ```
///
/// The message can then be written to the message buffer using a [`MessageWriter`]:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// # #[derive(Message)]
/// # struct Greeting(String);
/// #
/// fn write_hello(mut writer: MessageWriter<Greeting>) {
/// writer.write(Greeting("Hello!".to_string()));
/// }
/// ```
///
/// Messages can be efficiently read using a [`MessageReader`]:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// # #[derive(Message)]
/// # struct Greeting(String);
/// #
/// fn read_messages(mut reader: MessageReader<Greeting>) {
/// // Process all messages of type `Greeting`.
/// for Greeting(greeting) in reader.read() {
/// println!("{greeting}");
/// }
/// }
/// ```
/// [`Event`]: crate::event::Event
/// [`Observer`]: crate::observer::Observer
#[diagnostic::on_unimplemented(
message = "`{Self}` is not an `Message`",
label = "invalid `Message`",
note = "consider annotating `{Self}` with `#[derive(Message)]`"
)]
pub trait Message: Send + Sync + 'static {}
#[derive(Debug)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
pub(crate) struct MessageInstance<M: Message> {
pub message_id: MessageId<M>,
pub message: M,
}
/// A [`MessageId`] uniquely identifies a message stored in a specific [`World`].
///
/// A [`MessageId`] can, among other things, be used to trace the flow of a [`Message`] from the point it was
/// sent to the point it was processed. [`MessageId`]s increase monotonically by write order.
///
/// [`World`]: crate::world::World
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Clone, Debug, PartialEq, Hash)
)]
pub struct MessageId<M: Message> {
/// Uniquely identifies the message associated with this ID.
// This value corresponds to the order in which each message was written to the world.
pub id: usize,
/// The source code location that triggered this message.
pub caller: MaybeLocation,
#[cfg_attr(feature = "bevy_reflect", reflect(ignore, clone))]
pub(super) _marker: PhantomData<M>,
}
impl<M: Message> Copy for MessageId<M> {}
impl<M: Message> Clone for MessageId<M> {
fn clone(&self) -> Self {
*self
}
}
impl<M: Message> fmt::Display for MessageId<M> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
<Self as fmt::Debug>::fmt(self, f)
}
}
impl<M: Message> fmt::Debug for MessageId<M> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"message<{}>#{}",
core::any::type_name::<M>().split("::").last().unwrap(),
self.id,
)
}
}
impl<M: Message> PartialEq for MessageId<M> {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl<M: Message> Eq for MessageId<M> {}
impl<M: Message> PartialOrd for MessageId<M> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<M: Message> Ord for MessageId<M> {
fn cmp(&self, other: &Self) -> Ordering {
self.id.cmp(&other.id)
}
}
impl<M: Message> Hash for MessageId<M> {
fn hash<H: Hasher>(&self, state: &mut H) {
Hash::hash(&self.id, state);
}
}
| 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/message/message_mutator.rs | crates/bevy_ecs/src/message/message_mutator.rs | #[cfg(feature = "multi_threaded")]
use crate::message::MessageMutParIter;
use crate::{
message::{Message, MessageCursor, MessageMutIterator, MessageMutIteratorWithId, Messages},
system::{Local, ResMut, SystemParam},
};
/// Mutably reads messages of type `T` keeping track of which messages have already been read
/// by each system allowing multiple systems to read the same messages. Ideal for chains of systems
/// that all want to modify the same messages.
///
/// # Usage
///
/// [`MessageMutator`]s are usually declared as a [`SystemParam`].
/// ```
/// # use bevy_ecs::prelude::*;
///
/// #[derive(Message, Debug)]
/// pub struct MyMessage(pub u32); // Custom message type.
/// fn my_system(mut reader: MessageMutator<MyMessage>) {
/// for message in reader.read() {
/// message.0 += 1;
/// println!("received message: {:?}", message);
/// }
/// }
/// ```
///
/// # Concurrency
///
/// Multiple systems with `MessageMutator<T>` of the same message type can not run concurrently.
/// They also can not be executed in parallel with [`MessageReader`] or [`MessageWriter`].
///
/// # Clearing, Reading, and Peeking
///
/// Messages are stored in a double buffered queue that switches each frame. This switch also clears the previous
/// frame's messages. Messages should be read each frame otherwise they may be lost. For manual control over this
/// behavior, see [`Messages`].
///
/// Most of the time systems will want to use [`MessageMutator::read()`]. This function creates an iterator over
/// all messages that haven't been read yet by this system, marking the message as read in the process.
///
/// [`MessageReader`]: super::MessageReader
/// [`MessageWriter`]: super::MessageWriter
#[derive(SystemParam, Debug)]
pub struct MessageMutator<'w, 's, E: Message> {
pub(super) reader: Local<'s, MessageCursor<E>>,
#[system_param(validation_message = "Message not initialized")]
messages: ResMut<'w, Messages<E>>,
}
impl<'w, 's, E: Message> MessageMutator<'w, 's, E> {
/// Iterates over the messages this [`MessageMutator`] has not seen yet. This updates the
/// [`MessageMutator`]'s message counter, which means subsequent message reads will not include messages
/// that happened before now.
pub fn read(&mut self) -> MessageMutIterator<'_, E> {
self.reader.read_mut(&mut self.messages)
}
/// Like [`read`](Self::read), except also returning the [`MessageId`](super::MessageId) of the messages.
pub fn read_with_id(&mut self) -> MessageMutIteratorWithId<'_, E> {
self.reader.read_mut_with_id(&mut self.messages)
}
/// Returns a parallel iterator over the messages this [`MessageMutator`] has not seen yet.
/// See also [`for_each`](super::MessageParIter::for_each).
///
/// # Example
/// ```
/// # use bevy_ecs::prelude::*;
/// # use std::sync::atomic::{AtomicUsize, Ordering};
///
/// #[derive(Message)]
/// struct MyMessage {
/// value: usize,
/// }
///
/// #[derive(Resource, Default)]
/// struct Counter(AtomicUsize);
///
/// // setup
/// let mut world = World::new();
/// world.init_resource::<Messages<MyMessage>>();
/// world.insert_resource(Counter::default());
///
/// let mut schedule = Schedule::default();
/// schedule.add_systems(|mut messages: MessageMutator<MyMessage>, counter: Res<Counter>| {
/// messages.par_read().for_each(|MyMessage { value }| {
/// counter.0.fetch_add(*value, Ordering::Relaxed);
/// });
/// });
/// for value in 0..100 {
/// world.write_message(MyMessage { value });
/// }
/// schedule.run(&mut world);
/// let Counter(counter) = world.remove_resource::<Counter>().unwrap();
/// // all messages were processed
/// assert_eq!(counter.into_inner(), 4950);
/// ```
#[cfg(feature = "multi_threaded")]
pub fn par_read(&mut self) -> MessageMutParIter<'_, E> {
self.reader.par_read_mut(&mut self.messages)
}
/// Determines the number of messages available to be read from this [`MessageMutator`] without consuming any.
pub fn len(&self) -> usize {
self.reader.len(&self.messages)
}
/// Returns `true` if there are no messages available to read.
///
/// # Example
///
/// The following example shows a useful pattern where some behavior is triggered if new messages are available.
/// [`MessageMutator::clear()`] is used so the same messages don't re-trigger the behavior the next time the system runs.
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// #[derive(Message)]
/// struct Collision;
///
/// fn play_collision_sound(mut messages: MessageMutator<Collision>) {
/// if !messages.is_empty() {
/// messages.clear();
/// // Play a sound
/// }
/// }
/// # bevy_ecs::system::assert_is_system(play_collision_sound);
/// ```
pub fn is_empty(&self) -> bool {
self.reader.is_empty(&self.messages)
}
/// Consumes all available messages.
///
/// This means these messages will not appear in calls to [`MessageMutator::read()`] or
/// [`MessageMutator::read_with_id()`] and [`MessageMutator::is_empty()`] will return `true`.
///
/// For usage, see [`MessageMutator::is_empty()`].
pub fn clear(&mut self) {
self.reader.clear(&self.messages);
}
}
| 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/message/message_cursor.rs | crates/bevy_ecs/src/message/message_cursor.rs | use crate::message::{
Message, MessageIterator, MessageIteratorWithId, MessageMutIterator, MessageMutIteratorWithId,
Messages,
};
#[cfg(feature = "multi_threaded")]
use crate::message::{MessageMutParIter, MessageParIter};
use core::marker::PhantomData;
/// Stores the state for a [`MessageReader`] or [`MessageMutator`].
///
/// Access to the [`Messages<E>`] resource is required to read any incoming messages.
///
/// In almost all cases, you should just use a [`MessageReader`] or [`MessageMutator`],
/// which will automatically manage the state for you.
///
/// However, this type can be useful if you need to manually track messages,
/// such as when you're attempting to send and receive messages of the same type in the same system.
///
/// # Example
///
/// ```
/// use bevy_ecs::prelude::*;
/// use bevy_ecs::message::{Message, MessageCursor};
///
/// #[derive(Message, Clone, Debug)]
/// struct MyMessage;
///
/// /// A system that both sends and receives messages using a [`Local`] [`MessageCursor`].
/// fn send_and_receive_messages(
/// // The `Local` `SystemParam` stores state inside the system itself, rather than in the world.
/// // `MessageCursor<T>` is the internal state of `MessageMutator<T>`, which tracks which messages have been seen.
/// mut local_message_reader: Local<MessageCursor<MyMessage>>,
/// // We can access the `Messages` resource mutably, allowing us to both read and write its contents.
/// mut messages: ResMut<Messages<MyMessage>>,
/// ) {
/// // We must collect the messages to resend, because we can't mutate messages while we're iterating over the messages.
/// let mut messages_to_resend = Vec::new();
///
/// for message in local_message_reader.read(&mut messages) {
/// messages_to_resend.push(message.clone());
/// }
///
/// for message in messages_to_resend {
/// messages.write(MyMessage);
/// }
/// }
///
/// # bevy_ecs::system::assert_is_system(send_and_receive_messages);
/// ```
///
/// [`MessageReader`]: super::MessageReader
/// [`MessageMutator`]: super::MessageMutator
#[derive(Debug)]
pub struct MessageCursor<E: Message> {
pub(super) last_message_count: usize,
pub(super) _marker: PhantomData<E>,
}
impl<E: Message> Default for MessageCursor<E> {
fn default() -> Self {
MessageCursor {
last_message_count: 0,
_marker: Default::default(),
}
}
}
impl<E: Message> Clone for MessageCursor<E> {
fn clone(&self) -> Self {
MessageCursor {
last_message_count: self.last_message_count,
_marker: PhantomData,
}
}
}
impl<E: Message> MessageCursor<E> {
/// See [`MessageReader::read`](super::MessageReader::read)
pub fn read<'a>(&'a mut self, messages: &'a Messages<E>) -> MessageIterator<'a, E> {
self.read_with_id(messages).without_id()
}
/// See [`MessageMutator::read`](super::MessageMutator::read)
pub fn read_mut<'a>(&'a mut self, messages: &'a mut Messages<E>) -> MessageMutIterator<'a, E> {
self.read_mut_with_id(messages).without_id()
}
/// See [`MessageReader::read_with_id`](super::MessageReader::read_with_id)
pub fn read_with_id<'a>(
&'a mut self,
messages: &'a Messages<E>,
) -> MessageIteratorWithId<'a, E> {
MessageIteratorWithId::new(self, messages)
}
/// See [`MessageMutator::read_with_id`](super::MessageMutator::read_with_id)
pub fn read_mut_with_id<'a>(
&'a mut self,
messages: &'a mut Messages<E>,
) -> MessageMutIteratorWithId<'a, E> {
MessageMutIteratorWithId::new(self, messages)
}
/// See [`MessageReader::par_read`](super::MessageReader::par_read)
#[cfg(feature = "multi_threaded")]
pub fn par_read<'a>(&'a mut self, messages: &'a Messages<E>) -> MessageParIter<'a, E> {
MessageParIter::new(self, messages)
}
/// See [`MessageMutator::par_read`](super::MessageMutator::par_read)
#[cfg(feature = "multi_threaded")]
pub fn par_read_mut<'a>(
&'a mut self,
messages: &'a mut Messages<E>,
) -> MessageMutParIter<'a, E> {
MessageMutParIter::new(self, messages)
}
/// See [`MessageReader::len`](super::MessageReader::len)
pub fn len(&self, messages: &Messages<E>) -> usize {
// The number of messages in this reader is the difference between the most recent message
// and the last message seen by it. This will be at most the number of messages contained
// with the messages (any others have already been dropped)
// TODO: Warn when there are dropped messages, or return e.g. a `Result<usize, (usize, usize)>`
messages
.message_count
.saturating_sub(self.last_message_count)
.min(messages.len())
}
/// Amount of messages we missed.
pub fn missed_messages(&self, messages: &Messages<E>) -> usize {
messages
.oldest_message_count()
.saturating_sub(self.last_message_count)
}
/// See [`MessageReader::is_empty()`](super::MessageReader::is_empty)
pub fn is_empty(&self, messages: &Messages<E>) -> bool {
self.len(messages) == 0
}
/// See [`MessageReader::clear()`](super::MessageReader::clear)
pub fn clear(&mut self, messages: &Messages<E>) {
self.last_message_count = messages.message_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/message/message_registry.rs | crates/bevy_ecs/src/message/message_registry.rs | use crate::{
change_detection::{DetectChangesMut, MutUntyped, Tick},
component::ComponentId,
message::{Message, Messages},
resource::Resource,
world::World,
};
use alloc::vec::Vec;
#[doc(hidden)]
struct RegisteredMessage {
messages_component: ComponentId,
// Required to flush the secondary buffer and drop messages even if left unchanged.
previously_updated: bool,
// SAFETY: The message's component ID and the function must be used to fetch the Messages<T> resource
// of the same type initialized in `register_message`, or improper type casts will occur.
update: unsafe fn(MutUntyped),
}
/// A registry of all of the [`Messages`] in the [`World`], used by [`message_update_system`](crate::message::message_update_system)
/// to update all of the messages.
#[derive(Resource, Default)]
pub struct MessageRegistry {
/// Should the messages be updated?
///
/// This field is generally automatically updated by the [`signal_message_update_system`](crate::message::signal_message_update_system).
pub should_update: ShouldUpdateMessages,
message_updates: Vec<RegisteredMessage>,
}
/// Controls whether or not the messages in an [`MessageRegistry`] should be updated.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShouldUpdateMessages {
/// Without any fixed timestep, messages should always be updated each frame.
#[default]
Always,
/// We need to wait until at least one pass of the fixed update schedules to update the messages.
Waiting,
/// At least one pass of the fixed update schedules has occurred, and the messages are ready to be updated.
Ready,
}
impl MessageRegistry {
/// Registers a message type to be updated in a given [`World`]
///
/// If no instance of the [`MessageRegistry`] exists in the world, this will add one - otherwise it will use
/// the existing instance.
pub fn register_message<T: Message>(world: &mut World) {
// By initializing the resource here, we can be sure that it is present,
// and receive the correct, up-to-date `ComponentId` even if it was previously removed.
let component_id = world.init_resource::<Messages<T>>();
let mut registry = world.get_resource_or_init::<Self>();
registry.message_updates.push(RegisteredMessage {
messages_component: component_id,
previously_updated: false,
update: |ptr| {
// SAFETY: The resource was initialized with the type Messages<T>.
unsafe { ptr.with_type::<Messages<T>>() }
.bypass_change_detection()
.update();
},
});
}
/// Updates all of the registered messages in the World.
pub fn run_updates(&mut self, world: &mut World, last_change_tick: Tick) {
for registered_message in &mut self.message_updates {
// Bypass the type ID -> Component ID lookup with the cached component ID.
if let Some(messages) =
world.get_resource_mut_by_id(registered_message.messages_component)
{
let has_changed = messages.has_changed_since(last_change_tick);
if registered_message.previously_updated || has_changed {
// SAFETY: The update function pointer is called with the resource
// fetched from the same component ID.
unsafe { (registered_message.update)(messages) };
// Always set to true if the messages have changed, otherwise disable running on the second invocation
// to wait for more changes.
registered_message.previously_updated =
has_changed || !registered_message.previously_updated;
}
}
}
}
/// Removes a message from the world and its associated [`MessageRegistry`].
pub fn deregister_messages<T: Message>(world: &mut World) {
let component_id = world.init_resource::<Messages<T>>();
let mut registry = world.get_resource_or_init::<Self>();
registry
.message_updates
.retain(|e| e.messages_component != component_id);
world.remove_resource::<Messages<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/src/message/message_reader.rs | crates/bevy_ecs/src/message/message_reader.rs | #[cfg(feature = "multi_threaded")]
use crate::message::MessageParIter;
use crate::{
message::{Message, MessageCursor, MessageIterator, MessageIteratorWithId, Messages},
system::{Local, Res, SystemParam},
};
/// Reads [`Message`]s of type `T` in order and tracks which messages have already been read.
///
/// # Concurrency
///
/// Unlike [`MessageWriter<T>`], systems with `MessageReader<T>` param can be executed concurrently
/// (but not concurrently with `MessageWriter<T>` or `MessageMutator<T>` systems for the same message type).
///
/// [`MessageWriter<T>`]: super::MessageWriter
#[derive(SystemParam, Debug)]
pub struct MessageReader<'w, 's, E: Message> {
pub(super) reader: Local<'s, MessageCursor<E>>,
#[system_param(validation_message = "Message not initialized")]
messages: Res<'w, Messages<E>>,
}
impl<'w, 's, E: Message> MessageReader<'w, 's, E> {
/// Iterates over the messages this [`MessageReader`] has not seen yet. This updates the
/// [`MessageReader`]'s message counter, which means subsequent message reads will not include messages
/// that happened before now.
pub fn read(&mut self) -> MessageIterator<'_, E> {
self.reader.read(&self.messages)
}
/// Like [`read`](Self::read), except also returning the [`MessageId`](super::MessageId) of the messages.
pub fn read_with_id(&mut self) -> MessageIteratorWithId<'_, E> {
self.reader.read_with_id(&self.messages)
}
/// Returns a parallel iterator over the messages this [`MessageReader`] has not seen yet.
/// See also [`for_each`](MessageParIter::for_each).
///
/// # Example
/// ```
/// # use bevy_ecs::prelude::*;
/// # use std::sync::atomic::{AtomicUsize, Ordering};
///
/// #[derive(Message)]
/// struct MyMessage {
/// value: usize,
/// }
///
/// #[derive(Resource, Default)]
/// struct Counter(AtomicUsize);
///
/// // setup
/// let mut world = World::new();
/// world.init_resource::<Messages<MyMessage>>();
/// world.insert_resource(Counter::default());
///
/// let mut schedule = Schedule::default();
/// schedule.add_systems(|mut messages: MessageReader<MyMessage>, counter: Res<Counter>| {
/// messages.par_read().for_each(|MyMessage { value }| {
/// counter.0.fetch_add(*value, Ordering::Relaxed);
/// });
/// });
/// for value in 0..100 {
/// world.write_message(MyMessage { value });
/// }
/// schedule.run(&mut world);
/// let Counter(counter) = world.remove_resource::<Counter>().unwrap();
/// // all messages were processed
/// assert_eq!(counter.into_inner(), 4950);
/// ```
#[cfg(feature = "multi_threaded")]
pub fn par_read(&mut self) -> MessageParIter<'_, E> {
self.reader.par_read(&self.messages)
}
/// Determines the number of messages available to be read from this [`MessageReader`] without consuming any.
pub fn len(&self) -> usize {
self.reader.len(&self.messages)
}
/// Returns `true` if there are no messages available to read.
///
/// # Example
///
/// The following example shows a useful pattern where some behavior is triggered if new messages are available.
/// [`MessageReader::clear()`] is used so the same messages don't re-trigger the behavior the next time the system runs.
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// #[derive(Message)]
/// struct Collision;
///
/// fn play_collision_sound(mut messages: MessageReader<Collision>) {
/// if !messages.is_empty() {
/// messages.clear();
/// // Play a sound
/// }
/// }
/// # bevy_ecs::system::assert_is_system(play_collision_sound);
/// ```
pub fn is_empty(&self) -> bool {
self.reader.is_empty(&self.messages)
}
/// Consumes all available messages.
///
/// This means these messages will not appear in calls to [`MessageReader::read()`] or
/// [`MessageReader::read_with_id()`] and [`MessageReader::is_empty()`] will return `true`.
///
/// For usage, see [`MessageReader::is_empty()`].
pub fn clear(&mut self) {
self.reader.clear(&self.messages);
}
}
| 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/message/message_writer.rs | crates/bevy_ecs/src/message/message_writer.rs | use crate::{
message::{Message, MessageId, Messages, WriteBatchIds},
system::{ResMut, SystemParam},
};
/// Writes [`Message`]s of type `T`.
///
/// # Usage
///
/// `MessageWriter`s are usually declared as a [`SystemParam`].
/// ```
/// # use bevy_ecs::prelude::*;
///
/// #[derive(Message)]
/// pub struct MyMessage; // Custom message type.
/// fn my_system(mut writer: MessageWriter<MyMessage>) {
/// writer.write(MyMessage);
/// }
///
/// # bevy_ecs::system::assert_is_system(my_system);
/// ```
///
/// # Concurrency
///
/// `MessageWriter` param has [`ResMut<Messages<T>>`](Messages) inside. So two systems declaring `MessageWriter<T>` params
/// for the same message type won't be executed concurrently.
///
/// # Untyped messages
///
/// `MessageWriter` can only write messages of one specific type, which must be known at compile-time.
/// This is not a problem most of the time, but you may find a situation where you cannot know
/// ahead of time every kind of message you'll need to write. In this case, you can use the "type-erased message" pattern.
///
/// ```
/// # use bevy_ecs::{prelude::*, message::Messages};
/// # #[derive(Message)]
/// # pub struct MyMessage;
/// fn write_untyped(mut commands: Commands) {
/// // Write a message of a specific type without having to declare that
/// // type as a SystemParam.
/// //
/// // Effectively, we're just moving the type parameter from the /type/ to the /method/,
/// // which allows one to do all kinds of clever things with type erasure, such as sending
/// // custom messages to unknown 3rd party plugins (modding API).
/// //
/// // NOTE: the message won't actually be sent until commands get applied during
/// // apply_deferred.
/// commands.queue(|w: &mut World| {
/// w.write_message(MyMessage);
/// });
/// }
/// ```
/// Note that this is considered *non-idiomatic*, and should only be used when `MessageWriter` will not work.
///
/// [`Observer`]: crate::observer::Observer
#[derive(SystemParam)]
pub struct MessageWriter<'w, E: Message> {
#[system_param(validation_message = "Message not initialized")]
messages: ResMut<'w, Messages<E>>,
}
impl<'w, E: Message> MessageWriter<'w, E> {
/// Writes an `message`, which can later be read by [`MessageReader`](super::MessageReader)s.
/// This method returns the [ID](`MessageId`) of the written `message`.
///
/// See [`Messages`] for details.
#[doc(alias = "send")]
#[track_caller]
pub fn write(&mut self, message: E) -> MessageId<E> {
self.messages.write(message)
}
/// Writes a list of `messages` all at once, which can later be read by [`MessageReader`](super::MessageReader)s.
/// This is more efficient than writing each message individually.
/// This method returns the [IDs](`MessageId`) of the written `messages`.
///
/// See [`Messages`] for details.
#[doc(alias = "send_batch")]
#[track_caller]
pub fn write_batch(&mut self, messages: impl IntoIterator<Item = E>) -> WriteBatchIds<E> {
self.messages.write_batch(messages)
}
/// Writes the default value of the message. Useful when the message is an empty struct.
/// This method returns the [ID](`MessageId`) of the written `message`.
///
/// See [`Messages`] for details.
#[doc(alias = "send_default")]
#[track_caller]
pub fn write_default(&mut self) -> MessageId<E>
where
E: Default,
{
self.messages.write_default()
}
}
| 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/component/register.rs | crates/bevy_ecs/src/component/register.rs | use alloc::{boxed::Box, vec::Vec};
use bevy_platform::sync::PoisonError;
use bevy_utils::TypeIdMap;
use core::any::Any;
use core::{any::TypeId, fmt::Debug, ops::Deref};
use crate::component::{enforce_no_required_components_recursion, RequiredComponentsRegistrator};
use crate::{
component::{
Component, ComponentDescriptor, ComponentId, Components, RequiredComponents, StorageType,
},
query::DebugCheckedUnwrap as _,
resource::Resource,
};
/// Generates [`ComponentId`]s.
#[derive(Debug, Default)]
pub struct ComponentIds {
next: bevy_platform::sync::atomic::AtomicUsize,
}
impl ComponentIds {
/// Peeks the next [`ComponentId`] to be generated without generating it.
pub fn peek(&self) -> ComponentId {
ComponentId(
self.next
.load(bevy_platform::sync::atomic::Ordering::Relaxed),
)
}
/// Generates and returns the next [`ComponentId`].
pub fn next(&self) -> ComponentId {
ComponentId(
self.next
.fetch_add(1, bevy_platform::sync::atomic::Ordering::Relaxed),
)
}
/// Peeks the next [`ComponentId`] to be generated without generating it.
pub fn peek_mut(&mut self) -> ComponentId {
ComponentId(*self.next.get_mut())
}
/// Generates and returns the next [`ComponentId`].
pub fn next_mut(&mut self) -> ComponentId {
let id = self.next.get_mut();
let result = ComponentId(*id);
*id += 1;
result
}
/// Returns the number of [`ComponentId`]s generated.
pub fn len(&self) -> usize {
self.peek().0
}
/// Returns true if and only if no ids have been generated.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
/// A [`Components`] wrapper that enables additional features, like registration.
pub struct ComponentsRegistrator<'w> {
pub(super) components: &'w mut Components,
pub(super) ids: &'w mut ComponentIds,
pub(super) recursion_check_stack: Vec<ComponentId>,
}
impl Deref for ComponentsRegistrator<'_> {
type Target = Components;
fn deref(&self) -> &Self::Target {
self.components
}
}
impl<'w> ComponentsRegistrator<'w> {
/// Constructs a new [`ComponentsRegistrator`].
///
/// # Safety
///
/// The [`Components`] and [`ComponentIds`] must match.
/// For example, they must be from the same world.
pub unsafe fn new(components: &'w mut Components, ids: &'w mut ComponentIds) -> Self {
Self {
components,
ids,
recursion_check_stack: Vec::new(),
}
}
/// Converts this [`ComponentsRegistrator`] into a [`ComponentsQueuedRegistrator`].
/// This is intended for use to pass this value to a function that requires [`ComponentsQueuedRegistrator`].
/// It is generally not a good idea to queue a registration when you can instead register directly on this type.
pub fn as_queued(&self) -> ComponentsQueuedRegistrator<'_> {
// SAFETY: ensured by the caller that created self.
unsafe { ComponentsQueuedRegistrator::new(self.components, self.ids) }
}
/// Applies every queued registration.
/// This ensures that every valid [`ComponentId`] is registered,
/// enabling retrieving [`ComponentInfo`](super::ComponentInfo), etc.
pub fn apply_queued_registrations(&mut self) {
if !self.any_queued_mut() {
return;
}
// Note:
//
// This is not just draining the queue. We need to empty the queue without removing the information from `Components`.
// If we drained directly, we could break invariance.
//
// For example, say `ComponentA` and `ComponentB` are queued, and `ComponentA` requires `ComponentB`.
// If we drain directly, and `ComponentA` was the first to be registered, then, when `ComponentA`
// registers `ComponentB` in `Component::register_required_components`,
// `Components` will not know that `ComponentB` was queued
// (since it will have been drained from the queue.)
// If that happened, `Components` would assign a new `ComponentId` to `ComponentB`
// which would be *different* than the id it was assigned in the queue.
// Then, when the drain iterator gets to `ComponentB`,
// it would be unsafely registering `ComponentB`, which is already registered.
//
// As a result, we need to pop from each queue one by one instead of draining.
// components
while let Some(registrator) = {
let queued = self
.components
.queued
.get_mut()
.unwrap_or_else(PoisonError::into_inner);
queued.components.keys().next().copied().map(|type_id| {
// SAFETY: the id just came from a valid iterator.
unsafe { queued.components.remove(&type_id).debug_checked_unwrap() }
})
} {
registrator.register(self);
}
// resources
while let Some(registrator) = {
let queued = self
.components
.queued
.get_mut()
.unwrap_or_else(PoisonError::into_inner);
queued.resources.keys().next().copied().map(|type_id| {
// SAFETY: the id just came from a valid iterator.
unsafe { queued.resources.remove(&type_id).debug_checked_unwrap() }
})
} {
registrator.register(self);
}
// dynamic
let queued = &mut self
.components
.queued
.get_mut()
.unwrap_or_else(PoisonError::into_inner);
if !queued.dynamic_registrations.is_empty() {
for registrator in core::mem::take(&mut queued.dynamic_registrations) {
registrator.register(self);
}
}
}
/// Registers a [`Component`] of type `T` with this instance.
/// If a component of this type has already been registered, this will return
/// the ID of the pre-existing component.
///
/// # See also
///
/// * [`Components::component_id()`]
/// * [`ComponentsRegistrator::register_component_with_descriptor()`]
#[inline]
pub fn register_component<T: Component>(&mut self) -> ComponentId {
self.register_component_checked::<T>()
}
/// Same as [`Self::register_component_unchecked`] but keeps a checks for safety.
#[inline]
pub(super) fn register_component_checked<T: Component>(&mut self) -> ComponentId {
let type_id = TypeId::of::<T>();
if let Some(&id) = self.indices.get(&type_id) {
enforce_no_required_components_recursion(self, &self.recursion_check_stack, id);
return id;
}
if let Some(registrator) = self
.components
.queued
.get_mut()
.unwrap_or_else(PoisonError::into_inner)
.components
.remove(&type_id)
{
// If we are trying to register something that has already been queued, we respect the queue.
// Just like if we are trying to register something that already is, we respect the first registration.
return registrator.register(self);
}
let id = self.ids.next_mut();
// SAFETY: The component is not currently registered, and the id is fresh.
unsafe {
self.register_component_unchecked::<T>(id);
}
id
}
/// # Safety
///
/// Neither this component, nor its id may be registered or queued. This must be a new registration.
#[inline]
unsafe fn register_component_unchecked<T: Component>(&mut self, id: ComponentId) {
// SAFETY: ensured by caller.
unsafe {
self.components
.register_component_inner(id, ComponentDescriptor::new::<T>());
}
let type_id = TypeId::of::<T>();
let prev = self.components.indices.insert(type_id, id);
debug_assert!(prev.is_none());
self.recursion_check_stack.push(id);
let mut required_components = RequiredComponents::default();
// SAFETY: `required_components` is empty
let mut required_components_registrator =
unsafe { RequiredComponentsRegistrator::new(self, &mut required_components) };
T::register_required_components(id, &mut required_components_registrator);
// SAFETY:
// - `id` was just registered in `self`
// - RequiredComponentsRegistrator guarantees that only components from `self` are included in `required_components`;
// - we just initialized the component with id `id` so no component requiring it can exist yet.
unsafe {
self.components
.register_required_by(id, &required_components);
}
self.recursion_check_stack.pop();
// SAFETY: we just inserted it in `register_component_inner`
let info = unsafe {
&mut self
.components
.components
.get_mut(id.0)
.debug_checked_unwrap()
.as_mut()
.debug_checked_unwrap()
};
info.hooks.update_from_component::<T>();
info.required_components = required_components;
}
/// Registers a component described by `descriptor`.
///
/// # Note
///
/// If this method is called multiple times with identical descriptors, a distinct [`ComponentId`]
/// will be created for each one.
///
/// # See also
///
/// * [`Components::component_id()`]
/// * [`ComponentsRegistrator::register_component()`]
#[inline]
pub fn register_component_with_descriptor(
&mut self,
descriptor: ComponentDescriptor,
) -> ComponentId {
let id = self.ids.next_mut();
// SAFETY: The id is fresh.
unsafe {
self.components.register_component_inner(id, descriptor);
}
id
}
/// Registers a [`Resource`] of type `T` with this instance.
/// If a resource of this type has already been registered, this will return
/// the ID of the pre-existing resource.
///
/// # See also
///
/// * [`Components::resource_id()`]
/// * [`ComponentsRegistrator::register_resource_with_descriptor()`]
#[inline]
pub fn register_resource<T: Resource>(&mut self) -> ComponentId {
// SAFETY: The [`ComponentDescriptor`] matches the [`TypeId`]
unsafe {
self.register_resource_with(TypeId::of::<T>(), || {
ComponentDescriptor::new_resource::<T>()
})
}
}
/// Registers a [non-send resource](crate::system::NonSend) of type `T` with this instance.
/// If a resource of this type has already been registered, this will return
/// the ID of the pre-existing resource.
#[inline]
pub fn register_non_send<T: Any>(&mut self) -> ComponentId {
// SAFETY: The [`ComponentDescriptor`] matches the [`TypeId`]
unsafe {
self.register_resource_with(TypeId::of::<T>(), || {
ComponentDescriptor::new_non_send::<T>(StorageType::default())
})
}
}
/// Same as [`Components::register_resource_unchecked`] but handles safety.
///
/// # Safety
///
/// The [`ComponentDescriptor`] must match the [`TypeId`].
#[inline]
unsafe fn register_resource_with(
&mut self,
type_id: TypeId,
descriptor: impl FnOnce() -> ComponentDescriptor,
) -> ComponentId {
if let Some(id) = self.resource_indices.get(&type_id) {
return *id;
}
if let Some(registrator) = self
.components
.queued
.get_mut()
.unwrap_or_else(PoisonError::into_inner)
.resources
.remove(&type_id)
{
// If we are trying to register something that has already been queued, we respect the queue.
// Just like if we are trying to register something that already is, we respect the first registration.
return registrator.register(self);
}
let id = self.ids.next_mut();
// SAFETY: The resource is not currently registered, the id is fresh, and the [`ComponentDescriptor`] matches the [`TypeId`]
unsafe {
self.components
.register_resource_unchecked(type_id, id, descriptor());
}
id
}
/// Registers a [`Resource`] described by `descriptor`.
///
/// # Note
///
/// If this method is called multiple times with identical descriptors, a distinct [`ComponentId`]
/// will be created for each one.
///
/// # See also
///
/// * [`Components::resource_id()`]
/// * [`ComponentsRegistrator::register_resource()`]
#[inline]
pub fn register_resource_with_descriptor(
&mut self,
descriptor: ComponentDescriptor,
) -> ComponentId {
let id = self.ids.next_mut();
// SAFETY: The id is fresh.
unsafe {
self.components.register_component_inner(id, descriptor);
}
id
}
/// Equivalent of `Components::any_queued_mut`
pub fn any_queued_mut(&mut self) -> bool {
self.components.any_queued_mut()
}
/// Equivalent of `Components::any_queued_mut`
pub fn num_queued_mut(&mut self) -> usize {
self.components.num_queued_mut()
}
}
/// A queued component registration.
pub(super) struct QueuedRegistration {
pub(super) registrator:
Box<dyn FnOnce(&mut ComponentsRegistrator, ComponentId, ComponentDescriptor)>,
pub(super) id: ComponentId,
pub(super) descriptor: ComponentDescriptor,
}
impl QueuedRegistration {
/// Creates the [`QueuedRegistration`].
///
/// # Safety
///
/// [`ComponentId`] must be unique.
unsafe fn new(
id: ComponentId,
descriptor: ComponentDescriptor,
func: impl FnOnce(&mut ComponentsRegistrator, ComponentId, ComponentDescriptor) + 'static,
) -> Self {
Self {
registrator: Box::new(func),
id,
descriptor,
}
}
/// Performs the registration, returning the now valid [`ComponentId`].
pub(super) fn register(self, registrator: &mut ComponentsRegistrator) -> ComponentId {
(self.registrator)(registrator, self.id, self.descriptor);
self.id
}
}
/// Allows queuing components to be registered.
#[derive(Default)]
pub struct QueuedComponents {
pub(super) components: TypeIdMap<QueuedRegistration>,
pub(super) resources: TypeIdMap<QueuedRegistration>,
pub(super) dynamic_registrations: Vec<QueuedRegistration>,
}
impl Debug for QueuedComponents {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let components = self
.components
.iter()
.map(|(type_id, queued)| (type_id, queued.id))
.collect::<Vec<_>>();
let resources = self
.resources
.iter()
.map(|(type_id, queued)| (type_id, queued.id))
.collect::<Vec<_>>();
let dynamic_registrations = self
.dynamic_registrations
.iter()
.map(|queued| queued.id)
.collect::<Vec<_>>();
write!(f, "components: {components:?}, resources: {resources:?}, dynamic_registrations: {dynamic_registrations:?}")
}
}
/// A type that enables queuing registration in [`Components`].
///
/// # Note
///
/// These queued registrations return [`ComponentId`]s.
/// These ids are not yet valid, but they will become valid
/// when either [`ComponentsRegistrator::apply_queued_registrations`] is called or the same registration is made directly.
/// In either case, the returned [`ComponentId`]s will be correct, but they are not correct yet.
///
/// Generally, that means these [`ComponentId`]s can be safely used for read-only purposes.
/// Modifying the contents of the world through these [`ComponentId`]s directly without waiting for them to be fully registered
/// and without then confirming that they have been fully registered is not supported.
/// Hence, extra care is needed with these [`ComponentId`]s to ensure all safety rules are followed.
///
/// As a rule of thumb, if you have mutable access to [`ComponentsRegistrator`], prefer to use that instead.
/// Use this only if you need to know the id of a component but do not need to modify the contents of the world based on that id.
#[derive(Clone, Copy)]
pub struct ComponentsQueuedRegistrator<'w> {
components: &'w Components,
ids: &'w ComponentIds,
}
impl Deref for ComponentsQueuedRegistrator<'_> {
type Target = Components;
fn deref(&self) -> &Self::Target {
self.components
}
}
impl<'w> ComponentsQueuedRegistrator<'w> {
/// Constructs a new [`ComponentsQueuedRegistrator`].
///
/// # Safety
///
/// The [`Components`] and [`ComponentIds`] must match.
/// For example, they must be from the same world.
pub unsafe fn new(components: &'w Components, ids: &'w ComponentIds) -> Self {
Self { components, ids }
}
/// Queues this function to run as a component registrator if the given
/// type is not already queued as a component.
///
/// # Safety
///
/// The [`TypeId`] must not already be registered as a component.
unsafe fn register_arbitrary_component(
&self,
type_id: TypeId,
descriptor: ComponentDescriptor,
func: impl FnOnce(&mut ComponentsRegistrator, ComponentId, ComponentDescriptor) + 'static,
) -> ComponentId {
self.components
.queued
.write()
.unwrap_or_else(PoisonError::into_inner)
.components
.entry(type_id)
.or_insert_with(|| {
// SAFETY: The id was just generated.
unsafe { QueuedRegistration::new(self.ids.next(), descriptor, func) }
})
.id
}
/// Queues this function to run as a resource registrator if the given
/// type is not already queued as a resource.
///
/// # Safety
///
/// The [`TypeId`] must not already be registered as a resource.
unsafe fn register_arbitrary_resource(
&self,
type_id: TypeId,
descriptor: ComponentDescriptor,
func: impl FnOnce(&mut ComponentsRegistrator, ComponentId, ComponentDescriptor) + 'static,
) -> ComponentId {
self.components
.queued
.write()
.unwrap_or_else(PoisonError::into_inner)
.resources
.entry(type_id)
.or_insert_with(|| {
// SAFETY: The id was just generated.
unsafe { QueuedRegistration::new(self.ids.next(), descriptor, func) }
})
.id
}
/// Queues this function to run as a dynamic registrator.
fn register_arbitrary_dynamic(
&self,
descriptor: ComponentDescriptor,
func: impl FnOnce(&mut ComponentsRegistrator, ComponentId, ComponentDescriptor) + 'static,
) -> ComponentId {
let id = self.ids.next();
self.components
.queued
.write()
.unwrap_or_else(PoisonError::into_inner)
.dynamic_registrations
.push(
// SAFETY: The id was just generated.
unsafe { QueuedRegistration::new(id, descriptor, func) },
);
id
}
/// This is a queued version of [`ComponentsRegistrator::register_component`].
/// This will reserve an id and queue the registration.
/// These registrations will be carried out at the next opportunity.
///
/// If this has already been registered or queued, this returns the previous [`ComponentId`].
///
/// # Note
///
/// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
/// See type level docs for details.
#[inline]
pub fn queue_register_component<T: Component>(&self) -> ComponentId {
self.component_id::<T>().unwrap_or_else(|| {
// SAFETY: We just checked that this type was not already registered.
unsafe {
self.register_arbitrary_component(
TypeId::of::<T>(),
ComponentDescriptor::new::<T>(),
|registrator, id, _descriptor| {
// SAFETY: We just checked that this is not currently registered or queued, and if it was registered since, this would have been dropped from the queue.
#[expect(unused_unsafe, reason = "More precise to specify.")]
unsafe {
registrator.register_component_unchecked::<T>(id);
}
},
)
}
})
}
/// This is a queued version of [`ComponentsRegistrator::register_component_with_descriptor`].
/// This will reserve an id and queue the registration.
/// These registrations will be carried out at the next opportunity.
///
/// # Note
///
/// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
/// See type level docs for details.
#[inline]
pub fn queue_register_component_with_descriptor(
&self,
descriptor: ComponentDescriptor,
) -> ComponentId {
self.register_arbitrary_dynamic(descriptor, |registrator, id, descriptor| {
// SAFETY: Id uniqueness handled by caller.
unsafe {
registrator
.components
.register_component_inner(id, descriptor);
}
})
}
/// This is a queued version of [`ComponentsRegistrator::register_resource`].
/// This will reserve an id and queue the registration.
/// These registrations will be carried out at the next opportunity.
///
/// If this has already been registered or queued, this returns the previous [`ComponentId`].
///
/// # Note
///
/// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
/// See type level docs for details.
#[inline]
pub fn queue_register_resource<T: Resource>(&self) -> ComponentId {
let type_id = TypeId::of::<T>();
self.get_resource_id(type_id).unwrap_or_else(|| {
// SAFETY: We just checked that this type was not already registered.
unsafe {
self.register_arbitrary_resource(
type_id,
ComponentDescriptor::new_resource::<T>(),
move |registrator, id, descriptor| {
// SAFETY: We just checked that this is not currently registered or queued, and if it was registered since, this would have been dropped from the queue.
// SAFETY: Id uniqueness handled by caller, and the type_id matches descriptor.
#[expect(unused_unsafe, reason = "More precise to specify.")]
unsafe {
registrator
.components
.register_resource_unchecked(type_id, id, descriptor);
}
},
)
}
})
}
/// This is a queued version of [`ComponentsRegistrator::register_non_send`].
/// This will reserve an id and queue the registration.
/// These registrations will be carried out at the next opportunity.
///
/// If this has already been registered or queued, this returns the previous [`ComponentId`].
///
/// # Note
///
/// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
/// See type level docs for details.
#[inline]
pub fn queue_register_non_send<T: Any>(&self) -> ComponentId {
let type_id = TypeId::of::<T>();
self.get_resource_id(type_id).unwrap_or_else(|| {
// SAFETY: We just checked that this type was not already registered.
unsafe {
self.register_arbitrary_resource(
type_id,
ComponentDescriptor::new_non_send::<T>(StorageType::default()),
move |registrator, id, descriptor| {
// SAFETY: We just checked that this is not currently registered or queued, and if it was registered since, this would have been dropped from the queue.
// SAFETY: Id uniqueness handled by caller, and the type_id matches descriptor.
#[expect(unused_unsafe, reason = "More precise to specify.")]
unsafe {
registrator
.components
.register_resource_unchecked(type_id, id, descriptor);
}
},
)
}
})
}
/// This is a queued version of [`ComponentsRegistrator::register_resource_with_descriptor`].
/// This will reserve an id and queue the registration.
/// These registrations will be carried out at the next opportunity.
///
/// # Note
///
/// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
/// See type level docs for details.
#[inline]
pub fn queue_register_resource_with_descriptor(
&self,
descriptor: ComponentDescriptor,
) -> ComponentId {
self.register_arbitrary_dynamic(descriptor, |registrator, id, descriptor| {
// SAFETY: Id uniqueness handled by caller.
unsafe {
registrator
.components
.register_component_inner(id, descriptor);
}
})
}
}
| 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/component/required.rs | crates/bevy_ecs/src/component/required.rs | use alloc::{format, vec::Vec};
use bevy_platform::{hash::FixedHasher, sync::Arc};
use bevy_ptr::OwningPtr;
use core::fmt::Debug;
use indexmap::{IndexMap, IndexSet};
use thiserror::Error;
use crate::{
bundle::BundleInfo,
change_detection::{MaybeLocation, Tick},
component::{Component, ComponentId, Components, ComponentsRegistrator},
entity::Entity,
query::DebugCheckedUnwrap as _,
storage::{SparseSets, Table, TableRow},
};
/// Metadata associated with a required component. See [`Component`] for details.
#[derive(Clone)]
pub struct RequiredComponent {
/// The constructor used for the required component.
pub constructor: RequiredComponentConstructor,
}
/// A Required Component constructor. See [`Component`] for details.
#[derive(Clone)]
pub struct RequiredComponentConstructor(
// Note: this function makes `unsafe` assumptions, so it cannot be public.
Arc<dyn Fn(&mut Table, &mut SparseSets, Tick, TableRow, Entity, MaybeLocation)>,
);
impl RequiredComponentConstructor {
/// Creates a new instance of `RequiredComponentConstructor` for the given type
///
/// # Safety
///
/// - `component_id` must be a valid component for type `C`.
pub unsafe fn new<C: Component>(component_id: ComponentId, constructor: fn() -> C) -> Self {
RequiredComponentConstructor({
// `portable-atomic-util` `Arc` is not able to coerce an unsized
// type like `std::sync::Arc` can. Creating a `Box` first does the
// coercion.
//
// This would be resolved by https://github.com/rust-lang/rust/issues/123430
#[cfg(not(target_has_atomic = "ptr"))]
use alloc::boxed::Box;
type Constructor = dyn for<'a, 'b> Fn(
&'a mut Table,
&'b mut SparseSets,
Tick,
TableRow,
Entity,
MaybeLocation,
);
#[cfg(not(target_has_atomic = "ptr"))]
type Intermediate<T> = Box<T>;
#[cfg(target_has_atomic = "ptr")]
type Intermediate<T> = Arc<T>;
let boxed: Intermediate<Constructor> = Intermediate::new(
move |table, sparse_sets, change_tick, table_row, entity, caller| {
OwningPtr::make(constructor(), |ptr| {
// SAFETY: This will only be called in the context of `BundleInfo::write_components`, which will
// pass in a valid table_row and entity requiring a C constructor
// C::STORAGE_TYPE is the storage type associated with `component_id` / `C`
// `ptr` points to valid `C` data, which matches the type associated with `component_id`
unsafe {
BundleInfo::initialize_required_component(
table,
sparse_sets,
change_tick,
table_row,
entity,
component_id,
C::STORAGE_TYPE,
ptr,
caller,
);
}
});
},
);
Arc::from(boxed)
})
}
/// # Safety
/// This is intended to only be called in the context of [`BundleInfo::write_components`] to initialized required components.
/// Calling it _anywhere else_ should be considered unsafe.
///
/// `table_row` and `entity` must correspond to a valid entity that currently needs a component initialized via the constructor stored
/// on this [`RequiredComponentConstructor`]. The stored constructor must correspond to a component on `entity` that needs initialization.
/// `table` and `sparse_sets` must correspond to storages on a world where `entity` needs this required component initialized.
///
/// Again, don't call this anywhere but [`BundleInfo::write_components`].
pub(crate) unsafe fn initialize(
&self,
table: &mut Table,
sparse_sets: &mut SparseSets,
change_tick: Tick,
table_row: TableRow,
entity: Entity,
caller: MaybeLocation,
) {
(self.0)(table, sparse_sets, change_tick, table_row, entity, caller);
}
}
/// The collection of metadata for components that are required for a given component.
///
/// For more information, see the "Required Components" section of [`Component`].
#[derive(Default, Clone)]
pub struct RequiredComponents {
/// The components that are directly required (i.e. excluding inherited ones), in the order of their precedence.
///
/// # Safety
/// The [`RequiredComponent`] instance associated to each ID must be valid for its component.
pub(crate) direct: IndexMap<ComponentId, RequiredComponent, FixedHasher>,
/// All the components that are required (i.e. including inherited ones), in depth-first order. Most importantly,
/// components in this list always appear after all the components that they require.
///
/// Note that the direct components are not necessarily at the end of this list, for example if A and C are directly
/// requires, and A requires B requires C, then `all` will hold [C, B, A].
///
/// # Safety
/// The [`RequiredComponent`] instance associated to each ID must be valid for its component.
pub(crate) all: IndexMap<ComponentId, RequiredComponent, FixedHasher>,
}
impl Debug for RequiredComponents {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("RequiredComponents")
.field("direct", &self.direct.keys())
.field("all", &self.all.keys())
.finish()
}
}
impl RequiredComponents {
/// Registers the [`Component`] `C` as an explicitly required component.
///
/// If the component was not already registered as an explicit required component then it is added
/// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
///
/// # Safety
///
/// - all other components in this [`RequiredComponents`] instance must have been registered in `components`.
unsafe fn register<C: Component>(
&mut self,
components: &mut ComponentsRegistrator<'_>,
constructor: fn() -> C,
) {
let id = components.register_component::<C>();
// SAFETY:
// - `id` was just registered in `components`;
// - the caller guarantees all other components were registered in `components`.
unsafe { self.register_by_id::<C>(id, components, constructor) };
}
/// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
///
/// If the component was not already registered as an explicit required component then it is added
/// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
///
/// # Safety
///
/// - `component_id` must be a valid component in `components` for the type `C`;
/// - all other components in this [`RequiredComponents`] instance must have been registered in `components`.
unsafe fn register_by_id<C: Component>(
&mut self,
component_id: ComponentId,
components: &Components,
constructor: fn() -> C,
) {
// SAFETY: the caller guarantees that `component_id` is valid for the type `C`.
let constructor =
|| unsafe { RequiredComponentConstructor::new(component_id, constructor) };
// SAFETY:
// - the caller guarantees that `component_id` is valid in `components`
// - the caller guarantees all other components were registered in `components`;
// - constructor is guaranteed to create a valid constructor for the component with id `component_id`.
unsafe { self.register_dynamic_with(component_id, components, constructor) };
}
/// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
///
/// If the component was not already registered as an explicit required component then it is added
/// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
///
/// # Safety
///
/// - `component_id` must be a valid component in `components`;
/// - all other components in `self` must have been registered in `components`;
/// - `constructor` must return a [`RequiredComponentConstructor`] that constructs a valid instance for the
/// component with ID `component_id`.
unsafe fn register_dynamic_with(
&mut self,
component_id: ComponentId,
components: &Components,
constructor: impl FnOnce() -> RequiredComponentConstructor,
) {
// If already registered as a direct required component then bail.
let entry = match self.direct.entry(component_id) {
indexmap::map::Entry::Vacant(entry) => entry,
indexmap::map::Entry::Occupied(_) =>
panic!("Error while registering required component {component_id:?}: already directly required"),
};
// Insert into `direct`.
let constructor = constructor();
let required_component = RequiredComponent { constructor };
entry.insert(required_component.clone());
// Register inherited required components.
// SAFETY:
// - the caller guarantees all components that were in `self` have been registered in `components`;
// - `component_id` has just been added, but is also guaranteed by the called to be valid in `components`.
unsafe {
Self::register_inherited_required_components_unchecked(
&mut self.all,
component_id,
required_component,
components,
);
}
}
/// Rebuild the `all` list
///
/// # Safety
///
/// - all components in `self` must have been registered in `components`.
unsafe fn rebuild_inherited_required_components(&mut self, components: &Components) {
// Clear `all`, we are re-initializing it.
self.all.clear();
// Register all inherited components as if we just registered all components in `direct` one-by-one.
for (&required_id, required_component) in &self.direct {
// SAFETY:
// - the caller guarantees that all components in this instance have been registered in `components`,
// meaning both `all` and `required_id` have been registered in `components`;
// - `required_component` was associated to `required_id`, so it must hold a constructor valid for it.
unsafe {
Self::register_inherited_required_components_unchecked(
&mut self.all,
required_id,
required_component.clone(),
components,
);
}
}
}
/// Registers all the inherited required components from `required_id`.
///
/// # Safety
///
/// - all components in `all` must have been registered in `components`;
/// - `required_id` must have been registered in `components`;
/// - `required_component` must hold a valid constructor for the component with id `required_id`.
unsafe fn register_inherited_required_components_unchecked(
all: &mut IndexMap<ComponentId, RequiredComponent, FixedHasher>,
required_id: ComponentId,
required_component: RequiredComponent,
components: &Components,
) {
// SAFETY: the caller guarantees that `required_id` is valid in `components`.
let info = unsafe { components.get_info(required_id).debug_checked_unwrap() };
// Now we need to "recursively" register the
// Small optimization: if the current required component was already required recursively
// by an earlier direct required component then all its inherited components have all already
// been inserted, so let's not try to reinsert them.
if !all.contains_key(&required_id) {
for (&inherited_id, inherited_required) in &info.required_components().all {
// This is an inherited required component: insert it only if not already present.
// By the invariants of `RequiredComponents`, `info.required_components().all` holds the required
// components in a depth-first order, and this makes us store the components in `self.all` also
// in depth-first order, as long as we don't overwrite existing ones.
//
// SAFETY:
// `inherited_required` was associated to `inherited_id`, so it must have been valid for its component.
all.entry(inherited_id)
.or_insert_with(|| inherited_required.clone());
}
}
// For direct required components:
// - insert them after inherited components to follow the depth-first order;
// - insert them unconditionally in order to make their constructor the one that's used.
// Note that `insert` does not change the order of components, meaning `component_id` will still appear
// before any other component that requires it.
//
// SAFETY: the caller guarantees that `required_component` is valid for the component with ID `required_id`.
all.insert(required_id, required_component);
}
/// Iterates the ids of all required components. This includes recursive required components.
pub fn iter_ids(&self) -> impl Iterator<Item = ComponentId> + '_ {
self.all.keys().copied()
}
}
impl Components {
/// Registers the components in `required_components` as required by `requiree`.
///
/// # Safety
///
/// - `requiree` must have been registered in `self`
/// - all components in `required_components` must have been registered in `self`;
/// - this is called with `requiree` before being called on any component requiring `requiree`.
pub(crate) unsafe fn register_required_by(
&mut self,
requiree: ComponentId,
required_components: &RequiredComponents,
) {
for &required in required_components.all.keys() {
// SAFETY: the caller guarantees that all components in `required_components` have been registered in `self`.
let required_by = unsafe { self.get_required_by_mut(required).debug_checked_unwrap() };
// This preserves the invariant of `required_by` because:
// - components requiring `required` and required by `requiree` are already initialized at this point
// and hence registered in `required_by` before `requiree`;
// - components requiring `requiree` cannot exist yet, as this is called on `requiree` before them.
required_by.insert(requiree);
}
}
/// Registers the given component `R` and [required components] inherited from it as required by `T`.
///
/// When `T` is added to an entity, `R` will also be added if it was not already provided.
/// The given `constructor` will be used for the creation of `R`.
///
/// [required components]: Component#required-components
///
/// # Safety
///
/// - the given component IDs `required` and `requiree` must be valid in `self`;
/// - the given component ID `required` must be valid for the component type `R`.
///
///
/// # Errors
///
/// Returns a [`RequiredComponentsError`] if either of these are true:
/// - the `required` component is already a *directly* required component for the `requiree`; indirect
/// requirements through other components are allowed. In those cases, the more specific
/// registration will be used.
/// - the `requiree` component is already a (possibly indirect) required component for the `required` component.
pub(crate) unsafe fn register_required_components<R: Component>(
&mut self,
requiree: ComponentId,
required: ComponentId,
constructor: fn() -> R,
) -> Result<(), RequiredComponentsError> {
// First step: validate inputs and return errors.
// SAFETY: The caller ensures that the `required` is valid.
let required_required_components = unsafe {
self.get_required_components(required)
.debug_checked_unwrap()
};
// Cannot create cyclic requirements.
if required_required_components.all.contains_key(&requiree) {
return Err(RequiredComponentsError::CyclicRequirement(
requiree, required,
));
}
// SAFETY: The caller ensures that the `requiree` is valid.
let required_components = unsafe {
self.get_required_components_mut(requiree)
.debug_checked_unwrap()
};
// Cannot directly require the same component twice.
if required_components.direct.contains_key(&required) {
return Err(RequiredComponentsError::DuplicateRegistration(
requiree, required,
));
}
// Second step: register the single requirement requiree->required
// Store the old count of (all) required components. This will help determine which ones are new.
let old_required_count = required_components.all.len();
// SAFETY: the caller guarantees that `requiree` is valid in `self`.
unsafe {
self.required_components_scope(requiree, |this, required_components| {
// SAFETY: the caller guarantees that `required` is valid for type `R` in `self`
required_components.register_by_id(required, this, constructor);
});
}
// Third step: update the required components and required_by of all the indirect requirements/requirees.
// Borrow again otherwise it conflicts with the `self.required_components_scope` call.
// SAFETY: The caller ensures that the `requiree` is valid.
let required_components = unsafe {
self.get_required_components_mut(requiree)
.debug_checked_unwrap()
};
// Optimization: get all the new required components, i.e. those that were appended.
// Other components that might be inherited when requiring `required` can be safely ignored because
// any component requiring `requiree` will already transitively require them.
// Note: the only small exception is for `required` itself, for which we cannot ignore the value of the
// constructor. But for simplicity we will rebuild any `RequiredComponents`
let new_required_components = required_components.all[old_required_count..]
.keys()
.copied()
.collect::<Vec<_>>();
// Get all the new requiree components, i.e. `requiree` and all the components that `requiree` is required by.
// SAFETY: The caller ensures that the `requiree` is valid.
let requiree_required_by = unsafe { self.get_required_by(requiree).debug_checked_unwrap() };
let new_requiree_components = [requiree]
.into_iter()
.chain(requiree_required_by.iter().copied())
.collect::<IndexSet<_, FixedHasher>>();
// We now need to update the required and required_by components of all the components
// directly or indirectly involved.
// Important: we need to be careful about the order we do these operations in.
// Since computing the required components of some component depends on the required components of
// other components, and while we do this operations not all required components are up-to-date, we need
// to ensure we update components in such a way that we update a component after the components it depends on.
// Luckily, `new_requiree_components` comes from `ComponentInfo::required_by`, which guarantees an order
// with that property.
// Update the inherited required components of all requiree components (directly or indirectly).
// Skip the first one (requiree) because we already updates it.
for &indirect_requiree in &new_requiree_components[1..] {
// SAFETY: `indirect_requiree` comes from `self` so it must be valid.
unsafe {
self.required_components_scope(indirect_requiree, |this, required_components| {
// Rebuild the inherited required components.
// SAFETY: `required_components` comes from `self`, so all its components must have be valid in `self`.
required_components.rebuild_inherited_required_components(this);
});
}
}
// Update the `required_by` of all the components that were newly required (directly or indirectly).
for &indirect_required in &new_required_components {
// SAFETY: `indirect_required` comes from `self`, so it must be valid.
let required_by = unsafe {
self.get_required_by_mut(indirect_required)
.debug_checked_unwrap()
};
// Remove and re-add all the components in `new_requiree_components`
// This preserves the invariant of `required_by` because `new_requiree_components`
// satisfies its invariant, due to being `requiree` followed by its `required_by` components,
// and because any component not in `new_requiree_components` cannot require a component in it,
// since if that was the case it would appear in the `required_by` for `requiree`.
required_by.retain(|id| !new_requiree_components.contains(id));
required_by.extend(&new_requiree_components);
}
Ok(())
}
/// Temporarily take out the [`RequiredComponents`] of the component with id `component_id`
/// and runs the given closure with mutable access to `self` and the given [`RequiredComponents`].
///
/// SAFETY:
///
/// `component_id` is valid in `self.components`
unsafe fn required_components_scope<R>(
&mut self,
component_id: ComponentId,
f: impl FnOnce(&mut Self, &mut RequiredComponents) -> R,
) -> R {
struct DropGuard<'a> {
components: &'a mut Components,
component_id: ComponentId,
required_components: RequiredComponents,
}
impl Drop for DropGuard<'_> {
fn drop(&mut self) {
// SAFETY: The caller ensures that the `component_id` is valid.
let required_components = unsafe {
self.components
.get_required_components_mut(self.component_id)
.debug_checked_unwrap()
};
debug_assert!(required_components.direct.is_empty());
debug_assert!(required_components.all.is_empty());
*required_components = core::mem::take(&mut self.required_components);
}
}
let mut guard = DropGuard {
component_id,
// SAFETY: The caller ensures that the `component_id` is valid.
required_components: core::mem::take(unsafe {
self.get_required_components_mut(component_id)
.debug_checked_unwrap()
}),
components: self,
};
f(guard.components, &mut guard.required_components)
}
}
/// An error returned when the registration of a required component fails.
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum RequiredComponentsError {
/// The component is already a directly required component for the requiree.
#[error("Component {0:?} already directly requires component {1:?}")]
DuplicateRegistration(ComponentId, ComponentId),
/// Adding the given requirement would create a cycle.
#[error("Cyclic requirement found: the requiree component {0:?} is required by the required component {1:?}")]
CyclicRequirement(ComponentId, ComponentId),
/// An archetype with the component that requires other components already exists
#[error("An archetype with the component {0:?} that requires other components already exists")]
ArchetypeExists(ComponentId),
}
pub(super) fn enforce_no_required_components_recursion(
components: &Components,
recursion_check_stack: &[ComponentId],
required: ComponentId,
) {
if let Some(direct_recursion) = recursion_check_stack
.iter()
.position(|&id| id == required)
.map(|index| index == recursion_check_stack.len() - 1)
{
panic!(
"Recursive required components detected: {}\nhelp: {}",
recursion_check_stack
.iter()
.map(|id| format!("{}", components.get_name(*id).unwrap().shortname()))
.collect::<Vec<_>>()
.join(" β "),
if direct_recursion {
format!(
"Remove require({}).",
components.get_name(required).unwrap().shortname()
)
} else {
"If this is intentional, consider merging the components.".into()
}
);
}
}
/// This is a safe handle around `ComponentsRegistrator` and `RequiredComponents` to register required components.
pub struct RequiredComponentsRegistrator<'a, 'w> {
components: &'a mut ComponentsRegistrator<'w>,
required_components: &'a mut RequiredComponents,
}
impl<'a, 'w> RequiredComponentsRegistrator<'a, 'w> {
/// # Safety
///
/// All components in `required_components` must have been registered in `components`
pub(super) unsafe fn new(
components: &'a mut ComponentsRegistrator<'w>,
required_components: &'a mut RequiredComponents,
) -> Self {
Self {
components,
required_components,
}
}
/// Registers the [`Component`] `C` as an explicitly required component.
///
/// If the component was not already registered as an explicit required component then it is added
/// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
pub fn register_required<C: Component>(&mut self, constructor: fn() -> C) {
// SAFETY: we internally guarantee that all components in `required_components`
// are registered in `components`
unsafe {
self.required_components
.register(self.components, constructor);
}
}
/// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
///
/// If the component was not already registered as an explicit required component then it is added
/// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
///
/// # Safety
///
/// `component_id` must be a valid [`ComponentId`] for `C` in the [`Components`] instance of `self`.
pub unsafe fn register_required_by_id<C: Component>(
&mut self,
component_id: ComponentId,
constructor: fn() -> C,
) {
// SAFETY:
// - the caller guarantees `component_id` is a valid component in `components` for `C`;
// - we internally guarantee all other components in `required_components` are registered in `components`.
unsafe {
self.required_components.register_by_id::<C>(
component_id,
self.components,
constructor,
);
}
}
/// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
///
/// If the component was not already registered as an explicit required component then it is added
/// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
///
/// # Safety
///
/// - `component_id` must be valid in the [`Components`] instance of `self`;
/// - `constructor` must return a [`RequiredComponentConstructor`] that constructs a valid instance for the
/// component with ID `component_id`.
pub unsafe fn register_required_dynamic_with(
&mut self,
component_id: ComponentId,
constructor: impl FnOnce() -> RequiredComponentConstructor,
) {
// SAFETY:
// - the caller guarantees `component_id` is valid in `components`;
// - the caller guarantees `constructor` returns a valid constructor for `component_id`;
// - we internally guarantee all other components in `required_components` are registered in `components`.
unsafe {
self.required_components.register_dynamic_with(
component_id,
self.components,
constructor,
);
}
}
}
#[cfg(test)]
mod tests {
use alloc::string::{String, ToString};
use crate::{
bundle::Bundle,
component::{Component, RequiredComponentsError},
prelude::Resource,
world::World,
};
#[test]
fn required_components() {
#[derive(Component)]
#[require(Y)]
struct X;
#[derive(Component)]
#[require(Z = new_z())]
struct Y {
value: String,
}
#[derive(Component)]
struct Z(u32);
impl Default for Y {
fn default() -> Self {
Self {
value: "hello".to_string(),
}
}
}
fn new_z() -> Z {
Z(7)
}
let mut world = World::new();
let id = world.spawn(X).id();
assert_eq!(
"hello",
world.entity(id).get::<Y>().unwrap().value,
"Y should have the default value"
);
assert_eq!(
7,
world.entity(id).get::<Z>().unwrap().0,
"Z should have the value provided by the constructor defined in Y"
);
let id = world
.spawn((
X,
Y {
value: "foo".to_string(),
},
))
.id();
assert_eq!(
"foo",
world.entity(id).get::<Y>().unwrap().value,
"Y should have the manually provided value"
);
assert_eq!(
7,
world.entity(id).get::<Z>().unwrap().0,
"Z should have the value provided by the constructor defined in Y"
);
let id = world.spawn((X, Z(8))).id();
assert_eq!(
"hello",
world.entity(id).get::<Y>().unwrap().value,
"Y should have the default value"
);
assert_eq!(
8,
world.entity(id).get::<Z>().unwrap().0,
"Z should have the manually provided value"
);
}
#[test]
fn generic_required_components() {
#[derive(Component)]
#[require(Y<usize>)]
struct X;
#[derive(Component, Default)]
struct Y<T> {
value: T,
}
let mut world = World::new();
let id = world.spawn(X).id();
assert_eq!(
0,
world.entity(id).get::<Y<usize>>().unwrap().value,
"Y should have the default value"
);
}
#[test]
fn required_components_spawn_nonexistent_hooks() {
#[derive(Component)]
#[require(Y)]
struct X;
#[derive(Component, Default)]
struct Y;
#[derive(Resource)]
struct A(usize);
#[derive(Resource)]
struct I(usize);
let mut world = World::new();
world.insert_resource(A(0));
world.insert_resource(I(0));
world
.register_component_hooks::<Y>()
.on_add(|mut world, _| world.resource_mut::<A>().0 += 1)
.on_insert(|mut world, _| world.resource_mut::<I>().0 += 1);
// Spawn entity and ensure Y was added
assert!(world.spawn(X).contains::<Y>());
assert_eq!(world.resource::<A>().0, 1);
assert_eq!(world.resource::<I>().0, 1);
}
#[test]
fn required_components_insert_existing_hooks() {
#[derive(Component)]
#[require(Y)]
struct X;
| 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/component/info.rs | crates/bevy_ecs/src/component/info.rs | use alloc::{borrow::Cow, vec::Vec};
use bevy_platform::{hash::FixedHasher, sync::PoisonError};
use bevy_ptr::OwningPtr;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
use bevy_utils::{prelude::DebugName, TypeIdMap};
use core::{
alloc::Layout,
any::{Any, TypeId},
fmt::Debug,
mem::needs_drop,
};
use indexmap::IndexSet;
use crate::{
archetype::ArchetypeFlags,
component::{
Component, ComponentCloneBehavior, ComponentMutability, QueuedComponents,
RequiredComponents, StorageType,
},
lifecycle::ComponentHooks,
query::DebugCheckedUnwrap as _,
relationship::RelationshipAccessor,
resource::Resource,
storage::SparseSetIndex,
};
/// Stores metadata for a type of component or resource stored in a specific [`World`](crate::world::World).
#[derive(Debug, Clone)]
pub struct ComponentInfo {
pub(super) id: ComponentId,
pub(super) descriptor: ComponentDescriptor,
pub(super) hooks: ComponentHooks,
pub(super) required_components: RequiredComponents,
/// The set of components that require this components.
/// Invariant: components in this set always appear after the components that they require.
pub(super) required_by: IndexSet<ComponentId, FixedHasher>,
}
impl ComponentInfo {
/// Returns a value uniquely identifying the current component.
#[inline]
pub fn id(&self) -> ComponentId {
self.id
}
/// Returns the name of the current component.
#[inline]
pub fn name(&self) -> DebugName {
self.descriptor.name.clone()
}
/// Returns `true` if the current component is mutable.
#[inline]
pub fn mutable(&self) -> bool {
self.descriptor.mutable
}
/// Returns [`ComponentCloneBehavior`] of the current component.
#[inline]
pub fn clone_behavior(&self) -> &ComponentCloneBehavior {
&self.descriptor.clone_behavior
}
/// Returns the [`TypeId`] of the underlying component type.
/// Returns `None` if the component does not correspond to a Rust type.
#[inline]
pub fn type_id(&self) -> Option<TypeId> {
self.descriptor.type_id
}
/// Returns the layout used to store values of this component in memory.
#[inline]
pub fn layout(&self) -> Layout {
self.descriptor.layout
}
#[inline]
/// Get the function which should be called to clean up values of
/// the underlying component type. This maps to the
/// [`Drop`] implementation for 'normal' Rust components
///
/// Returns `None` if values of the underlying component type don't
/// need to be dropped, e.g. as reported by [`needs_drop`].
pub fn drop(&self) -> Option<unsafe fn(OwningPtr<'_>)> {
self.descriptor.drop
}
/// Returns a value indicating the storage strategy for the current component.
#[inline]
pub fn storage_type(&self) -> StorageType {
self.descriptor.storage_type
}
/// Returns `true` if the underlying component type can be freely shared between threads.
/// If this returns `false`, then extra care must be taken to ensure that components
/// are not accessed from the wrong thread.
#[inline]
pub fn is_send_and_sync(&self) -> bool {
self.descriptor.is_send_and_sync
}
/// Create a new [`ComponentInfo`].
pub(crate) fn new(id: ComponentId, descriptor: ComponentDescriptor) -> Self {
ComponentInfo {
id,
descriptor,
hooks: Default::default(),
required_components: Default::default(),
required_by: Default::default(),
}
}
/// Update the given flags to include any [`ComponentHook`](crate::component::ComponentHook) registered to self
#[inline]
pub(crate) fn update_archetype_flags(&self, flags: &mut ArchetypeFlags) {
if self.hooks().on_add.is_some() {
flags.insert(ArchetypeFlags::ON_ADD_HOOK);
}
if self.hooks().on_insert.is_some() {
flags.insert(ArchetypeFlags::ON_INSERT_HOOK);
}
if self.hooks().on_replace.is_some() {
flags.insert(ArchetypeFlags::ON_REPLACE_HOOK);
}
if self.hooks().on_remove.is_some() {
flags.insert(ArchetypeFlags::ON_REMOVE_HOOK);
}
if self.hooks().on_despawn.is_some() {
flags.insert(ArchetypeFlags::ON_DESPAWN_HOOK);
}
}
/// Provides a reference to the collection of hooks associated with this [`Component`]
pub fn hooks(&self) -> &ComponentHooks {
&self.hooks
}
/// Retrieves the [`RequiredComponents`] collection, which contains all required components (and their constructors)
/// needed by this component. This includes _recursive_ required components.
pub fn required_components(&self) -> &RequiredComponents {
&self.required_components
}
/// Returns [`RelationshipAccessor`] for this component if it is a [`Relationship`](crate::relationship::Relationship) or [`RelationshipTarget`](crate::relationship::RelationshipTarget) , `None` otherwise.
pub fn relationship_accessor(&self) -> Option<&RelationshipAccessor> {
self.descriptor.relationship_accessor.as_ref()
}
}
/// A value which uniquely identifies the type of a [`Component`] or [`Resource`] within a
/// [`World`](crate::world::World).
///
/// Each time a new `Component` type is registered within a `World` using
/// e.g. [`World::register_component`](crate::world::World::register_component) or
/// [`World::register_component_with_descriptor`](crate::world::World::register_component_with_descriptor)
/// or a Resource with e.g. [`World::init_resource`](crate::world::World::init_resource),
/// a corresponding `ComponentId` is created to track it.
///
/// While the distinction between `ComponentId` and [`TypeId`] may seem superficial, breaking them
/// into two separate but related concepts allows components to exist outside of Rust's type system.
/// Each Rust type registered as a `Component` will have a corresponding `ComponentId`, but additional
/// `ComponentId`s may exist in a `World` to track components which cannot be
/// represented as Rust types for scripting or other advanced use-cases.
///
/// A `ComponentId` is tightly coupled to its parent `World`. Attempting to use a `ComponentId` from
/// one `World` to access the metadata of a `Component` in a different `World` is undefined behavior
/// and must not be attempted.
///
/// Given a type `T` which implements [`Component`], the `ComponentId` for `T` can be retrieved
/// from a `World` using [`World::component_id()`](crate::world::World::component_id) or via [`Components::component_id()`].
/// Access to the `ComponentId` for a [`Resource`] is available via [`Components::resource_id()`].
#[derive(Debug, Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, Hash, PartialEq, Clone)
)]
pub struct ComponentId(pub(super) usize);
impl ComponentId {
/// Creates a new [`ComponentId`].
///
/// The `index` is a unique value associated with each type of component in a given world.
/// Usually, this value is taken from a counter incremented for each type of component registered with the world.
#[inline]
pub const fn new(index: usize) -> ComponentId {
ComponentId(index)
}
/// Returns the index of the current component.
#[inline]
pub fn index(self) -> usize {
self.0
}
}
impl SparseSetIndex for ComponentId {
#[inline]
fn sparse_set_index(&self) -> usize {
self.index()
}
#[inline]
fn get_sparse_set_index(value: usize) -> Self {
Self(value)
}
}
/// A value describing a component or resource, which may or may not correspond to a Rust type.
#[derive(Clone)]
pub struct ComponentDescriptor {
name: DebugName,
// SAFETY: This must remain private. It must match the statically known StorageType of the
// associated rust component type if one exists.
storage_type: StorageType,
// SAFETY: This must remain private. It must only be set to "true" if this component is
// actually Send + Sync
is_send_and_sync: bool,
type_id: Option<TypeId>,
layout: Layout,
// SAFETY: this function must be safe to call with pointers pointing to items of the type
// this descriptor describes.
// None if the underlying type doesn't need to be dropped
drop: Option<for<'a> unsafe fn(OwningPtr<'a>)>,
mutable: bool,
clone_behavior: ComponentCloneBehavior,
relationship_accessor: Option<RelationshipAccessor>,
}
// We need to ignore the `drop` field in our `Debug` impl
impl Debug for ComponentDescriptor {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("ComponentDescriptor")
.field("name", &self.name)
.field("storage_type", &self.storage_type)
.field("is_send_and_sync", &self.is_send_and_sync)
.field("type_id", &self.type_id)
.field("layout", &self.layout)
.field("mutable", &self.mutable)
.field("clone_behavior", &self.clone_behavior)
.field("relationship_accessor", &self.relationship_accessor)
.finish()
}
}
impl ComponentDescriptor {
/// # Safety
///
/// `x` must point to a valid value of type `T`.
unsafe fn drop_ptr<T>(x: OwningPtr<'_>) {
// SAFETY: Contract is required to be upheld by the caller.
unsafe {
x.drop_as::<T>();
}
}
/// Create a new `ComponentDescriptor` for the type `T`.
pub fn new<T: Component>() -> Self {
Self {
name: DebugName::type_name::<T>(),
storage_type: T::STORAGE_TYPE,
is_send_and_sync: true,
type_id: Some(TypeId::of::<T>()),
layout: Layout::new::<T>(),
drop: needs_drop::<T>().then_some(Self::drop_ptr::<T> as _),
mutable: T::Mutability::MUTABLE,
clone_behavior: T::clone_behavior(),
relationship_accessor: T::relationship_accessor().map(|v| v.accessor),
}
}
/// Create a new `ComponentDescriptor`.
///
/// # Safety
/// - the `drop` fn must be usable on a pointer with a value of the layout `layout`
/// - the component type must be safe to access from any thread (Send + Sync in rust terms)
/// - `relationship_accessor` must be valid for this component type if not `None`
pub unsafe fn new_with_layout(
name: impl Into<Cow<'static, str>>,
storage_type: StorageType,
layout: Layout,
drop: Option<for<'a> unsafe fn(OwningPtr<'a>)>,
mutable: bool,
clone_behavior: ComponentCloneBehavior,
relationship_accessor: Option<RelationshipAccessor>,
) -> Self {
Self {
name: name.into().into(),
storage_type,
is_send_and_sync: true,
type_id: None,
layout,
drop,
mutable,
clone_behavior,
relationship_accessor,
}
}
/// Create a new `ComponentDescriptor` for a resource.
///
/// The [`StorageType`] for resources is always [`StorageType::Table`].
pub fn new_resource<T: Resource>() -> Self {
Self {
name: DebugName::type_name::<T>(),
// PERF: `SparseStorage` may actually be a more
// reasonable choice as `storage_type` for resources.
storage_type: StorageType::Table,
is_send_and_sync: true,
type_id: Some(TypeId::of::<T>()),
layout: Layout::new::<T>(),
drop: needs_drop::<T>().then_some(Self::drop_ptr::<T> as _),
mutable: true,
clone_behavior: ComponentCloneBehavior::Default,
relationship_accessor: None,
}
}
pub(super) fn new_non_send<T: Any>(storage_type: StorageType) -> Self {
Self {
name: DebugName::type_name::<T>(),
storage_type,
is_send_and_sync: false,
type_id: Some(TypeId::of::<T>()),
layout: Layout::new::<T>(),
drop: needs_drop::<T>().then_some(Self::drop_ptr::<T> as _),
mutable: true,
clone_behavior: ComponentCloneBehavior::Default,
relationship_accessor: None,
}
}
/// Returns a value indicating the storage strategy for the current component.
#[inline]
pub fn storage_type(&self) -> StorageType {
self.storage_type
}
/// Returns the [`TypeId`] of the underlying component type.
/// Returns `None` if the component does not correspond to a Rust type.
#[inline]
pub fn type_id(&self) -> Option<TypeId> {
self.type_id
}
/// Returns the name of the current component.
#[inline]
pub fn name(&self) -> DebugName {
self.name.clone()
}
/// Returns whether this component is mutable.
#[inline]
pub fn mutable(&self) -> bool {
self.mutable
}
}
/// Stores metadata associated with each kind of [`Component`] in a given [`World`](crate::world::World).
#[derive(Debug, Default)]
pub struct Components {
pub(super) components: Vec<Option<ComponentInfo>>,
pub(super) indices: TypeIdMap<ComponentId>,
pub(super) resource_indices: TypeIdMap<ComponentId>,
// This is kept internal and local to verify that no deadlocks can occur.
pub(super) queued: bevy_platform::sync::RwLock<QueuedComponents>,
}
impl Components {
/// This registers any descriptor, component or resource.
///
/// # Safety
///
/// The id must have never been registered before. This must be a fresh registration.
#[inline]
pub(super) unsafe fn register_component_inner(
&mut self,
id: ComponentId,
descriptor: ComponentDescriptor,
) {
let info = ComponentInfo::new(id, descriptor);
let least_len = id.0 + 1;
if self.components.len() < least_len {
self.components.resize_with(least_len, || None);
}
// SAFETY: We just extended the vec to make this index valid.
let slot = unsafe { self.components.get_mut(id.0).debug_checked_unwrap() };
// Caller ensures id is unique
debug_assert!(slot.is_none());
*slot = Some(info);
}
/// Returns the number of components registered or queued with this instance.
#[inline]
pub fn len(&self) -> usize {
self.num_queued() + self.num_registered()
}
/// Returns `true` if there are no components registered or queued with this instance. Otherwise, this returns `false`.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the number of components registered with this instance.
#[inline]
pub fn num_queued(&self) -> usize {
let queued = self.queued.read().unwrap_or_else(PoisonError::into_inner);
queued.components.len() + queued.dynamic_registrations.len() + queued.resources.len()
}
/// Returns `true` if there are any components registered with this instance. Otherwise, this returns `false`.
#[inline]
pub fn any_queued(&self) -> bool {
self.num_queued() > 0
}
/// A faster version of [`Self::num_queued`].
#[inline]
pub fn num_queued_mut(&mut self) -> usize {
let queued = self
.queued
.get_mut()
.unwrap_or_else(PoisonError::into_inner);
queued.components.len() + queued.dynamic_registrations.len() + queued.resources.len()
}
/// A faster version of [`Self::any_queued`].
#[inline]
pub fn any_queued_mut(&mut self) -> bool {
self.num_queued_mut() > 0
}
/// Returns the number of components registered with this instance.
#[inline]
pub fn num_registered(&self) -> usize {
self.components.len()
}
/// Returns `true` if there are any components registered with this instance. Otherwise, this returns `false`.
#[inline]
pub fn any_registered(&self) -> bool {
self.num_registered() > 0
}
/// Gets the metadata associated with the given component, if it is registered.
/// This will return `None` if the id is not registered or is queued.
///
/// This will return an incorrect result if `id` did not come from the same world as `self`. It may return `None` or a garbage value.
#[inline]
pub fn get_info(&self, id: ComponentId) -> Option<&ComponentInfo> {
self.components.get(id.0).and_then(|info| info.as_ref())
}
/// Gets the [`ComponentDescriptor`] of the component with this [`ComponentId`] if it is present.
/// This will return `None` only if the id is neither registered nor queued to be registered.
///
/// Currently, the [`Cow`] will be [`Cow::Owned`] if and only if the component is queued. It will be [`Cow::Borrowed`] otherwise.
///
/// This will return an incorrect result if `id` did not come from the same world as `self`. It may return `None` or a garbage value.
#[inline]
pub fn get_descriptor<'a>(&'a self, id: ComponentId) -> Option<Cow<'a, ComponentDescriptor>> {
self.components
.get(id.0)
.and_then(|info| info.as_ref().map(|info| Cow::Borrowed(&info.descriptor)))
.or_else(|| {
let queued = self.queued.read().unwrap_or_else(PoisonError::into_inner);
// first check components, then resources, then dynamic
queued
.components
.values()
.chain(queued.resources.values())
.chain(queued.dynamic_registrations.iter())
.find(|queued| queued.id == id)
.map(|queued| Cow::Owned(queued.descriptor.clone()))
})
}
/// Gets the name of the component with this [`ComponentId`] if it is present.
/// This will return `None` only if the id is neither registered nor queued to be registered.
///
/// This will return an incorrect result if `id` did not come from the same world as `self`. It may return `None` or a garbage value.
#[inline]
pub fn get_name<'a>(&'a self, id: ComponentId) -> Option<DebugName> {
self.components
.get(id.0)
.and_then(|info| info.as_ref().map(|info| info.descriptor.name()))
.or_else(|| {
let queued = self.queued.read().unwrap_or_else(PoisonError::into_inner);
// first check components, then resources, then dynamic
queued
.components
.values()
.chain(queued.resources.values())
.chain(queued.dynamic_registrations.iter())
.find(|queued| queued.id == id)
.map(|queued| queued.descriptor.name.clone())
})
}
/// Gets the metadata associated with the given component.
/// # Safety
///
/// `id` must be a valid and fully registered [`ComponentId`].
#[inline]
pub unsafe fn get_info_unchecked(&self, id: ComponentId) -> &ComponentInfo {
// SAFETY: The caller ensures `id` is valid.
unsafe {
self.components
.get(id.0)
.debug_checked_unwrap()
.as_ref()
.debug_checked_unwrap()
}
}
#[inline]
pub(crate) fn get_hooks_mut(&mut self, id: ComponentId) -> Option<&mut ComponentHooks> {
self.components
.get_mut(id.0)
.and_then(|info| info.as_mut().map(|info| &mut info.hooks))
}
#[inline]
pub(crate) fn get_required_components(&self, id: ComponentId) -> Option<&RequiredComponents> {
self.components
.get(id.0)
.and_then(|info| info.as_ref().map(|info| &info.required_components))
}
#[inline]
pub(crate) fn get_required_components_mut(
&mut self,
id: ComponentId,
) -> Option<&mut RequiredComponents> {
self.components
.get_mut(id.0)
.and_then(|info| info.as_mut().map(|info| &mut info.required_components))
}
#[inline]
pub(crate) fn get_required_by(
&self,
id: ComponentId,
) -> Option<&IndexSet<ComponentId, FixedHasher>> {
self.components
.get(id.0)
.and_then(|info| info.as_ref().map(|info| &info.required_by))
}
#[inline]
pub(crate) fn get_required_by_mut(
&mut self,
id: ComponentId,
) -> Option<&mut IndexSet<ComponentId, FixedHasher>> {
self.components
.get_mut(id.0)
.and_then(|info| info.as_mut().map(|info| &mut info.required_by))
}
/// Returns true if the [`ComponentId`] is fully registered and valid.
/// Ids may be invalid if they are still queued to be registered.
/// Those ids are still correct, but they are not usable in every context yet.
#[inline]
pub fn is_id_valid(&self, id: ComponentId) -> bool {
self.components.get(id.0).is_some_and(Option::is_some)
}
/// Type-erased equivalent of [`Components::valid_component_id()`].
#[inline]
pub fn get_valid_id(&self, type_id: TypeId) -> Option<ComponentId> {
self.indices.get(&type_id).copied()
}
/// Returns the [`ComponentId`] of the given [`Component`] type `T` if it is fully registered.
/// If you want to include queued registration, see [`Components::component_id()`].
///
/// ```
/// use bevy_ecs::prelude::*;
///
/// let mut world = World::new();
///
/// #[derive(Component)]
/// struct ComponentA;
///
/// let component_a_id = world.register_component::<ComponentA>();
///
/// assert_eq!(component_a_id, world.components().valid_component_id::<ComponentA>().unwrap())
/// ```
///
/// # See also
///
/// * [`Components::get_valid_id()`]
/// * [`Components::valid_resource_id()`]
/// * [`World::component_id()`](crate::world::World::component_id)
#[inline]
pub fn valid_component_id<T: Component>(&self) -> Option<ComponentId> {
self.get_valid_id(TypeId::of::<T>())
}
/// Type-erased equivalent of [`Components::valid_resource_id()`].
#[inline]
pub fn get_valid_resource_id(&self, type_id: TypeId) -> Option<ComponentId> {
self.resource_indices.get(&type_id).copied()
}
/// Returns the [`ComponentId`] of the given [`Resource`] type `T` if it is fully registered.
/// If you want to include queued registration, see [`Components::resource_id()`].
///
/// ```
/// use bevy_ecs::prelude::*;
///
/// let mut world = World::new();
///
/// #[derive(Resource, Default)]
/// struct ResourceA;
///
/// let resource_a_id = world.init_resource::<ResourceA>();
///
/// assert_eq!(resource_a_id, world.components().valid_resource_id::<ResourceA>().unwrap())
/// ```
///
/// # See also
///
/// * [`Components::valid_component_id()`]
/// * [`Components::get_resource_id()`]
#[inline]
pub fn valid_resource_id<T: Resource>(&self) -> Option<ComponentId> {
self.get_valid_resource_id(TypeId::of::<T>())
}
/// Type-erased equivalent of [`Components::component_id()`].
#[inline]
pub fn get_id(&self, type_id: TypeId) -> Option<ComponentId> {
self.indices.get(&type_id).copied().or_else(|| {
self.queued
.read()
.unwrap_or_else(PoisonError::into_inner)
.components
.get(&type_id)
.map(|queued| queued.id)
})
}
/// Returns the [`ComponentId`] of the given [`Component`] type `T`.
///
/// The returned `ComponentId` is specific to the `Components` instance
/// it was retrieved from and should not be used with another `Components`
/// instance.
///
/// Returns [`None`] if the `Component` type has not yet been initialized using
/// [`ComponentsRegistrator::register_component()`](super::ComponentsRegistrator::register_component) or
/// [`ComponentsQueuedRegistrator::queue_register_component()`](super::ComponentsQueuedRegistrator::queue_register_component).
///
/// ```
/// use bevy_ecs::prelude::*;
///
/// let mut world = World::new();
///
/// #[derive(Component)]
/// struct ComponentA;
///
/// let component_a_id = world.register_component::<ComponentA>();
///
/// assert_eq!(component_a_id, world.components().component_id::<ComponentA>().unwrap())
/// ```
///
/// # See also
///
/// * [`ComponentIdFor`](super::ComponentIdFor)
/// * [`Components::get_id()`]
/// * [`Components::resource_id()`]
/// * [`World::component_id()`](crate::world::World::component_id)
#[inline]
pub fn component_id<T: Component>(&self) -> Option<ComponentId> {
self.get_id(TypeId::of::<T>())
}
/// Type-erased equivalent of [`Components::resource_id()`].
#[inline]
pub fn get_resource_id(&self, type_id: TypeId) -> Option<ComponentId> {
self.resource_indices.get(&type_id).copied().or_else(|| {
self.queued
.read()
.unwrap_or_else(PoisonError::into_inner)
.resources
.get(&type_id)
.map(|queued| queued.id)
})
}
/// Returns the [`ComponentId`] of the given [`Resource`] type `T`.
///
/// The returned `ComponentId` is specific to the `Components` instance
/// it was retrieved from and should not be used with another `Components`
/// instance.
///
/// Returns [`None`] if the `Resource` type has not yet been initialized using
/// [`ComponentsRegistrator::register_resource()`](super::ComponentsRegistrator::register_resource) or
/// [`ComponentsQueuedRegistrator::queue_register_resource()`](super::ComponentsQueuedRegistrator::queue_register_resource).
///
/// ```
/// use bevy_ecs::prelude::*;
///
/// let mut world = World::new();
///
/// #[derive(Resource, Default)]
/// struct ResourceA;
///
/// let resource_a_id = world.init_resource::<ResourceA>();
///
/// assert_eq!(resource_a_id, world.components().resource_id::<ResourceA>().unwrap())
/// ```
///
/// # See also
///
/// * [`Components::component_id()`]
/// * [`Components::get_resource_id()`]
#[inline]
pub fn resource_id<T: Resource>(&self) -> Option<ComponentId> {
self.get_resource_id(TypeId::of::<T>())
}
/// # Safety
///
/// The [`ComponentDescriptor`] must match the [`TypeId`].
/// The [`ComponentId`] must be unique.
/// The [`TypeId`] and [`ComponentId`] must not be registered or queued.
#[inline]
pub(super) unsafe fn register_resource_unchecked(
&mut self,
type_id: TypeId,
component_id: ComponentId,
descriptor: ComponentDescriptor,
) {
// SAFETY: ensured by caller
unsafe {
self.register_component_inner(component_id, descriptor);
}
let prev = self.resource_indices.insert(type_id, component_id);
debug_assert!(prev.is_none());
}
/// Gets an iterator over all components fully registered with this instance.
pub fn iter_registered(&self) -> impl Iterator<Item = &ComponentInfo> + '_ {
self.components.iter().filter_map(Option::as_ref)
}
}
| 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/component/clone.rs | crates/bevy_ecs/src/component/clone.rs | use core::marker::PhantomData;
use crate::component::Component;
use crate::entity::{ComponentCloneCtx, SourceComponent};
/// Function type that can be used to clone a component of an entity.
pub type ComponentCloneFn = fn(&SourceComponent, &mut ComponentCloneCtx);
/// The clone behavior to use when cloning or moving a [`Component`].
#[derive(Clone, Debug, Default)]
pub enum ComponentCloneBehavior {
/// Uses the default behavior (which is passed to [`ComponentCloneBehavior::resolve`])
#[default]
Default,
/// Do not clone/move this component.
Ignore,
/// Uses a custom [`ComponentCloneFn`].
Custom(ComponentCloneFn),
}
impl ComponentCloneBehavior {
/// Set clone handler based on `Clone` trait.
///
/// If set as a handler for a component that is not the same as the one used to create this handler, it will panic.
pub fn clone<C: Component + Clone>() -> Self {
Self::Custom(component_clone_via_clone::<C>)
}
/// Set clone handler based on `Reflect` trait.
#[cfg(feature = "bevy_reflect")]
pub fn reflect() -> Self {
Self::Custom(component_clone_via_reflect)
}
/// Returns the "global default"
pub fn global_default_fn() -> ComponentCloneFn {
#[cfg(feature = "bevy_reflect")]
return component_clone_via_reflect;
#[cfg(not(feature = "bevy_reflect"))]
return component_clone_ignore;
}
/// Resolves the [`ComponentCloneBehavior`] to a [`ComponentCloneFn`]. If [`ComponentCloneBehavior::Default`] is
/// specified, the given `default` function will be used.
pub fn resolve(&self, default: ComponentCloneFn) -> ComponentCloneFn {
match self {
ComponentCloneBehavior::Default => default,
ComponentCloneBehavior::Ignore => component_clone_ignore,
ComponentCloneBehavior::Custom(custom) => *custom,
}
}
}
/// Component [clone handler function](ComponentCloneFn) implemented using the [`Clone`] trait.
/// Can be [set](Component::clone_behavior) as clone handler for the specific component it is implemented for.
/// It will panic if set as handler for any other component.
///
pub fn component_clone_via_clone<C: Clone + Component>(
source: &SourceComponent,
ctx: &mut ComponentCloneCtx,
) {
if let Some(component) = source.read::<C>() {
ctx.write_target_component(component.clone());
}
}
/// Component [clone handler function](ComponentCloneFn) implemented using reflect.
/// Can be [set](Component::clone_behavior) as clone handler for any registered component,
/// but only reflected components will be cloned.
///
/// To clone a component using this handler, the following must be true:
/// - World has [`AppTypeRegistry`](crate::reflect::AppTypeRegistry)
/// - Component has [`TypeId`](core::any::TypeId)
/// - Component is registered
/// - Component has [`ReflectFromPtr`](bevy_reflect::ReflectFromPtr) registered
/// - Component can be cloned via [`PartialReflect::reflect_clone`] _or_ has one of the following registered: [`ReflectFromReflect`](bevy_reflect::ReflectFromReflect),
/// [`ReflectDefault`](bevy_reflect::std_traits::ReflectDefault), [`ReflectFromWorld`](crate::reflect::ReflectFromWorld)
///
/// If any of the conditions is not satisfied, the component will be skipped.
///
/// See [`EntityClonerBuilder`](crate::entity::EntityClonerBuilder) for details.
///
/// [`PartialReflect::reflect_clone`]: bevy_reflect::PartialReflect::reflect_clone
#[cfg(feature = "bevy_reflect")]
pub fn component_clone_via_reflect(source: &SourceComponent, ctx: &mut ComponentCloneCtx) {
let Some(app_registry) = ctx.type_registry().cloned() else {
return;
};
let registry = app_registry.read();
let Some(source_component_reflect) = source.read_reflect(®istry) else {
return;
};
let component_info = ctx.component_info();
// checked in read_source_component_reflect
let type_id = component_info.type_id().unwrap();
// Try to clone using `reflect_clone`
if let Ok(mut component) = source_component_reflect.reflect_clone() {
if let Some(reflect_component) =
registry.get_type_data::<crate::reflect::ReflectComponent>(type_id)
{
reflect_component.map_entities(&mut *component, ctx.entity_mapper());
}
drop(registry);
ctx.write_target_component_reflect(component);
return;
}
// Try to clone using ReflectFromReflect
if let Some(reflect_from_reflect) =
registry.get_type_data::<bevy_reflect::ReflectFromReflect>(type_id)
&& let Some(mut component) =
reflect_from_reflect.from_reflect(source_component_reflect.as_partial_reflect())
{
if let Some(reflect_component) =
registry.get_type_data::<crate::reflect::ReflectComponent>(type_id)
{
reflect_component.map_entities(&mut *component, ctx.entity_mapper());
}
drop(registry);
ctx.write_target_component_reflect(component);
return;
}
// Else, try to clone using ReflectDefault
if let Some(reflect_default) =
registry.get_type_data::<bevy_reflect::std_traits::ReflectDefault>(type_id)
{
let mut component = reflect_default.default();
component.apply(source_component_reflect.as_partial_reflect());
drop(registry);
ctx.write_target_component_reflect(component);
return;
}
// Otherwise, try to clone using ReflectFromWorld
if let Some(reflect_from_world) =
registry.get_type_data::<crate::reflect::ReflectFromWorld>(type_id)
{
use crate::{entity::EntityMapper, world::World};
let reflect_from_world = reflect_from_world.clone();
let source_component_cloned = source_component_reflect.to_dynamic();
let component_layout = component_info.layout();
let target = ctx.target();
let component_id = ctx.component_id();
drop(registry);
ctx.queue_deferred(move |world: &mut World, mapper: &mut dyn EntityMapper| {
let mut component = reflect_from_world.from_world(world);
assert_eq!(type_id, (*component).type_id());
component.apply(source_component_cloned.as_partial_reflect());
if let Some(reflect_component) = app_registry
.read()
.get_type_data::<crate::reflect::ReflectComponent>(type_id)
{
reflect_component.map_entities(&mut *component, mapper);
}
// SAFETY:
// - component_id is from the same world as target entity
// - component is a valid value represented by component_id
unsafe {
use alloc::boxed::Box;
use bevy_ptr::OwningPtr;
let raw_component_ptr =
core::ptr::NonNull::new_unchecked(Box::into_raw(component).cast::<u8>());
world
.entity_mut(target)
.insert_by_id(component_id, OwningPtr::new(raw_component_ptr));
if component_layout.size() > 0 {
// Ensure we don't attempt to deallocate zero-sized components
alloc::alloc::dealloc(raw_component_ptr.as_ptr(), component_layout);
}
}
});
}
}
/// Noop implementation of component clone handler function.
///
/// See [`EntityClonerBuilder`](crate::entity::EntityClonerBuilder) for details.
pub fn component_clone_ignore(_source: &SourceComponent, _ctx: &mut ComponentCloneCtx) {}
/// Wrapper for components clone specialization using autoderef.
#[doc(hidden)]
pub struct DefaultCloneBehaviorSpecialization<T>(PhantomData<T>);
impl<T> Default for DefaultCloneBehaviorSpecialization<T> {
fn default() -> Self {
Self(PhantomData)
}
}
/// Base trait for components clone specialization using autoderef.
#[doc(hidden)]
pub trait DefaultCloneBehaviorBase {
fn default_clone_behavior(&self) -> ComponentCloneBehavior;
}
impl<C> DefaultCloneBehaviorBase for DefaultCloneBehaviorSpecialization<C> {
fn default_clone_behavior(&self) -> ComponentCloneBehavior {
ComponentCloneBehavior::Default
}
}
/// Specialized trait for components clone specialization using autoderef.
#[doc(hidden)]
pub trait DefaultCloneBehaviorViaClone {
fn default_clone_behavior(&self) -> ComponentCloneBehavior;
}
impl<C: Clone + Component> DefaultCloneBehaviorViaClone for &DefaultCloneBehaviorSpecialization<C> {
fn default_clone_behavior(&self) -> ComponentCloneBehavior {
ComponentCloneBehavior::clone::<C>()
}
}
| 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/component/mod.rs | crates/bevy_ecs/src/component/mod.rs | //! Types for declaring and storing [`Component`]s.
mod clone;
mod info;
mod register;
mod required;
pub use clone::*;
pub use info::*;
pub use register::*;
pub use required::*;
use crate::{
entity::EntityMapper,
lifecycle::ComponentHook,
relationship::ComponentRelationshipAccessor,
system::{Local, SystemParam},
world::{FromWorld, World},
};
pub use bevy_ecs_macros::Component;
use core::{fmt::Debug, marker::PhantomData, ops::Deref};
/// A data type that can be used to store data for an [entity].
///
/// `Component` is a [derivable trait]: this means that a data type can implement it by applying a `#[derive(Component)]` attribute to it.
/// However, components must always satisfy the `Send + Sync + 'static` trait bounds.
///
/// [entity]: crate::entity
/// [derivable trait]: https://doc.rust-lang.org/book/appendix-03-derivable-traits.html
///
/// # Examples
///
/// Components can take many forms: they are usually structs, but can also be of every other kind of data type, like enums or zero sized types.
/// The following examples show how components are laid out in code.
///
/// ```
/// # use bevy_ecs::component::Component;
/// # struct Color;
/// #
/// // A component can contain data...
/// #[derive(Component)]
/// struct LicensePlate(String);
///
/// // ... but it can also be a zero-sized marker.
/// #[derive(Component)]
/// struct Car;
///
/// // Components can also be structs with named fields...
/// #[derive(Component)]
/// struct VehiclePerformance {
/// acceleration: f32,
/// top_speed: f32,
/// handling: f32,
/// }
///
/// // ... or enums.
/// #[derive(Component)]
/// enum WheelCount {
/// Two,
/// Three,
/// Four,
/// }
/// ```
///
/// # Component and data access
///
/// Components can be marked as immutable by adding the `#[component(immutable)]`
/// attribute when using the derive macro.
/// See the documentation for [`ComponentMutability`] for more details around this
/// feature.
///
/// See the [`entity`] module level documentation to learn how to add or remove components from an entity.
///
/// See the documentation for [`Query`] to learn how to access component data from a system.
///
/// [`entity`]: crate::entity#usage
/// [`Query`]: crate::system::Query
/// [`ComponentMutability`]: crate::component::ComponentMutability
///
/// # Choosing a storage type
///
/// Components can be stored in the world using different strategies with their own performance implications.
/// By default, components are added to the [`Table`] storage, which is optimized for query iteration.
///
/// Alternatively, components can be added to the [`SparseSet`] storage, which is optimized for component insertion and removal.
/// This is achieved by adding an additional `#[component(storage = "SparseSet")]` attribute to the derive one:
///
/// ```
/// # use bevy_ecs::component::Component;
/// #
/// #[derive(Component)]
/// #[component(storage = "SparseSet")]
/// struct ComponentA;
/// ```
///
/// [`Table`]: crate::storage::Table
/// [`SparseSet`]: crate::storage::SparseSet
///
/// # Required Components
///
/// Components can specify Required Components. If some [`Component`] `A` requires [`Component`] `B`, then when `A` is inserted,
/// `B` will _also_ be initialized and inserted (if it was not manually specified).
///
/// The [`Default`] constructor will be used to initialize the component, by default:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// #[require(B)]
/// struct A;
///
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
/// struct B(usize);
///
/// # let mut world = World::default();
/// // This will implicitly also insert B with the Default constructor
/// let id = world.spawn(A).id();
/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
///
/// // This will _not_ implicitly insert B, because it was already provided
/// world.spawn((A, B(11)));
/// ```
///
/// Components can have more than one required component:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// #[require(B, C)]
/// struct A;
///
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
/// #[require(C)]
/// struct B(usize);
///
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
/// struct C(u32);
///
/// # let mut world = World::default();
/// // This will implicitly also insert B and C with their Default constructors
/// let id = world.spawn(A).id();
/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
/// ```
///
/// You can define inline component values that take the following forms:
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// #[require(
/// B(1), // tuple structs
/// C { // named-field structs
/// x: 1,
/// ..Default::default()
/// },
/// D::One, // enum variants
/// E::ONE, // associated consts
/// F::new(1) // constructors
/// )]
/// struct A;
///
/// #[derive(Component, PartialEq, Eq, Debug)]
/// struct B(u8);
///
/// #[derive(Component, PartialEq, Eq, Debug, Default)]
/// struct C {
/// x: u8,
/// y: u8,
/// }
///
/// #[derive(Component, PartialEq, Eq, Debug)]
/// enum D {
/// Zero,
/// One,
/// }
///
/// #[derive(Component, PartialEq, Eq, Debug)]
/// struct E(u8);
///
/// impl E {
/// pub const ONE: Self = Self(1);
/// }
///
/// #[derive(Component, PartialEq, Eq, Debug)]
/// struct F(u8);
///
/// impl F {
/// fn new(value: u8) -> Self {
/// Self(value)
/// }
/// }
///
/// # let mut world = World::default();
/// let id = world.spawn(A).id();
/// assert_eq!(&B(1), world.entity(id).get::<B>().unwrap());
/// assert_eq!(&C { x: 1, y: 0 }, world.entity(id).get::<C>().unwrap());
/// assert_eq!(&D::One, world.entity(id).get::<D>().unwrap());
/// assert_eq!(&E(1), world.entity(id).get::<E>().unwrap());
/// assert_eq!(&F(1), world.entity(id).get::<F>().unwrap());
/// ````
///
///
/// You can also define arbitrary expressions by using `=`
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// #[require(C = init_c())]
/// struct A;
///
/// #[derive(Component, PartialEq, Eq, Debug)]
/// #[require(C = C(20))]
/// struct B;
///
/// #[derive(Component, PartialEq, Eq, Debug)]
/// struct C(usize);
///
/// fn init_c() -> C {
/// C(10)
/// }
///
/// # let mut world = World::default();
/// // This will implicitly also insert C with the init_c() constructor
/// let id = world.spawn(A).id();
/// assert_eq!(&C(10), world.entity(id).get::<C>().unwrap());
///
/// // This will implicitly also insert C with the `|| C(20)` constructor closure
/// let id = world.spawn(B).id();
/// assert_eq!(&C(20), world.entity(id).get::<C>().unwrap());
/// ```
///
/// Required components are _recursive_. This means, if a Required Component has required components,
/// those components will _also_ be inserted if they are missing:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// #[require(B)]
/// struct A;
///
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
/// #[require(C)]
/// struct B(usize);
///
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
/// struct C(u32);
///
/// # let mut world = World::default();
/// // This will implicitly also insert B and C with their Default constructors
/// let id = world.spawn(A).id();
/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
/// ```
///
/// Note that cycles in the "component require tree" will result in stack overflows when attempting to
/// insert a component.
///
/// This "multiple inheritance" pattern does mean that it is possible to have duplicate requires for a given type
/// at different levels of the inheritance tree:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// struct X(usize);
///
/// #[derive(Component, Default)]
/// #[require(X(1))]
/// struct Y;
///
/// #[derive(Component)]
/// #[require(
/// Y,
/// X(2),
/// )]
/// struct Z;
///
/// # let mut world = World::default();
/// // In this case, the x2 constructor is used for X
/// let id = world.spawn(Z).id();
/// assert_eq!(2, world.entity(id).get::<X>().unwrap().0);
/// ```
///
/// In general, this shouldn't happen often, but when it does the algorithm for choosing the constructor from the tree is simple and predictable:
/// 1. A constructor from a direct `#[require()]`, if one exists, is selected with priority.
/// 2. Otherwise, perform a Depth First Search on the tree of requirements and select the first one found.
///
/// From a user perspective, just think about this as the following:
/// 1. Specifying a required component constructor for Foo directly on a spawned component Bar will result in that constructor being used (and overriding existing constructors lower in the inheritance tree). This is the classic "inheritance override" behavior people expect.
/// 2. For cases where "multiple inheritance" results in constructor clashes, Components should be listed in "importance order". List a component earlier in the requirement list to initialize its inheritance tree earlier.
///
/// ## Registering required components at runtime
///
/// In most cases, required components should be registered using the `require` attribute as shown above.
/// However, in some cases, it may be useful to register required components at runtime.
///
/// This can be done through [`World::register_required_components`] or [`World::register_required_components_with`]
/// for the [`Default`] and custom constructors respectively:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// struct A;
///
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
/// struct B(usize);
///
/// #[derive(Component, PartialEq, Eq, Debug)]
/// struct C(u32);
///
/// # let mut world = World::default();
/// // Register B as required by A and C as required by B.
/// world.register_required_components::<A, B>();
/// world.register_required_components_with::<B, C>(|| C(2));
///
/// // This will implicitly also insert B with its Default constructor
/// // and C with the custom constructor defined by B.
/// let id = world.spawn(A).id();
/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
/// assert_eq!(&C(2), world.entity(id).get::<C>().unwrap());
/// ```
///
/// Similar rules as before apply to duplicate requires fer a given type at different levels
/// of the inheritance tree. `A` requiring `C` directly would take precedence over indirectly
/// requiring it through `A` requiring `B` and `B` requiring `C`.
///
/// Unlike with the `require` attribute, directly requiring the same component multiple times
/// for the same component will result in a panic. This is done to prevent conflicting constructors
/// and confusing ordering dependencies.
///
/// Note that requirements must currently be registered before the requiring component is inserted
/// into the world for the first time. Registering requirements after this will lead to a panic.
///
/// # Relationships between Entities
///
/// Sometimes it is useful to define relationships between entities. A common example is the
/// parent / child relationship. Since Components are how data is stored for Entities, one might
/// naturally think to create a Component which has a field of type [`Entity`].
///
/// To facilitate this pattern, Bevy provides the [`Relationship`](`crate::relationship::Relationship`)
/// trait. You can derive the [`Relationship`](`crate::relationship::Relationship`) and
/// [`RelationshipTarget`](`crate::relationship::RelationshipTarget`) traits in addition to the
/// Component trait in order to implement data driven relationships between entities, see the trait
/// docs for more details.
///
/// In addition, Bevy provides canonical implementations of the parent / child relationship via the
/// [`ChildOf`](crate::hierarchy::ChildOf) [`Relationship`](crate::relationship::Relationship) and
/// the [`Children`](crate::hierarchy::Children)
/// [`RelationshipTarget`](crate::relationship::RelationshipTarget).
///
/// # Adding component's hooks
///
/// See [`ComponentHooks`] for a detailed explanation of component's hooks.
///
/// Alternatively to the example shown in [`ComponentHooks`]' documentation, hooks can be configured using following attributes:
/// - `#[component(on_add = on_add_function)]`
/// - `#[component(on_insert = on_insert_function)]`
/// - `#[component(on_replace = on_replace_function)]`
/// - `#[component(on_remove = on_remove_function)]`
///
/// ```
/// # use bevy_ecs::component::Component;
/// # use bevy_ecs::lifecycle::HookContext;
/// # use bevy_ecs::world::DeferredWorld;
/// # use bevy_ecs::entity::Entity;
/// # use bevy_ecs::component::ComponentId;
/// # use core::panic::Location;
/// #
/// #[derive(Component)]
/// #[component(on_add = my_on_add_hook)]
/// #[component(on_insert = my_on_insert_hook)]
/// // Another possible way of configuring hooks:
/// // #[component(on_add = my_on_add_hook, on_insert = my_on_insert_hook)]
/// //
/// // We don't have a replace or remove hook, so we can leave them out:
/// // #[component(on_replace = my_on_replace_hook, on_remove = my_on_remove_hook)]
/// struct ComponentA;
///
/// fn my_on_add_hook(world: DeferredWorld, context: HookContext) {
/// // ...
/// }
///
/// // You can also destructure items directly in the signature
/// fn my_on_insert_hook(world: DeferredWorld, HookContext { caller, .. }: HookContext) {
/// // ...
/// }
/// ```
///
/// This also supports function calls that yield closures
///
/// ```
/// # use bevy_ecs::component::Component;
/// # use bevy_ecs::lifecycle::HookContext;
/// # use bevy_ecs::world::DeferredWorld;
/// #
/// #[derive(Component)]
/// #[component(on_add = my_msg_hook("hello"))]
/// #[component(on_despawn = my_msg_hook("yoink"))]
/// struct ComponentA;
///
/// // a hook closure generating function
/// fn my_msg_hook(message: &'static str) -> impl Fn(DeferredWorld, HookContext) {
/// move |_world, _ctx| {
/// println!("{message}");
/// }
/// }
///
/// ```
///
/// A hook's function path can be elided if it is `Self::on_add`, `Self::on_insert` etc.
/// ```
/// # use bevy_ecs::lifecycle::HookContext;
/// # use bevy_ecs::prelude::*;
/// # use bevy_ecs::world::DeferredWorld;
/// #
/// #[derive(Component, Debug)]
/// #[component(on_add)]
/// struct DoubleOnSpawn(usize);
///
/// impl DoubleOnSpawn {
/// fn on_add(mut world: DeferredWorld, context: HookContext) {
/// let mut entity = world.get_mut::<Self>(context.entity).unwrap();
/// entity.0 *= 2;
/// }
/// }
/// #
/// # let mut world = World::new();
/// # let entity = world.spawn(DoubleOnSpawn(2));
/// # assert_eq!(entity.get::<DoubleOnSpawn>().unwrap().0, 4);
/// ```
///
/// # Setting the clone behavior
///
/// You can specify how the [`Component`] is cloned when deriving it.
///
/// Your options are the functions and variants of [`ComponentCloneBehavior`]
/// See [Handlers section of `EntityClonerBuilder`](crate::entity::EntityClonerBuilder#handlers) to understand how this affects handler priority.
/// ```
/// # use bevy_ecs::prelude::*;
///
/// #[derive(Component)]
/// #[component(clone_behavior = Ignore)]
/// struct MyComponent;
///
/// ```
///
/// # Implementing the trait for foreign types
///
/// As a consequence of the [orphan rule], it is not possible to separate into two different crates the implementation of `Component` from the definition of a type.
/// This means that it is not possible to directly have a type defined in a third party library as a component.
/// This important limitation can be easily worked around using the [newtype pattern]:
/// this makes it possible to locally define and implement `Component` for a tuple struct that wraps the foreign type.
/// The following example gives a demonstration of this pattern.
///
/// ```
/// // `Component` is defined in the `bevy_ecs` crate.
/// use bevy_ecs::component::Component;
///
/// // `Duration` is defined in the `std` crate.
/// use std::time::Duration;
///
/// // It is not possible to implement `Component` for `Duration` from this position, as they are
/// // both foreign items, defined in an external crate. However, nothing prevents to define a new
/// // `Cooldown` type that wraps `Duration`. As `Cooldown` is defined in a local crate, it is
/// // possible to implement `Component` for it.
/// #[derive(Component)]
/// struct Cooldown(Duration);
/// ```
///
/// [orphan rule]: https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type
/// [newtype pattern]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#using-the-newtype-pattern-to-implement-external-traits-on-external-types
///
/// # `!Sync` Components
/// A `!Sync` type cannot implement `Component`. 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::component::Component;
/// #[derive(Component)]
/// struct NotSync {
/// counter: RefCell<usize>,
/// }
/// ```
///
/// This will compile since the `RefCell` is wrapped with `SyncCell`.
/// ```
/// # use std::cell::RefCell;
/// # use bevy_ecs::component::Component;
/// use bevy_platform::cell::SyncCell;
///
/// // This will compile.
/// #[derive(Component)]
/// struct ActuallySync {
/// counter: SyncCell<RefCell<usize>>,
/// }
/// ```
///
/// [`SyncCell`]: bevy_platform::cell::SyncCell
/// [`Exclusive`]: https://doc.rust-lang.org/nightly/std/sync/struct.Exclusive.html
/// [`ComponentHooks`]: crate::lifecycle::ComponentHooks
#[diagnostic::on_unimplemented(
message = "`{Self}` is not a `Component`",
label = "invalid `Component`",
note = "consider annotating `{Self}` with `#[derive(Component)]`"
)]
pub trait Component: Send + Sync + 'static {
/// A constant indicating the storage type used for this component.
const STORAGE_TYPE: StorageType;
/// A marker type to assist Bevy with determining if this component is
/// mutable, or immutable. Mutable components will have [`Component<Mutability = Mutable>`],
/// while immutable components will instead have [`Component<Mutability = Immutable>`].
///
/// * For a component to be mutable, this type must be [`Mutable`].
/// * For a component to be immutable, this type must be [`Immutable`].
type Mutability: ComponentMutability;
/// Gets the `on_add` [`ComponentHook`] for this [`Component`] if one is defined.
fn on_add() -> Option<ComponentHook> {
None
}
/// Gets the `on_insert` [`ComponentHook`] for this [`Component`] if one is defined.
fn on_insert() -> Option<ComponentHook> {
None
}
/// Gets the `on_replace` [`ComponentHook`] for this [`Component`] if one is defined.
fn on_replace() -> Option<ComponentHook> {
None
}
/// Gets the `on_remove` [`ComponentHook`] for this [`Component`] if one is defined.
fn on_remove() -> Option<ComponentHook> {
None
}
/// Gets the `on_despawn` [`ComponentHook`] for this [`Component`] if one is defined.
fn on_despawn() -> Option<ComponentHook> {
None
}
/// Registers required components.
///
/// # Safety
///
/// - `_required_components` must only contain components valid in `_components`.
fn register_required_components(
_component_id: ComponentId,
_required_components: &mut RequiredComponentsRegistrator,
) {
}
/// Called when registering this component, allowing to override clone function (or disable cloning altogether) for this component.
///
/// See [Handlers section of `EntityClonerBuilder`](crate::entity::EntityClonerBuilder#handlers) to understand how this affects handler priority.
#[inline]
fn clone_behavior() -> ComponentCloneBehavior {
ComponentCloneBehavior::Default
}
/// Maps the entities on this component using the given [`EntityMapper`]. This is used to remap entities in contexts like scenes and entity cloning.
/// When deriving [`Component`], this is populated by annotating fields containing entities with `#[entities]`
///
/// ```
/// # use bevy_ecs::{component::Component, entity::Entity};
/// #[derive(Component)]
/// struct Inventory {
/// #[entities]
/// items: Vec<Entity>
/// }
/// ```
///
/// Fields with `#[entities]` must implement [`MapEntities`](crate::entity::MapEntities).
///
/// Bevy provides various implementations of [`MapEntities`](crate::entity::MapEntities), so that arbitrary combinations like these are supported with `#[entities]`:
///
/// ```rust
/// # use bevy_ecs::{component::Component, entity::Entity};
/// #[derive(Component)]
/// struct Inventory {
/// #[entities]
/// items: Vec<Option<Entity>>
/// }
/// ```
///
/// You might need more specialized logic. A likely cause of this is your component contains collections of entities that
/// don't implement [`MapEntities`](crate::entity::MapEntities). In that case, you can annotate your component with
/// `#[component(map_entities)]`. Using this attribute, you must implement `MapEntities` for the
/// component itself, and this method will simply call that implementation.
///
/// ```
/// # use bevy_ecs::{component::Component, entity::{Entity, MapEntities, EntityMapper}};
/// # use std::collections::HashMap;
/// #[derive(Component)]
/// #[component(map_entities)]
/// struct Inventory {
/// items: HashMap<Entity, usize>
/// }
///
/// impl MapEntities for Inventory {
/// fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) {
/// self.items = self.items
/// .drain()
/// .map(|(id, count)|(entity_mapper.get_mapped(id), count))
/// .collect();
/// }
/// }
/// # let a = Entity::from_bits(0x1_0000_0001);
/// # let b = Entity::from_bits(0x1_0000_0002);
/// # let mut inv = Inventory { items: Default::default() };
/// # inv.items.insert(a, 10);
/// # <Inventory as Component>::map_entities(&mut inv, &mut (a,b));
/// # assert_eq!(inv.items.get(&b), Some(&10));
/// ````
///
/// Alternatively, you can specify the path to a function with `#[component(map_entities = function_path)]`, similar to component hooks.
/// In this case, the inputs of the function should mirror the inputs to this method, with the second parameter being generic.
///
/// ```
/// # use bevy_ecs::{component::Component, entity::{Entity, MapEntities, EntityMapper}};
/// # use std::collections::HashMap;
/// #[derive(Component)]
/// #[component(map_entities = map_the_map)]
/// // Also works: map_the_map::<M> or map_the_map::<_>
/// struct Inventory {
/// items: HashMap<Entity, usize>
/// }
///
/// fn map_the_map<M: EntityMapper>(inv: &mut Inventory, entity_mapper: &mut M) {
/// inv.items = inv.items
/// .drain()
/// .map(|(id, count)|(entity_mapper.get_mapped(id), count))
/// .collect();
/// }
/// # let a = Entity::from_bits(0x1_0000_0001);
/// # let b = Entity::from_bits(0x1_0000_0002);
/// # let mut inv = Inventory { items: Default::default() };
/// # inv.items.insert(a, 10);
/// # <Inventory as Component>::map_entities(&mut inv, &mut (a,b));
/// # assert_eq!(inv.items.get(&b), Some(&10));
/// ````
///
/// You can use the turbofish (`::<A,B,C>`) to specify parameters when a function is generic, using either M or _ for the type of the mapper parameter.
#[inline]
fn map_entities<E: EntityMapper>(_this: &mut Self, _mapper: &mut E) {}
/// Returns [`ComponentRelationshipAccessor`] required for working with relationships in dynamic contexts.
///
/// If component is not a [`Relationship`](crate::relationship::Relationship) or [`RelationshipTarget`](crate::relationship::RelationshipTarget), this should return `None`.
fn relationship_accessor() -> Option<ComponentRelationshipAccessor<Self>> {
None
}
}
mod private {
pub trait Seal {}
}
/// The mutability option for a [`Component`]. This can either be:
/// * [`Mutable`]
/// * [`Immutable`]
///
/// This is controlled through either [`Component::Mutability`] or `#[component(immutable)]`
/// when using the derive macro.
///
/// Immutable components are guaranteed to never have an exclusive reference,
/// `&mut ...`, created while inserted onto an entity.
/// In all other ways, they are identical to mutable components.
/// This restriction allows hooks to observe all changes made to an immutable
/// component, effectively turning the `Insert` and `Replace` hooks into a
/// `OnMutate` hook.
/// This is not practical for mutable components, as the runtime cost of invoking
/// a hook for every exclusive reference created would be far too high.
///
/// # Examples
///
/// ```rust
/// # use bevy_ecs::component::Component;
/// #
/// #[derive(Component)]
/// #[component(immutable)]
/// struct ImmutableFoo;
/// ```
pub trait ComponentMutability: private::Seal + 'static {
/// Boolean to indicate if this mutability setting implies a mutable or immutable
/// component.
const MUTABLE: bool;
}
/// Parameter indicating a [`Component`] is immutable.
///
/// See [`ComponentMutability`] for details.
pub struct Immutable;
impl private::Seal for Immutable {}
impl ComponentMutability for Immutable {
const MUTABLE: bool = false;
}
/// Parameter indicating a [`Component`] is mutable.
///
/// See [`ComponentMutability`] for details.
pub struct Mutable;
impl private::Seal for Mutable {}
impl ComponentMutability for Mutable {
const MUTABLE: bool = true;
}
/// The storage used for a specific component type.
///
/// # Examples
/// The [`StorageType`] for a component is configured via the derive attribute
///
/// ```
/// # use bevy_ecs::{prelude::*, component::*};
/// #[derive(Component)]
/// #[component(storage = "SparseSet")]
/// struct A;
/// ```
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq)]
pub enum StorageType {
/// Provides fast and cache-friendly iteration, but slower addition and removal of components.
/// This is the default storage type.
#[default]
Table,
/// Provides fast addition and removal of components, but slower iteration.
SparseSet,
}
/// A [`SystemParam`] that provides access to the [`ComponentId`] for a specific component type.
///
/// # Example
/// ```
/// # use bevy_ecs::{system::Local, component::{Component, ComponentId, ComponentIdFor}};
/// #[derive(Component)]
/// struct Player;
/// fn my_system(component_id: ComponentIdFor<Player>) {
/// let component_id: ComponentId = component_id.get();
/// // ...
/// }
/// ```
#[derive(SystemParam)]
pub struct ComponentIdFor<'s, T: Component>(Local<'s, InitComponentId<T>>);
impl<T: Component> ComponentIdFor<'_, T> {
/// Gets the [`ComponentId`] for the type `T`.
#[inline]
pub fn get(&self) -> ComponentId {
**self
}
}
impl<T: Component> Deref for ComponentIdFor<'_, T> {
type Target = ComponentId;
fn deref(&self) -> &Self::Target {
&self.0.component_id
}
}
impl<T: Component> From<ComponentIdFor<'_, T>> for ComponentId {
#[inline]
fn from(to_component_id: ComponentIdFor<T>) -> ComponentId {
*to_component_id
}
}
/// Initializes the [`ComponentId`] for a specific type when used with [`FromWorld`].
struct InitComponentId<T: Component> {
component_id: ComponentId,
marker: PhantomData<T>,
}
impl<T: Component> FromWorld for InitComponentId<T> {
fn from_world(world: &mut World) -> Self {
Self {
component_id: world.register_component::<T>(),
marker: PhantomData,
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ecs/examples/change_detection.rs | crates/bevy_ecs/examples/change_detection.rs | //! In this example we will simulate a population of entities. In every tick we will:
//! 1. spawn a new entity with a certain possibility
//! 2. age all entities
//! 3. despawn entities with age > 2
//!
//! To demonstrate change detection, there are some console outputs based on changes in
//! the `EntityCounter` resource and updated Age components
#![expect(
clippy::std_instead_of_core,
clippy::print_stdout,
reason = "Examples should not follow this lint"
)]
use bevy_ecs::prelude::*;
use rand::Rng;
use std::ops::Deref;
fn main() {
// Create a new empty World to hold our Entities, Components and Resources
let mut world = World::new();
// Add the counter resource to remember how many entities where spawned
world.insert_resource(EntityCounter { value: 0 });
// Create a new Schedule, which stores systems and controls their relative ordering
let mut schedule = Schedule::default();
// Add systems to the Schedule to execute our app logic
// We can label our systems to force a specific run-order between some of them
schedule.add_systems((
spawn_entities.in_set(SimulationSystems::Spawn),
print_counter_when_changed.after(SimulationSystems::Spawn),
age_all_entities.in_set(SimulationSystems::Age),
remove_old_entities.after(SimulationSystems::Age),
print_changed_entities.after(SimulationSystems::Age),
));
// Simulate 10 frames in our world
for iteration in 1..=10 {
println!("Simulating frame {iteration}/10");
schedule.run(&mut world);
}
}
// This struct will be used as a Resource keeping track of the total amount of spawned entities
#[derive(Debug, Resource)]
struct EntityCounter {
pub value: i32,
}
// This struct represents a Component and holds the age in frames of the entity it gets assigned to
#[derive(Component, Default, Debug)]
struct Age {
frames: i32,
}
// System sets can be used to group systems and configured to control relative ordering
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
enum SimulationSystems {
Spawn,
Age,
}
// This system randomly spawns a new entity in 60% of all frames
// The entity will start with an age of 0 frames
// If an entity gets spawned, we increase the counter in the EntityCounter resource
fn spawn_entities(mut commands: Commands, mut entity_counter: ResMut<EntityCounter>) {
if rand::rng().random_bool(0.6) {
let entity_id = commands.spawn(Age::default()).id();
println!(" spawning {entity_id:?}");
entity_counter.value += 1;
}
}
// This system prints out changes in our entity collection
// For every entity that just got the Age component added we will print that it's the
// entities first birthday. These entities where spawned in the previous frame.
// For every entity with a changed Age component we will print the new value.
// In this example the Age component is changed in every frame, so we don't actually
// need the `Changed` here, but it is still used for the purpose of demonstration.
fn print_changed_entities(
entity_with_added_component: Query<Entity, Added<Age>>,
entity_with_mutated_component: Query<(Entity, &Age), Changed<Age>>,
) {
for entity in &entity_with_added_component {
println!(" {entity} has its first birthday!");
}
for (entity, value) in &entity_with_mutated_component {
println!(" {entity} is now {value:?} frames old");
}
}
// This system iterates over all entities and increases their age in every frame
fn age_all_entities(mut entities: Query<&mut Age>) {
for mut age in &mut entities {
age.frames += 1;
}
}
// This system iterates over all entities in every frame and despawns entities older than 2 frames
fn remove_old_entities(mut commands: Commands, entities: Query<(Entity, &Age)>) {
for (entity, age) in &entities {
if age.frames > 2 {
println!(" despawning {entity} due to age > 2");
commands.entity(entity).despawn();
}
}
}
// This system will print the new counter value every time it was changed since
// the last execution of the system.
fn print_counter_when_changed(entity_counter: Res<EntityCounter>) {
if entity_counter.is_changed() {
println!(
" total number of entities spawned: {}",
entity_counter.deref().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/examples/resources.rs | crates/bevy_ecs/examples/resources.rs | //! In this example we add a counter resource and increase its value in one system,
//! while a different system prints the current count to the console.
#![expect(
clippy::std_instead_of_core,
clippy::print_stdout,
reason = "Examples should not follow this lint"
)]
use bevy_ecs::prelude::*;
use rand::Rng;
use std::ops::Deref;
fn main() {
// Create a world
let mut world = World::new();
// Add the counter resource
world.insert_resource(Counter { value: 0 });
// Create a schedule
let mut schedule = Schedule::default();
// Add systems to increase the counter and to print out the current value
schedule.add_systems((increase_counter, print_counter).chain());
for iteration in 1..=10 {
println!("Simulating frame {iteration}/10");
schedule.run(&mut world);
}
}
// Counter resource to be increased and read by systems
#[derive(Debug, Resource)]
struct Counter {
pub value: i32,
}
fn increase_counter(mut counter: ResMut<Counter>) {
if rand::rng().random_bool(0.5) {
counter.value += 1;
println!(" Increased counter value");
}
}
fn print_counter(counter: Res<Counter>) {
println!(" {:?}", counter.deref());
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.