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_time/src/time.rs
crates/bevy_time/src/time.rs
use bevy_ecs::resource::Resource; use core::time::Duration; #[cfg(feature = "bevy_reflect")] use { bevy_ecs::reflect::ReflectResource, bevy_reflect::{std_traits::ReflectDefault, Reflect}, }; /// A generic clock resource that tracks how much it has advanced since its /// previous update and since its creation. /// /// Multiple instances of this resource are inserted automatically by /// [`TimePlugin`](crate::TimePlugin): /// /// - [`Time<Real>`](crate::real::Real) tracks real wall-clock time elapsed. /// - [`Time<Virtual>`](crate::virt::Virtual) tracks virtual game time that may /// be paused or scaled. /// - [`Time<Fixed>`](crate::fixed::Fixed) tracks fixed timesteps based on /// virtual time. /// - [`Time`] is a generic clock that corresponds to "current" or "default" /// time for systems. It contains [`Time<Virtual>`](crate::virt::Virtual) /// except inside the [`FixedMain`](bevy_app::FixedMain) schedule when it /// contains [`Time<Fixed>`](crate::fixed::Fixed). /// /// The time elapsed since the previous time this clock was advanced is saved as /// [`delta()`](Time::delta) and the total amount of time the clock has advanced /// is saved as [`elapsed()`](Time::elapsed). Both are represented as exact /// [`Duration`] values with fixed nanosecond precision. The clock does not /// support time moving backwards, but it can be updated with [`Duration::ZERO`] /// which will set [`delta()`](Time::delta) to zero. /// /// These values are also available in seconds as `f32` via /// [`delta_secs()`](Time::delta_secs) and /// [`elapsed_secs()`](Time::elapsed_secs), and also in seconds as `f64` /// via [`delta_secs_f64()`](Time::delta_secs_f64) and /// [`elapsed_secs_f64()`](Time::elapsed_secs_f64). /// /// Since [`elapsed_secs()`](Time::elapsed_secs) will grow constantly and /// is `f32`, it will exhibit gradual precision loss. For applications that /// require an `f32` value but suffer from gradual precision loss there is /// [`elapsed_secs_wrapped()`](Time::elapsed_secs_wrapped) available. The /// same wrapped value is also available as [`Duration`] and `f64` for /// consistency. The wrap period is by default 1 hour, and can be set by /// [`set_wrap_period()`](Time::set_wrap_period). /// /// # Accessing clocks /// /// By default, any systems requiring current [`delta()`](Time::delta) or /// [`elapsed()`](Time::elapsed) should use `Res<Time>` to access the default /// time configured for the program. By default, this refers to /// [`Time<Virtual>`](crate::virt::Virtual) except during the /// [`FixedMain`](bevy_app::FixedMain) schedule when it refers to /// [`Time<Fixed>`](crate::fixed::Fixed). This ensures your system can be used /// either in [`Update`](bevy_app::Update) or /// [`FixedUpdate`](bevy_app::FixedUpdate) schedule depending on what is needed. /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_time::prelude::*; /// # /// fn ambivalent_system(time: Res<Time>) { /// println!("this how I see time: delta {:?}, elapsed {:?}", time.delta(), time.elapsed()); /// } /// ``` /// /// If your system needs to react based on real time (wall clock time), like for /// user interfaces, it should use `Res<Time<Real>>`. The /// [`delta()`](Time::delta) and [`elapsed()`](Time::elapsed) values will always /// correspond to real time and will not be affected by pause, time scaling or /// other tweaks. /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_time::prelude::*; /// # /// fn real_time_system(time: Res<Time<Real>>) { /// println!("this will always be real time: delta {:?}, elapsed {:?}", time.delta(), time.elapsed()); /// } /// ``` /// /// If your system specifically needs to access fixed timestep clock, even when /// placed in `Update` schedule, you should use `Res<Time<Fixed>>`. The /// [`delta()`](Time::delta) and [`elapsed()`](Time::elapsed) values will /// correspond to the latest fixed timestep that has been run. /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_time::prelude::*; /// # /// fn fixed_time_system(time: Res<Time<Fixed>>) { /// println!("this will always be the last executed fixed timestep: delta {:?}, elapsed {:?}", time.delta(), time.elapsed()); /// } /// ``` /// /// Finally, if your system specifically needs to know the current virtual game /// time, even if placed inside [`FixedUpdate`](bevy_app::FixedUpdate), for /// example to know if the game is [`was_paused()`](Time::was_paused) or to use /// [`effective_speed()`](Time::effective_speed), you can use /// `Res<Time<Virtual>>`. However, if the system is placed in /// [`FixedUpdate`](bevy_app::FixedUpdate), extra care must be used because your /// system might be run multiple times with the same [`delta()`](Time::delta) /// and [`elapsed()`](Time::elapsed) values as the virtual game time has not /// changed between the iterations. /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_time::prelude::*; /// # /// fn fixed_time_system(time: Res<Time<Virtual>>) { /// println!("this will be virtual time for this update: delta {:?}, elapsed {:?}", time.delta(), time.elapsed()); /// println!("also the relative speed of the game is now {}", time.effective_speed()); /// } /// ``` /// /// If you need to change the settings for any of the clocks, for example to /// [`pause()`](Time::pause) the game, you should use `ResMut<Time<Virtual>>`. /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_time::prelude::*; /// # /// #[derive(Message)] /// struct Pause(bool); /// /// fn pause_system(mut time: ResMut<Time<Virtual>>, mut pause_reader: MessageReader<Pause>) { /// for pause in pause_reader.read() { /// if pause.0 { /// time.pause(); /// } else { /// time.unpause(); /// } /// } /// } /// ``` /// /// # Adding custom clocks /// /// New custom clocks can be created by creating your own struct as a context /// and passing it to [`new_with()`](Time::new_with). These clocks can be /// inserted as resources as normal and then accessed by systems. You can use /// the [`advance_by()`](Time::advance_by) or [`advance_to()`](Time::advance_to) /// methods to move the clock forwards based on your own logic. /// /// If you want to add methods for your time instance and they require access to /// both your context and the generic time part, it's probably simplest to add a /// custom trait for them and implement it for `Time<Custom>`. /// /// Your context struct will need to implement the [`Default`] trait because /// [`Time`] structures support reflection. It also makes initialization trivial /// by being able to call `app.init_resource::<Time<Custom>>()`. /// /// You can also replace the "generic" `Time` clock resource if the "default" /// time for your game should not be the default virtual time provided. You can /// get a "generic" snapshot of your clock by calling `as_generic()` and then /// overwrite the [`Time`] resource with it. The default systems added by /// [`TimePlugin`](crate::TimePlugin) will overwrite the [`Time`] clock during /// [`First`](bevy_app::First) and [`FixedUpdate`](bevy_app::FixedUpdate) /// schedules. /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_time::prelude::*; /// # use bevy_platform::time::Instant; /// # /// #[derive(Debug)] /// struct Custom { /// last_external_time: Instant, /// } /// /// impl Default for Custom { /// fn default() -> Self { /// Self { /// last_external_time: Instant::now(), /// } /// } /// } /// /// trait CustomTime { /// fn update_from_external(&mut self, instant: Instant); /// } /// /// impl CustomTime for Time<Custom> { /// fn update_from_external(&mut self, instant: Instant) { /// let delta = instant - self.context().last_external_time; /// self.advance_by(delta); /// self.context_mut().last_external_time = instant; /// } /// } /// ``` #[derive(Resource, Debug, Copy, Clone)] #[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Resource, Default))] pub struct Time<T: Default = ()> { context: T, wrap_period: Duration, delta: Duration, delta_secs: f32, delta_secs_f64: f64, elapsed: Duration, elapsed_secs: f32, elapsed_secs_f64: f64, elapsed_wrapped: Duration, elapsed_secs_wrapped: f32, elapsed_secs_wrapped_f64: f64, } impl<T: Default> Time<T> { const DEFAULT_WRAP_PERIOD: Duration = Duration::from_secs(3600); // 1 hour /// Create a new clock from context with [`Self::delta`] and [`Self::elapsed`] starting from /// zero. pub fn new_with(context: T) -> Self { Self { context, ..Default::default() } } /// Advance this clock by adding a `delta` duration to it. /// /// The added duration will be returned by [`Self::delta`] and /// [`Self::elapsed`] will be increased by the duration. Adding /// [`Duration::ZERO`] is allowed and will set [`Self::delta`] to zero. pub fn advance_by(&mut self, delta: Duration) { self.delta = delta; self.delta_secs = self.delta.as_secs_f32(); self.delta_secs_f64 = self.delta.as_secs_f64(); self.elapsed += delta; self.elapsed_secs = self.elapsed.as_secs_f32(); self.elapsed_secs_f64 = self.elapsed.as_secs_f64(); self.elapsed_wrapped = duration_rem(self.elapsed, self.wrap_period); self.elapsed_secs_wrapped = self.elapsed_wrapped.as_secs_f32(); self.elapsed_secs_wrapped_f64 = self.elapsed_wrapped.as_secs_f64(); } /// Advance this clock to a specific `elapsed` time. /// /// [`Self::delta()`] will return the amount of time the clock was advanced /// and [`Self::elapsed()`] will be the `elapsed` value passed in. Cannot be /// used to move time backwards. /// /// # Panics /// /// Panics if `elapsed` is less than `Self::elapsed()`. pub fn advance_to(&mut self, elapsed: Duration) { assert!( elapsed >= self.elapsed, "tried to move time backwards to an earlier elapsed moment" ); self.advance_by(elapsed - self.elapsed); } /// Returns the modulus used to calculate [`elapsed_wrapped`](#method.elapsed_wrapped). /// /// **Note:** The default modulus is one hour. #[inline] pub fn wrap_period(&self) -> Duration { self.wrap_period } /// Sets the modulus used to calculate [`elapsed_wrapped`](#method.elapsed_wrapped). /// /// **Note:** This will not take effect until the next update. /// /// # Panics /// /// Panics if `wrap_period` is a zero-length duration. #[inline] pub fn set_wrap_period(&mut self, wrap_period: Duration) { assert!(!wrap_period.is_zero(), "division by zero"); self.wrap_period = wrap_period; } /// Returns how much time has advanced since the last [`update`](#method.update), as a /// [`Duration`]. #[inline] pub fn delta(&self) -> Duration { self.delta } /// Returns how much time has advanced since the last [`update`](#method.update), as [`f32`] /// seconds. #[inline] pub fn delta_secs(&self) -> f32 { self.delta_secs } /// Returns how much time has advanced since the last [`update`](#method.update), as [`f64`] /// seconds. #[inline] pub fn delta_secs_f64(&self) -> f64 { self.delta_secs_f64 } /// Returns how much time has advanced since [`startup`](#method.startup), as [`Duration`]. #[inline] pub fn elapsed(&self) -> Duration { self.elapsed } /// Returns how much time has advanced since [`startup`](#method.startup), as [`f32`] seconds. /// /// **Note:** This is a monotonically increasing value. Its precision will degrade over time. /// If you need an `f32` but that precision loss is unacceptable, /// use [`elapsed_secs_wrapped`](#method.elapsed_secs_wrapped). #[inline] pub fn elapsed_secs(&self) -> f32 { self.elapsed_secs } /// Returns how much time has advanced since [`startup`](#method.startup), as [`f64`] seconds. #[inline] pub fn elapsed_secs_f64(&self) -> f64 { self.elapsed_secs_f64 } /// Returns how much time has advanced since [`startup`](#method.startup) modulo /// the [`wrap_period`](#method.wrap_period), as [`Duration`]. #[inline] pub fn elapsed_wrapped(&self) -> Duration { self.elapsed_wrapped } /// Returns how much time has advanced since [`startup`](#method.startup) modulo /// the [`wrap_period`](#method.wrap_period), as [`f32`] seconds. /// /// This method is intended for applications (e.g. shaders) that require an [`f32`] value but /// suffer from the gradual precision loss of [`elapsed_secs`](#method.elapsed_secs). #[inline] pub fn elapsed_secs_wrapped(&self) -> f32 { self.elapsed_secs_wrapped } /// Returns how much time has advanced since [`startup`](#method.startup) modulo /// the [`wrap_period`](#method.wrap_period), as [`f64`] seconds. #[inline] pub fn elapsed_secs_wrapped_f64(&self) -> f64 { self.elapsed_secs_wrapped_f64 } /// Returns a reference to the context of this specific clock. #[inline] pub fn context(&self) -> &T { &self.context } /// Returns a mutable reference to the context of this specific clock. #[inline] pub fn context_mut(&mut self) -> &mut T { &mut self.context } /// Returns a copy of this clock as fully generic clock without context. #[inline] pub fn as_generic(&self) -> Time<()> { Time { context: (), wrap_period: self.wrap_period, delta: self.delta, delta_secs: self.delta_secs, delta_secs_f64: self.delta_secs_f64, elapsed: self.elapsed, elapsed_secs: self.elapsed_secs, elapsed_secs_f64: self.elapsed_secs_f64, elapsed_wrapped: self.elapsed_wrapped, elapsed_secs_wrapped: self.elapsed_secs_wrapped, elapsed_secs_wrapped_f64: self.elapsed_secs_wrapped_f64, } } } impl<T: Default> Default for Time<T> { fn default() -> Self { Self { context: Default::default(), wrap_period: Self::DEFAULT_WRAP_PERIOD, delta: Duration::ZERO, delta_secs: 0.0, delta_secs_f64: 0.0, elapsed: Duration::ZERO, elapsed_secs: 0.0, elapsed_secs_f64: 0.0, elapsed_wrapped: Duration::ZERO, elapsed_secs_wrapped: 0.0, elapsed_secs_wrapped_f64: 0.0, } } } fn duration_rem(dividend: Duration, divisor: Duration) -> Duration { // `Duration` does not have a built-in modulo operation let quotient = (dividend.as_nanos() / divisor.as_nanos()) as u32; dividend - (quotient * divisor) } #[cfg(test)] mod test { use super::*; #[test] fn test_initial_state() { let time: Time = Time::default(); assert_eq!(time.wrap_period(), Time::<()>::DEFAULT_WRAP_PERIOD); assert_eq!(time.delta(), Duration::ZERO); assert_eq!(time.delta_secs(), 0.0); assert_eq!(time.delta_secs_f64(), 0.0); assert_eq!(time.elapsed(), Duration::ZERO); assert_eq!(time.elapsed_secs(), 0.0); assert_eq!(time.elapsed_secs_f64(), 0.0); assert_eq!(time.elapsed_wrapped(), Duration::ZERO); assert_eq!(time.elapsed_secs_wrapped(), 0.0); assert_eq!(time.elapsed_secs_wrapped_f64(), 0.0); } #[test] fn test_advance_by() { let mut time: Time = Time::default(); time.advance_by(Duration::from_millis(250)); assert_eq!(time.delta(), Duration::from_millis(250)); assert_eq!(time.delta_secs(), 0.25); assert_eq!(time.delta_secs_f64(), 0.25); assert_eq!(time.elapsed(), Duration::from_millis(250)); assert_eq!(time.elapsed_secs(), 0.25); assert_eq!(time.elapsed_secs_f64(), 0.25); time.advance_by(Duration::from_millis(500)); assert_eq!(time.delta(), Duration::from_millis(500)); assert_eq!(time.delta_secs(), 0.5); assert_eq!(time.delta_secs_f64(), 0.5); assert_eq!(time.elapsed(), Duration::from_millis(750)); assert_eq!(time.elapsed_secs(), 0.75); assert_eq!(time.elapsed_secs_f64(), 0.75); time.advance_by(Duration::ZERO); assert_eq!(time.delta(), Duration::ZERO); assert_eq!(time.delta_secs(), 0.0); assert_eq!(time.delta_secs_f64(), 0.0); assert_eq!(time.elapsed(), Duration::from_millis(750)); assert_eq!(time.elapsed_secs(), 0.75); assert_eq!(time.elapsed_secs_f64(), 0.75); } #[test] fn test_advance_to() { let mut time: Time = Time::default(); time.advance_to(Duration::from_millis(250)); assert_eq!(time.delta(), Duration::from_millis(250)); assert_eq!(time.delta_secs(), 0.25); assert_eq!(time.delta_secs_f64(), 0.25); assert_eq!(time.elapsed(), Duration::from_millis(250)); assert_eq!(time.elapsed_secs(), 0.25); assert_eq!(time.elapsed_secs_f64(), 0.25); time.advance_to(Duration::from_millis(750)); assert_eq!(time.delta(), Duration::from_millis(500)); assert_eq!(time.delta_secs(), 0.5); assert_eq!(time.delta_secs_f64(), 0.5); assert_eq!(time.elapsed(), Duration::from_millis(750)); assert_eq!(time.elapsed_secs(), 0.75); assert_eq!(time.elapsed_secs_f64(), 0.75); time.advance_to(Duration::from_millis(750)); assert_eq!(time.delta(), Duration::ZERO); assert_eq!(time.delta_secs(), 0.0); assert_eq!(time.delta_secs_f64(), 0.0); assert_eq!(time.elapsed(), Duration::from_millis(750)); assert_eq!(time.elapsed_secs(), 0.75); assert_eq!(time.elapsed_secs_f64(), 0.75); } #[test] #[should_panic] fn test_advance_to_backwards_panics() { let mut time: Time = Time::default(); time.advance_to(Duration::from_millis(750)); time.advance_to(Duration::from_millis(250)); } #[test] fn test_wrapping() { let mut time: Time = Time::default(); time.set_wrap_period(Duration::from_secs(3)); time.advance_by(Duration::from_secs(2)); assert_eq!(time.elapsed_wrapped(), Duration::from_secs(2)); assert_eq!(time.elapsed_secs_wrapped(), 2.0); assert_eq!(time.elapsed_secs_wrapped_f64(), 2.0); time.advance_by(Duration::from_secs(2)); assert_eq!(time.elapsed_wrapped(), Duration::from_secs(1)); assert_eq!(time.elapsed_secs_wrapped(), 1.0); assert_eq!(time.elapsed_secs_wrapped_f64(), 1.0); time.advance_by(Duration::from_secs(2)); assert_eq!(time.elapsed_wrapped(), Duration::ZERO); assert_eq!(time.elapsed_secs_wrapped(), 0.0); assert_eq!(time.elapsed_secs_wrapped_f64(), 0.0); time.advance_by(Duration::new(3, 250_000_000)); assert_eq!(time.elapsed_wrapped(), Duration::from_millis(250)); assert_eq!(time.elapsed_secs_wrapped(), 0.25); assert_eq!(time.elapsed_secs_wrapped_f64(), 0.25); } #[test] fn test_wrapping_change() { let mut time: Time = Time::default(); time.set_wrap_period(Duration::from_secs(5)); time.advance_by(Duration::from_secs(8)); assert_eq!(time.elapsed_wrapped(), Duration::from_secs(3)); assert_eq!(time.elapsed_secs_wrapped(), 3.0); assert_eq!(time.elapsed_secs_wrapped_f64(), 3.0); time.set_wrap_period(Duration::from_secs(2)); assert_eq!(time.elapsed_wrapped(), Duration::from_secs(3)); assert_eq!(time.elapsed_secs_wrapped(), 3.0); assert_eq!(time.elapsed_secs_wrapped_f64(), 3.0); time.advance_by(Duration::ZERO); // Time will wrap to modulo duration from full `elapsed()`, not to what // is left in `elapsed_wrapped()`. This test of values is here to ensure // that we notice if we change that behavior. assert_eq!(time.elapsed_wrapped(), Duration::from_secs(0)); assert_eq!(time.elapsed_secs_wrapped(), 0.0); assert_eq!(time.elapsed_secs_wrapped_f64(), 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_time/src/timer.rs
crates/bevy_time/src/timer.rs
use crate::Stopwatch; #[cfg(feature = "bevy_reflect")] use bevy_reflect::prelude::*; use core::time::Duration; /// Tracks elapsed time. Enters the finished state once `duration` is reached. /// /// Note that in order to advance the timer [`tick`](Timer::tick) **MUST** be called. /// /// # Timer modes /// /// There are two timer modes ([`TimerMode`]): /// /// - Non repeating timers will stop tracking and stay in the finished state until reset. /// - Repeating timers will only be in the finished state on each tick `duration` is reached or /// exceeded, and can still be reset at any given point. /// /// # Pausing timers /// /// You can pause a timer using [`Timer::pause`]. Paused timers will not have elapsed time increased. /// /// # Elapsing multiple times a frame /// /// Repeating timers might elapse multiple times per frame if the time is advanced by more than the timer duration. /// You can check how many times a timer elapsed each tick with [`Timer::times_finished_this_tick`]. /// For non-repeating timers, this will always be 0 or 1. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serialize", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Default, Clone, PartialEq) )] pub struct Timer { stopwatch: Stopwatch, duration: Duration, mode: TimerMode, finished: bool, times_finished_this_tick: u32, } impl Timer { /// Creates a new timer with a given duration. /// /// See also [`Timer::from_seconds`](Timer::from_seconds). pub fn new(duration: Duration, mode: TimerMode) -> Self { Self { duration, mode, ..Default::default() } } /// Creates a new timer with a given duration in seconds. /// /// # Example /// ``` /// # use bevy_time::*; /// let mut timer = Timer::from_seconds(1.0, TimerMode::Once); /// ``` pub fn from_seconds(duration: f32, mode: TimerMode) -> Self { Self { duration: Duration::from_secs_f32(duration), mode, ..Default::default() } } /// Returns `true` if the timer has reached its duration. /// /// For repeating timers, this method behaves identically to [`Timer::just_finished`]. /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// /// let mut timer_once = Timer::from_seconds(1.0, TimerMode::Once); /// timer_once.tick(Duration::from_secs_f32(1.5)); /// assert!(timer_once.is_finished()); /// timer_once.tick(Duration::from_secs_f32(0.5)); /// assert!(timer_once.is_finished()); /// /// let mut timer_repeating = Timer::from_seconds(1.0, TimerMode::Repeating); /// timer_repeating.tick(Duration::from_secs_f32(1.1)); /// assert!(timer_repeating.is_finished()); /// timer_repeating.tick(Duration::from_secs_f32(0.8)); /// assert!(!timer_repeating.is_finished()); /// timer_repeating.tick(Duration::from_secs_f32(0.6)); /// assert!(timer_repeating.is_finished()); /// ``` #[inline] pub fn is_finished(&self) -> bool { self.finished } /// Returns `true` only on the tick the timer reached its duration. /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut timer = Timer::from_seconds(1.0, TimerMode::Once); /// timer.tick(Duration::from_secs_f32(1.5)); /// assert!(timer.just_finished()); /// timer.tick(Duration::from_secs_f32(0.5)); /// assert!(!timer.just_finished()); /// ``` #[inline] pub fn just_finished(&self) -> bool { self.times_finished_this_tick > 0 } /// Returns the time elapsed on the timer. Guaranteed to be between 0.0 and `duration`. /// Will only equal `duration` when the timer is finished and non repeating. /// /// See also [`Stopwatch::elapsed`](Stopwatch::elapsed). /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut timer = Timer::from_seconds(1.0, TimerMode::Once); /// timer.tick(Duration::from_secs_f32(0.5)); /// assert_eq!(timer.elapsed(), Duration::from_secs_f32(0.5)); /// ``` #[inline] pub fn elapsed(&self) -> Duration { self.stopwatch.elapsed() } /// Returns the time elapsed on the timer as an `f32`. /// See also [`Timer::elapsed`](Timer::elapsed). #[inline] pub fn elapsed_secs(&self) -> f32 { self.stopwatch.elapsed_secs() } /// Returns the time elapsed on the timer as an `f64`. /// See also [`Timer::elapsed`](Timer::elapsed). #[inline] pub fn elapsed_secs_f64(&self) -> f64 { self.stopwatch.elapsed_secs_f64() } /// Sets the elapsed time of the timer without any other considerations. /// /// See also [`Stopwatch::set`](Stopwatch::set). /// /// # /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut timer = Timer::from_seconds(1.0, TimerMode::Once); /// timer.set_elapsed(Duration::from_secs(2)); /// assert_eq!(timer.elapsed(), Duration::from_secs(2)); /// // the timer is not finished even if the elapsed time is greater than the duration. /// assert!(!timer.is_finished()); /// ``` #[inline] pub fn set_elapsed(&mut self, time: Duration) { self.stopwatch.set_elapsed(time); } /// Returns the duration of the timer. /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let timer = Timer::new(Duration::from_secs(1), TimerMode::Once); /// assert_eq!(timer.duration(), Duration::from_secs(1)); /// ``` #[inline] pub fn duration(&self) -> Duration { self.duration } /// Sets the duration of the timer. /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut timer = Timer::from_seconds(1.5, TimerMode::Once); /// timer.set_duration(Duration::from_secs(1)); /// assert_eq!(timer.duration(), Duration::from_secs(1)); /// ``` #[inline] pub fn set_duration(&mut self, duration: Duration) { self.duration = duration; } /// Finishes the timer. /// /// # Examples /// ``` /// # use bevy_time::*; /// let mut timer = Timer::from_seconds(1.5, TimerMode::Once); /// timer.finish(); /// assert!(timer.is_finished()); /// ``` #[inline] pub fn finish(&mut self) { let remaining = self.remaining(); self.tick(remaining); } /// Almost finishes the timer leaving 1 ns of remaining time. /// This can be useful when needing an immediate action without having /// to wait for the set duration of the timer in the first tick. /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut timer = Timer::from_seconds(1.5, TimerMode::Once); /// timer.almost_finish(); /// assert!(!timer.is_finished()); /// assert_eq!(timer.remaining(), Duration::from_nanos(1)); /// ``` #[inline] pub fn almost_finish(&mut self) { let remaining = self.remaining() - Duration::from_nanos(1); self.tick(remaining); } /// Returns the mode of the timer. /// /// # Examples /// ``` /// # use bevy_time::*; /// let mut timer = Timer::from_seconds(1.0, TimerMode::Repeating); /// assert_eq!(timer.mode(), TimerMode::Repeating); /// ``` #[inline] pub fn mode(&self) -> TimerMode { self.mode } /// Sets the mode of the timer. /// /// # Examples /// ``` /// # use bevy_time::*; /// let mut timer = Timer::from_seconds(1.0, TimerMode::Repeating); /// timer.set_mode(TimerMode::Once); /// assert_eq!(timer.mode(), TimerMode::Once); /// ``` #[doc(alias = "repeating")] #[inline] pub fn set_mode(&mut self, mode: TimerMode) { if self.mode != TimerMode::Repeating && mode == TimerMode::Repeating && self.finished { self.stopwatch.reset(); self.finished = self.just_finished(); } self.mode = mode; } /// Advance the timer by `delta` seconds. /// Non repeating timer will clamp at duration. /// Repeating timer will wrap around. /// Will not affect paused timers. /// /// See also [`Stopwatch::tick`](Stopwatch::tick). /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut timer = Timer::from_seconds(1.0, TimerMode::Once); /// let mut repeating = Timer::from_seconds(1.0, TimerMode::Repeating); /// timer.tick(Duration::from_secs_f32(1.5)); /// repeating.tick(Duration::from_secs_f32(1.5)); /// assert_eq!(timer.elapsed_secs(), 1.0); /// assert_eq!(repeating.elapsed_secs(), 0.5); /// ``` pub fn tick(&mut self, delta: Duration) -> &Self { if self.is_paused() { self.times_finished_this_tick = 0; if self.mode == TimerMode::Repeating { self.finished = false; } return self; } if self.mode != TimerMode::Repeating && self.is_finished() { self.times_finished_this_tick = 0; return self; } self.stopwatch.tick(delta); self.finished = self.elapsed() >= self.duration(); if self.is_finished() { if self.mode == TimerMode::Repeating { self.times_finished_this_tick = self .elapsed() .as_nanos() .checked_div(self.duration().as_nanos()) .map_or(u32::MAX, |x| x as u32); self.set_elapsed( self.elapsed() .as_nanos() .checked_rem(self.duration().as_nanos()) .map_or(Duration::ZERO, |x| Duration::from_nanos(x as u64)), ); } else { self.times_finished_this_tick = 1; self.set_elapsed(self.duration()); } } else { self.times_finished_this_tick = 0; } self } /// Pauses the Timer. Disables the ticking of the timer. /// /// See also [`Stopwatch::pause`](Stopwatch::pause). /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut timer = Timer::from_seconds(1.0, TimerMode::Once); /// timer.pause(); /// timer.tick(Duration::from_secs_f32(0.5)); /// assert_eq!(timer.elapsed_secs(), 0.0); /// ``` #[inline] pub fn pause(&mut self) { self.stopwatch.pause(); } /// Unpauses the Timer. Resumes the ticking of the timer. /// /// See also [`Stopwatch::unpause()`](Stopwatch::unpause). /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut timer = Timer::from_seconds(1.0, TimerMode::Once); /// timer.pause(); /// timer.tick(Duration::from_secs_f32(0.5)); /// timer.unpause(); /// timer.tick(Duration::from_secs_f32(0.5)); /// assert_eq!(timer.elapsed_secs(), 0.5); /// ``` #[inline] pub fn unpause(&mut self) { self.stopwatch.unpause(); } /// Returns `true` if the timer is paused. /// /// See also [`Stopwatch::is_paused`](Stopwatch::is_paused). /// /// # Examples /// ``` /// # use bevy_time::*; /// let mut timer = Timer::from_seconds(1.0, TimerMode::Once); /// assert!(!timer.is_paused()); /// timer.pause(); /// assert!(timer.is_paused()); /// timer.unpause(); /// assert!(!timer.is_paused()); /// ``` #[inline] pub fn is_paused(&self) -> bool { self.stopwatch.is_paused() } /// Resets the timer. The reset doesn't affect the `paused` state of the timer. /// /// See also [`Stopwatch::reset`](Stopwatch::reset). /// /// Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut timer = Timer::from_seconds(1.0, TimerMode::Once); /// timer.tick(Duration::from_secs_f32(1.5)); /// timer.reset(); /// assert!(!timer.is_finished()); /// assert!(!timer.just_finished()); /// assert_eq!(timer.elapsed_secs(), 0.0); /// ``` pub fn reset(&mut self) { self.stopwatch.reset(); self.finished = false; self.times_finished_this_tick = 0; } /// Returns the fraction of the timer elapsed time (goes from 0.0 to 1.0). /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut timer = Timer::from_seconds(2.0, TimerMode::Once); /// timer.tick(Duration::from_secs_f32(0.5)); /// assert_eq!(timer.fraction(), 0.25); /// ``` #[inline] pub fn fraction(&self) -> f32 { if self.duration == Duration::ZERO { 1.0 } else { self.elapsed().as_secs_f32() / self.duration().as_secs_f32() } } /// Returns the fraction of the timer remaining time (goes from 1.0 to 0.0). /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut timer = Timer::from_seconds(2.0, TimerMode::Once); /// timer.tick(Duration::from_secs_f32(0.5)); /// assert_eq!(timer.fraction_remaining(), 0.75); /// ``` #[inline] pub fn fraction_remaining(&self) -> f32 { 1.0 - self.fraction() } /// Returns the remaining time in seconds /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::cmp::Ordering; /// use std::time::Duration; /// let mut timer = Timer::from_seconds(2.0, TimerMode::Once); /// timer.tick(Duration::from_secs_f32(0.5)); /// let result = timer.remaining_secs().total_cmp(&1.5); /// assert_eq!(Ordering::Equal, result); /// ``` #[inline] pub fn remaining_secs(&self) -> f32 { self.remaining().as_secs_f32() } /// Returns the remaining time using Duration /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut timer = Timer::from_seconds(2.0, TimerMode::Once); /// timer.tick(Duration::from_secs_f32(0.5)); /// assert_eq!(timer.remaining(), Duration::from_secs_f32(1.5)); /// ``` #[inline] pub fn remaining(&self) -> Duration { self.duration() - self.elapsed() } /// Returns the number of times a repeating timer /// finished during the last [`tick`](Timer<T>::tick) call. /// /// For non repeating-timers, this method will only ever /// return 0 or 1. /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut timer = Timer::from_seconds(1.0, TimerMode::Repeating); /// timer.tick(Duration::from_secs_f32(6.0)); /// assert_eq!(timer.times_finished_this_tick(), 6); /// timer.tick(Duration::from_secs_f32(2.0)); /// assert_eq!(timer.times_finished_this_tick(), 2); /// timer.tick(Duration::from_secs_f32(0.5)); /// assert_eq!(timer.times_finished_this_tick(), 0); /// ``` #[inline] pub fn times_finished_this_tick(&self) -> u32 { self.times_finished_this_tick } } /// Specifies [`Timer`] behavior. #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Default)] #[cfg_attr(feature = "serialize", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Default, Clone, PartialEq, Hash) )] pub enum TimerMode { /// Run once and stop. #[default] Once, /// Reset when finished. Repeating, } #[cfg(test)] mod tests { use super::*; #[test] fn non_repeating_timer() { let mut t = Timer::from_seconds(10.0, TimerMode::Once); // Tick once, check all attributes t.tick(Duration::from_secs_f32(0.25)); assert_eq!(t.elapsed_secs(), 0.25); assert_eq!(t.elapsed_secs_f64(), 0.25); assert_eq!(t.duration(), Duration::from_secs_f32(10.0)); assert!(!t.is_finished()); assert!(!t.just_finished()); assert_eq!(t.times_finished_this_tick(), 0); assert_eq!(t.mode(), TimerMode::Once); assert_eq!(t.fraction(), 0.025); assert_eq!(t.fraction_remaining(), 0.975); // Ticking while paused changes nothing t.pause(); t.tick(Duration::from_secs_f32(500.0)); assert_eq!(t.elapsed_secs(), 0.25); assert_eq!(t.duration(), Duration::from_secs_f32(10.0)); assert!(!t.is_finished()); assert!(!t.just_finished()); assert_eq!(t.times_finished_this_tick(), 0); assert_eq!(t.mode(), TimerMode::Once); assert_eq!(t.fraction(), 0.025); assert_eq!(t.fraction_remaining(), 0.975); // Tick past the end and make sure elapsed doesn't go past 0.0 and other things update t.unpause(); t.tick(Duration::from_secs_f32(500.0)); assert_eq!(t.elapsed_secs(), 10.0); assert_eq!(t.elapsed_secs_f64(), 10.0); assert!(t.is_finished()); assert!(t.just_finished()); assert_eq!(t.times_finished_this_tick(), 1); assert_eq!(t.fraction(), 1.0); assert_eq!(t.fraction_remaining(), 0.0); // Continuing to tick when finished should only change just_finished t.tick(Duration::from_secs_f32(1.0)); assert_eq!(t.elapsed_secs(), 10.0); assert_eq!(t.elapsed_secs_f64(), 10.0); assert!(t.is_finished()); assert!(!t.just_finished()); assert_eq!(t.times_finished_this_tick(), 0); assert_eq!(t.fraction(), 1.0); assert_eq!(t.fraction_remaining(), 0.0); } #[test] fn repeating_timer() { let mut t = Timer::from_seconds(2.0, TimerMode::Repeating); // Tick once, check all attributes t.tick(Duration::from_secs_f32(0.75)); assert_eq!(t.elapsed_secs(), 0.75); assert_eq!(t.elapsed_secs_f64(), 0.75); assert_eq!(t.duration(), Duration::from_secs_f32(2.0)); assert!(!t.is_finished()); assert!(!t.just_finished()); assert_eq!(t.times_finished_this_tick(), 0); assert_eq!(t.mode(), TimerMode::Repeating); assert_eq!(t.fraction(), 0.375); assert_eq!(t.fraction_remaining(), 0.625); // Tick past the end and make sure elapsed wraps t.tick(Duration::from_secs_f32(1.5)); assert_eq!(t.elapsed_secs(), 0.25); assert_eq!(t.elapsed_secs_f64(), 0.25); assert!(t.is_finished()); assert!(t.just_finished()); assert_eq!(t.times_finished_this_tick(), 1); assert_eq!(t.fraction(), 0.125); assert_eq!(t.fraction_remaining(), 0.875); // Continuing to tick should turn off both finished & just_finished for repeating timers t.tick(Duration::from_secs_f32(1.0)); assert_eq!(t.elapsed_secs(), 1.25); assert_eq!(t.elapsed_secs_f64(), 1.25); assert!(!t.is_finished()); assert!(!t.just_finished()); assert_eq!(t.times_finished_this_tick(), 0); assert_eq!(t.fraction(), 0.625); assert_eq!(t.fraction_remaining(), 0.375); } #[test] fn times_finished_repeating() { let mut t = Timer::from_seconds(1.0, TimerMode::Repeating); assert_eq!(t.times_finished_this_tick(), 0); t.tick(Duration::from_secs_f32(3.5)); assert_eq!(t.times_finished_this_tick(), 3); assert_eq!(t.elapsed_secs(), 0.5); assert_eq!(t.elapsed_secs_f64(), 0.5); assert!(t.is_finished()); assert!(t.just_finished()); t.tick(Duration::from_secs_f32(0.2)); assert_eq!(t.times_finished_this_tick(), 0); } #[test] fn times_finished_this_tick() { let mut t = Timer::from_seconds(1.0, TimerMode::Once); assert_eq!(t.times_finished_this_tick(), 0); t.tick(Duration::from_secs_f32(1.5)); assert_eq!(t.times_finished_this_tick(), 1); t.tick(Duration::from_secs_f32(0.5)); assert_eq!(t.times_finished_this_tick(), 0); } #[test] fn times_finished_this_tick_repeating_zero_duration() { let mut t = Timer::from_seconds(0.0, TimerMode::Repeating); assert_eq!(t.times_finished_this_tick(), 0); assert_eq!(t.elapsed(), Duration::ZERO); assert_eq!(t.fraction(), 1.0); t.tick(Duration::from_secs(1)); assert_eq!(t.times_finished_this_tick(), u32::MAX); assert_eq!(t.elapsed(), Duration::ZERO); assert_eq!(t.fraction(), 1.0); t.tick(Duration::from_secs(2)); assert_eq!(t.times_finished_this_tick(), u32::MAX); assert_eq!(t.elapsed(), Duration::ZERO); assert_eq!(t.fraction(), 1.0); t.reset(); assert_eq!(t.times_finished_this_tick(), 0); assert_eq!(t.elapsed(), Duration::ZERO); assert_eq!(t.fraction(), 1.0); } #[test] fn times_finished_this_tick_precise() { let mut t = Timer::from_seconds(0.01, TimerMode::Repeating); let duration = Duration::from_secs_f64(0.333); // total duration: 0.333 => 33 times finished t.tick(duration); assert_eq!(t.times_finished_this_tick(), 33); // total duration: 0.666 => 33 times finished t.tick(duration); assert_eq!(t.times_finished_this_tick(), 33); // total duration: 0.999 => 33 times finished t.tick(duration); assert_eq!(t.times_finished_this_tick(), 33); // total duration: 1.332 => 34 times finished t.tick(duration); assert_eq!(t.times_finished_this_tick(), 34); } #[test] fn almost_finished_repeating() { let mut t = Timer::from_seconds(10.0, TimerMode::Repeating); let duration = Duration::from_nanos(1); t.almost_finish(); assert!(!t.is_finished()); assert_eq!(t.times_finished_this_tick(), 0); assert_eq!(t.remaining(), Duration::from_nanos(1)); t.tick(duration); assert!(t.is_finished()); assert_eq!(t.times_finished_this_tick(), 1); } #[test] fn paused() { let mut t = Timer::from_seconds(10.0, TimerMode::Once); t.tick(Duration::from_secs_f32(10.0)); assert!(t.just_finished()); assert!(t.is_finished()); // A paused timer should change just_finished to false after a tick t.pause(); t.tick(Duration::from_secs_f32(5.0)); assert!(!t.just_finished()); assert!(t.is_finished()); } #[test] fn paused_repeating() { let mut t = Timer::from_seconds(10.0, TimerMode::Repeating); t.tick(Duration::from_secs_f32(10.0)); assert!(t.just_finished()); assert!(t.is_finished()); // A paused repeating timer should change finished and just_finished to false after a tick t.pause(); t.tick(Duration::from_secs_f32(5.0)); assert!(!t.just_finished()); assert!(!t.is_finished()); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_time/src/common_conditions.rs
crates/bevy_time/src/common_conditions.rs
use crate::{Real, Time, Timer, TimerMode, Virtual}; use bevy_ecs::system::Res; use core::time::Duration; /// Run condition that is active on a regular time interval, using [`Time`] to advance /// the timer. The timer ticks at the rate of [`Time::relative_speed`]. /// /// ```no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, Update}; /// # use bevy_ecs::schedule::IntoScheduleConfigs; /// # use core::time::Duration; /// # use bevy_time::common_conditions::on_timer; /// fn main() { /// App::new() /// .add_plugins(DefaultPlugins) /// .add_systems( /// Update, /// tick.run_if(on_timer(Duration::from_secs(1))), /// ) /// .run(); /// } /// fn tick() { /// // ran once a second /// } /// ``` /// /// Note that this does **not** guarantee that systems will run at exactly the /// specified interval. If delta time is larger than the specified `duration` then /// the system will only run once even though the timer may have completed multiple /// times. This condition should only be used with large time durations (relative to /// delta time). /// /// For more accurate timers, use the [`Timer`] class directly (see /// [`Timer::times_finished_this_tick`] to address the problem mentioned above), or /// use fixed timesteps that allow systems to run multiple times per frame. pub fn on_timer(duration: Duration) -> impl FnMut(Res<Time>) -> bool + Clone { let mut timer = Timer::new(duration, TimerMode::Repeating); move |time: Res<Time>| { timer.tick(time.delta()); timer.just_finished() } } /// Run condition that is active on a regular time interval, /// using [`Time<Real>`] to advance the timer. /// The timer ticks are not scaled. /// /// ```no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, Update}; /// # use bevy_ecs::schedule::IntoScheduleConfigs; /// # use core::time::Duration; /// # use bevy_time::common_conditions::on_real_timer; /// fn main() { /// App::new() /// .add_plugins(DefaultPlugins) /// .add_systems( /// Update, /// tick.run_if(on_real_timer(Duration::from_secs(1))), /// ) /// .run(); /// } /// fn tick() { /// // ran once a second /// } /// ``` /// /// Note that this does **not** guarantee that systems will run at exactly the /// specified interval. If delta time is larger than the specified `duration` then /// the system will only run once even though the timer may have completed multiple /// times. This condition should only be used with large time durations (relative to /// delta time). /// /// For more accurate timers, use the [`Timer`] class directly (see /// [`Timer::times_finished_this_tick`] to address the problem mentioned above), or /// use fixed timesteps that allow systems to run multiple times per frame. pub fn on_real_timer(duration: Duration) -> impl FnMut(Res<Time<Real>>) -> bool + Clone { let mut timer = Timer::new(duration, TimerMode::Repeating); move |time: Res<Time<Real>>| { timer.tick(time.delta()); timer.just_finished() } } /// Run condition that is active *once* after the specified delay, /// using [`Time`] to advance the timer. /// The timer ticks at the rate of [`Time::relative_speed`]. /// /// ```rust,no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, Update}; /// # use bevy_ecs::schedule::IntoScheduleConfigs; /// # use core::time::Duration; /// # use bevy_time::common_conditions::once_after_delay; /// fn main() { /// App::new() /// .add_plugins(DefaultPlugins) /// .add_systems( /// Update, /// tick.run_if(once_after_delay(Duration::from_secs(1))), /// ) /// .run(); /// } /// fn tick() { /// // ran once, after a second /// } /// ``` pub fn once_after_delay(duration: Duration) -> impl FnMut(Res<Time>) -> bool + Clone { let mut timer = Timer::new(duration, TimerMode::Once); move |time: Res<Time>| { timer.tick(time.delta()); timer.just_finished() } } /// Run condition that is active *once* after the specified delay, /// using [`Time<Real>`] to advance the timer. /// The timer ticks are not scaled. /// /// ```rust,no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, Update}; /// # use bevy_ecs::schedule::IntoScheduleConfigs; /// # use core::time::Duration; /// # use bevy_time::common_conditions::once_after_delay; /// fn main() { /// App::new() /// .add_plugins(DefaultPlugins) /// .add_systems( /// Update, /// tick.run_if(once_after_delay(Duration::from_secs(1))), /// ) /// .run(); /// } /// fn tick() { /// // ran once, after a second /// } /// ``` pub fn once_after_real_delay(duration: Duration) -> impl FnMut(Res<Time<Real>>) -> bool + Clone { let mut timer = Timer::new(duration, TimerMode::Once); move |time: Res<Time<Real>>| { timer.tick(time.delta()); timer.just_finished() } } /// Run condition that is active *indefinitely* after the specified delay, /// using [`Time`] to advance the timer. /// The timer ticks at the rate of [`Time::relative_speed`]. /// /// ```rust,no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, Update}; /// # use bevy_ecs::schedule::IntoScheduleConfigs; /// # use core::time::Duration; /// # use bevy_time::common_conditions::repeating_after_delay; /// fn main() { /// App::new() /// .add_plugins(DefaultPlugins) /// .add_systems( /// Update, /// tick.run_if(repeating_after_delay(Duration::from_secs(1))), /// ) /// .run(); /// } /// fn tick() { /// // ran every frame, after a second /// } /// ``` pub fn repeating_after_delay(duration: Duration) -> impl FnMut(Res<Time>) -> bool + Clone { let mut timer = Timer::new(duration, TimerMode::Once); move |time: Res<Time>| { timer.tick(time.delta()); timer.is_finished() } } /// Run condition that is active *indefinitely* after the specified delay, /// using [`Time<Real>`] to advance the timer. /// The timer ticks are not scaled. /// /// ```rust,no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, Update}; /// # use bevy_ecs::schedule::IntoScheduleConfigs; /// # use core::time::Duration; /// # use bevy_time::common_conditions::repeating_after_real_delay; /// fn main() { /// App::new() /// .add_plugins(DefaultPlugins) /// .add_systems( /// Update, /// tick.run_if(repeating_after_real_delay(Duration::from_secs(1))), /// ) /// .run(); /// } /// fn tick() { /// // ran every frame, after a second /// } /// ``` pub fn repeating_after_real_delay( duration: Duration, ) -> impl FnMut(Res<Time<Real>>) -> bool + Clone { let mut timer = Timer::new(duration, TimerMode::Once); move |time: Res<Time<Real>>| { timer.tick(time.delta()); timer.is_finished() } } /// Run condition that is active when the [`Time<Virtual>`] clock is paused. /// Use [`bevy_ecs::schedule::common_conditions::not`] to make it active when /// it's not paused. /// /// ```rust,no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, Update}; /// # use bevy_ecs::schedule::{common_conditions::not, IntoScheduleConfigs}; /// # use bevy_time::common_conditions::paused; /// fn main() { /// App::new() /// .add_plugins(DefaultPlugins) /// .add_systems( /// Update, /// ( /// is_paused.run_if(paused), /// not_paused.run_if(not(paused)), /// ) /// ) /// .run(); /// } /// fn is_paused() { /// // ran when time is paused /// } /// /// fn not_paused() { /// // ran when time is not paused /// } /// ``` pub fn paused(time: Res<Time<Virtual>>) -> bool { time.is_paused() } #[cfg(test)] mod tests { use super::*; use bevy_ecs::schedule::{IntoScheduleConfigs, Schedule}; fn test_system() {} // Ensure distributive_run_if compiles with the common conditions. #[test] fn distributive_run_if_compiles() { Schedule::default().add_systems( (test_system, test_system) .distributive_run_if(on_timer(Duration::new(1, 0))) .distributive_run_if(paused), ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_time/src/stopwatch.rs
crates/bevy_time/src/stopwatch.rs
#[cfg(feature = "bevy_reflect")] use bevy_reflect::{prelude::*, Reflect}; use core::time::Duration; /// A Stopwatch is a struct that tracks elapsed time when started. /// /// Note that in order to advance the stopwatch [`tick`](Stopwatch::tick) **MUST** be called. /// # Examples /// /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut stopwatch = Stopwatch::new(); /// assert_eq!(stopwatch.elapsed_secs(), 0.0); /// /// stopwatch.tick(Duration::from_secs_f32(1.0)); // tick one second /// assert_eq!(stopwatch.elapsed_secs(), 1.0); /// /// stopwatch.pause(); /// stopwatch.tick(Duration::from_secs_f32(1.0)); // paused stopwatches don't tick /// assert_eq!(stopwatch.elapsed_secs(), 1.0); /// /// stopwatch.reset(); // reset the stopwatch /// assert!(stopwatch.is_paused()); /// assert_eq!(stopwatch.elapsed_secs(), 0.0); /// ``` #[derive(Clone, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serialize", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Default, Clone, PartialEq) )] pub struct Stopwatch { elapsed: Duration, is_paused: bool, } impl Stopwatch { /// Create a new unpaused `Stopwatch` with no elapsed time. /// /// # Examples /// ``` /// # use bevy_time::*; /// let stopwatch = Stopwatch::new(); /// assert_eq!(stopwatch.elapsed_secs(), 0.0); /// assert_eq!(stopwatch.is_paused(), false); /// ``` pub fn new() -> Self { Default::default() } /// Returns the elapsed time since the last [`reset`](Stopwatch::reset) /// of the stopwatch. /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut stopwatch = Stopwatch::new(); /// stopwatch.tick(Duration::from_secs(1)); /// assert_eq!(stopwatch.elapsed(), Duration::from_secs(1)); /// ``` /// /// # See Also /// /// [`elapsed_secs`](Stopwatch::elapsed_secs) - if an `f32` value is desirable instead. /// [`elapsed_secs_f64`](Stopwatch::elapsed_secs_f64) - if an `f64` is desirable instead. #[inline] pub fn elapsed(&self) -> Duration { self.elapsed } /// Returns the elapsed time since the last [`reset`](Stopwatch::reset) /// of the stopwatch, in seconds. /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut stopwatch = Stopwatch::new(); /// stopwatch.tick(Duration::from_secs(1)); /// assert_eq!(stopwatch.elapsed_secs(), 1.0); /// ``` /// /// # See Also /// /// [`elapsed`](Stopwatch::elapsed) - if a `Duration` is desirable instead. /// [`elapsed_secs_f64`](Stopwatch::elapsed_secs_f64) - if an `f64` is desirable instead. #[inline] pub fn elapsed_secs(&self) -> f32 { self.elapsed().as_secs_f32() } /// Returns the elapsed time since the last [`reset`](Stopwatch::reset) /// of the stopwatch, in seconds, as f64. /// /// # See Also /// /// [`elapsed`](Stopwatch::elapsed) - if a `Duration` is desirable instead. /// [`elapsed_secs`](Stopwatch::elapsed_secs) - if an `f32` is desirable instead. #[inline] pub fn elapsed_secs_f64(&self) -> f64 { self.elapsed().as_secs_f64() } /// Sets the elapsed time of the stopwatch. /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut stopwatch = Stopwatch::new(); /// stopwatch.set_elapsed(Duration::from_secs_f32(1.0)); /// assert_eq!(stopwatch.elapsed_secs(), 1.0); /// ``` #[inline] pub fn set_elapsed(&mut self, time: Duration) { self.elapsed = time; } /// Advance the stopwatch by `delta` seconds. /// If the stopwatch is paused, ticking will not have any effect /// on elapsed time. /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut stopwatch = Stopwatch::new(); /// stopwatch.tick(Duration::from_secs_f32(1.5)); /// assert_eq!(stopwatch.elapsed_secs(), 1.5); /// ``` pub fn tick(&mut self, delta: Duration) -> &Self { if !self.is_paused() { self.elapsed = self.elapsed.saturating_add(delta); } self } /// Pauses the stopwatch. Any call to [`tick`](Stopwatch::tick) while /// paused will not have any effect on the elapsed time. /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut stopwatch = Stopwatch::new(); /// stopwatch.pause(); /// stopwatch.tick(Duration::from_secs_f32(1.5)); /// assert!(stopwatch.is_paused()); /// assert_eq!(stopwatch.elapsed_secs(), 0.0); /// ``` #[inline] pub fn pause(&mut self) { self.is_paused = true; } /// Unpauses the stopwatch. Resume the effect of ticking on elapsed time. /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut stopwatch = Stopwatch::new(); /// stopwatch.pause(); /// stopwatch.tick(Duration::from_secs_f32(1.0)); /// stopwatch.unpause(); /// stopwatch.tick(Duration::from_secs_f32(1.0)); /// assert!(!stopwatch.is_paused()); /// assert_eq!(stopwatch.elapsed_secs(), 1.0); /// ``` #[inline] pub fn unpause(&mut self) { self.is_paused = false; } /// Returns `true` if the stopwatch is paused. /// /// # Examples /// ``` /// # use bevy_time::*; /// let mut stopwatch = Stopwatch::new(); /// assert!(!stopwatch.is_paused()); /// stopwatch.pause(); /// assert!(stopwatch.is_paused()); /// stopwatch.unpause(); /// assert!(!stopwatch.is_paused()); /// ``` #[inline] pub fn is_paused(&self) -> bool { self.is_paused } /// Resets the stopwatch. The reset doesn't affect the paused state of the stopwatch. /// /// # Examples /// ``` /// # use bevy_time::*; /// use std::time::Duration; /// let mut stopwatch = Stopwatch::new(); /// stopwatch.tick(Duration::from_secs_f32(1.5)); /// stopwatch.reset(); /// assert_eq!(stopwatch.elapsed_secs(), 0.0); /// ``` #[inline] pub fn reset(&mut self) { self.elapsed = Default::default(); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_time/src/real.rs
crates/bevy_time/src/real.rs
use bevy_platform::time::Instant; #[cfg(feature = "bevy_reflect")] use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use core::time::Duration; use crate::time::Time; /// Real time clock representing elapsed wall clock time. /// /// A specialization of the [`Time`] structure. **For method documentation, see /// [`Time<Real>#impl-Time<Real>`].** /// /// It is automatically inserted as a resource by /// [`TimePlugin`](crate::TimePlugin) and updated with time instants according /// to [`TimeUpdateStrategy`](crate::TimeUpdateStrategy).[^disclaimer] /// /// Note: /// Using [`TimeUpdateStrategy::ManualDuration`](crate::TimeUpdateStrategy::ManualDuration) /// allows for mocking the wall clock for testing purposes. /// Besides this use case, it is not recommended to do this, as it will no longer /// represent "wall clock" time as intended. /// /// The [`delta()`](Time::delta) and [`elapsed()`](Time::elapsed) values of this /// clock should be used for anything which deals specifically with real time /// (wall clock time). It will not be affected by relative game speed /// adjustments, pausing or other adjustments.[^disclaimer] /// /// The clock does not count time from [`startup()`](Time::startup) to /// [`first_update()`](Time::first_update()) into elapsed, but instead will /// start counting time from the first update call. [`delta()`](Time::delta) and /// [`elapsed()`](Time::elapsed) will report zero on the first update as there /// is no previous update instant. This means that a [`delta()`](Time::delta) of /// zero must be handled without errors in application logic, as it may /// theoretically also happen at other times. /// /// [`Instant`]s for [`startup()`](Time::startup), /// [`first_update()`](Time::first_update) and /// [`last_update()`](Time::last_update) are recorded and accessible. /// /// [^disclaimer]: When using [`TimeUpdateStrategy::ManualDuration`](crate::TimeUpdateStrategy::ManualDuration), /// [`Time<Real>#impl-Time<Real>`] is only a *mock* of wall clock time. /// #[derive(Debug, Copy, Clone)] #[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Clone, Default))] pub struct Real { startup: Instant, first_update: Option<Instant>, last_update: Option<Instant>, } impl Default for Real { fn default() -> Self { Self { startup: Instant::now(), first_update: None, last_update: None, } } } impl Time<Real> { /// Constructs a new `Time<Real>` instance with a specific startup /// [`Instant`]. pub fn new(startup: Instant) -> Self { Self::new_with(Real { startup, ..Default::default() }) } /// Updates the internal time measurements. /// /// Calling this method as part of your app will most likely result in /// inaccurate timekeeping, as the [`Time`] resource is ordinarily managed /// by the [`TimePlugin`](crate::TimePlugin). pub fn update(&mut self) { let instant = Instant::now(); self.update_with_instant(instant); } /// Updates time with a specified [`Duration`]. /// /// This method is provided for use in tests. /// /// Calling this method as part of your app will most likely result in /// inaccurate timekeeping, as the [`Time`] resource is ordinarily managed /// by the [`TimePlugin`](crate::TimePlugin). pub fn update_with_duration(&mut self, duration: Duration) { let last_update = self.context().last_update.unwrap_or(self.context().startup); self.update_with_instant(last_update + duration); } /// Updates time with a specified [`Instant`]. /// /// This method is provided for use in tests. /// /// Calling this method as part of your app will most likely result in inaccurate timekeeping, /// as the [`Time`] resource is ordinarily managed by the [`TimePlugin`](crate::TimePlugin). pub fn update_with_instant(&mut self, instant: Instant) { let Some(last_update) = self.context().last_update else { let context = self.context_mut(); context.first_update = Some(instant); context.last_update = Some(instant); return; }; let delta = instant - last_update; self.advance_by(delta); self.context_mut().last_update = Some(instant); } /// Returns the [`Instant`] the clock was created. /// /// This usually represents when the app was started. #[inline] pub fn startup(&self) -> Instant { self.context().startup } /// Returns the [`Instant`] when [`Self::update`] was first called, if it /// exists. /// /// This usually represents when the first app update started. #[inline] pub fn first_update(&self) -> Option<Instant> { self.context().first_update } /// Returns the [`Instant`] when [`Self::update`] was last called, if it /// exists. /// /// This usually represents when the current app update started. #[inline] pub fn last_update(&self) -> Option<Instant> { self.context().last_update } } #[cfg(test)] mod test { use super::*; // Waits until Instant::now() has increased. // // ``` // let previous = Instant::now(); // wait(); // assert!(Instant::now() > previous); // ``` fn wait() { let start = Instant::now(); while Instant::now() <= start {} } #[test] fn test_update() { let startup = Instant::now(); let mut time = Time::<Real>::new(startup); assert_eq!(time.startup(), startup); assert_eq!(time.first_update(), None); assert_eq!(time.last_update(), None); assert_eq!(time.delta(), Duration::ZERO); assert_eq!(time.elapsed(), Duration::ZERO); wait(); time.update(); assert_ne!(time.first_update(), None); assert_ne!(time.last_update(), None); assert_eq!(time.delta(), Duration::ZERO); assert_eq!(time.elapsed(), Duration::ZERO); wait(); time.update(); assert_ne!(time.first_update(), None); assert_ne!(time.last_update(), None); assert_ne!(time.last_update(), time.first_update()); assert_ne!(time.delta(), Duration::ZERO); assert_eq!(time.elapsed(), time.delta()); wait(); let prev_elapsed = time.elapsed(); time.update(); assert_ne!(time.delta(), Duration::ZERO); assert_eq!(time.elapsed(), prev_elapsed + time.delta()); } #[test] fn test_update_with_instant() { let startup = Instant::now(); let mut time = Time::<Real>::new(startup); wait(); let first_update = Instant::now(); time.update_with_instant(first_update); assert_eq!(time.startup(), startup); assert_eq!(time.first_update(), Some(first_update)); assert_eq!(time.last_update(), Some(first_update)); assert_eq!(time.delta(), Duration::ZERO); assert_eq!(time.elapsed(), Duration::ZERO); wait(); let second_update = Instant::now(); time.update_with_instant(second_update); assert_eq!(time.first_update(), Some(first_update)); assert_eq!(time.last_update(), Some(second_update)); assert_eq!(time.delta(), second_update - first_update); assert_eq!(time.elapsed(), second_update - first_update); wait(); let third_update = Instant::now(); time.update_with_instant(third_update); assert_eq!(time.first_update(), Some(first_update)); assert_eq!(time.last_update(), Some(third_update)); assert_eq!(time.delta(), third_update - second_update); assert_eq!(time.elapsed(), third_update - first_update); } #[test] fn test_update_with_duration() { let startup = Instant::now(); let mut time = Time::<Real>::new(startup); time.update_with_duration(Duration::from_secs(1)); assert_eq!(time.startup(), startup); assert_eq!(time.first_update(), Some(startup + Duration::from_secs(1))); assert_eq!(time.last_update(), Some(startup + Duration::from_secs(1))); assert_eq!(time.delta(), Duration::ZERO); assert_eq!(time.elapsed(), Duration::ZERO); time.update_with_duration(Duration::from_secs(1)); assert_eq!(time.first_update(), Some(startup + Duration::from_secs(1))); assert_eq!(time.last_update(), Some(startup + Duration::from_secs(2))); assert_eq!(time.delta(), Duration::from_secs(1)); assert_eq!(time.elapsed(), Duration::from_secs(1)); time.update_with_duration(Duration::from_secs(1)); assert_eq!(time.first_update(), Some(startup + Duration::from_secs(1))); assert_eq!(time.last_update(), Some(startup + Duration::from_secs(3))); assert_eq!(time.delta(), Duration::from_secs(1)); assert_eq!(time.elapsed(), Duration::from_secs(2)); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_log/src/lib.rs
crates/bevy_log/src/lib.rs
#![cfg_attr(docsrs, feature(doc_cfg))] #![doc( html_logo_url = "https://bevy.org/assets/icon.png", html_favicon_url = "https://bevy.org/assets/icon.png" )] //! This crate provides logging functions and configuration for [Bevy](https://bevy.org) //! apps, and automatically configures platform specific log handlers (i.e. Wasm or Android). //! //! The macros provided for logging are reexported from [`tracing`](https://docs.rs/tracing), //! and behave identically to it. //! //! By default, the [`LogPlugin`] from this crate is included in Bevy's `DefaultPlugins` //! and the logging macros can be used out of the box, if used. //! //! For more fine-tuned control over logging behavior, set up the [`LogPlugin`] or //! `DefaultPlugins` during app initialization. extern crate alloc; use core::error::Error; #[cfg(target_os = "android")] mod android_tracing; mod once; #[cfg(feature = "trace_tracy_memory")] #[global_allocator] static GLOBAL: tracy_client::ProfiledAllocator<std::alloc::System> = tracy_client::ProfiledAllocator::new(std::alloc::System, 100); /// The log prelude. /// /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { #[doc(hidden)] pub use tracing::{ debug, debug_span, error, error_span, info, info_span, trace, trace_span, warn, warn_span, }; #[doc(hidden)] pub use crate::{debug_once, error_once, info_once, trace_once, warn_once}; #[doc(hidden)] pub use bevy_utils::once; } pub use bevy_utils::once; pub use tracing::{ self, debug, debug_span, error, error_span, info, info_span, trace, trace_span, warn, warn_span, Level, }; pub use tracing_subscriber; use bevy_app::{App, Plugin}; use tracing_log::LogTracer; use tracing_subscriber::{ filter::{FromEnvError, ParseError}, layer::Layered, prelude::*, registry::Registry, EnvFilter, Layer, }; #[cfg(feature = "tracing-chrome")] use { bevy_ecs::resource::Resource, bevy_platform::cell::SyncCell, tracing_subscriber::fmt::{format::DefaultFields, FormattedFields}, }; /// Wrapper resource for `tracing-chrome`'s flush guard. /// When the guard is dropped the chrome log is written to file. #[cfg(feature = "tracing-chrome")] #[expect( dead_code, reason = "`FlushGuard` never needs to be read, it just needs to be kept alive for the `App`'s lifetime." )] #[derive(Resource)] pub(crate) struct FlushGuard(SyncCell<tracing_chrome::FlushGuard>); /// Adds logging to Apps. This plugin is part of the `DefaultPlugins`. Adding /// this plugin will setup a collector appropriate to your target platform: /// * Using [`tracing-subscriber`](https://crates.io/crates/tracing-subscriber) by default, /// logging to `stdout`. /// * Using [`android_log-sys`](https://crates.io/crates/android_log-sys) on Android, /// logging to Android logs. /// * Using [`tracing-wasm`](https://crates.io/crates/tracing-wasm) in Wasm, logging /// to the browser console. /// /// You can configure this plugin. /// ```no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup}; /// # use bevy_log::LogPlugin; /// # use tracing::Level; /// fn main() { /// App::new() /// .add_plugins(DefaultPlugins.set(LogPlugin { /// level: Level::DEBUG, /// filter: "wgpu=error,bevy_render=info,bevy_ecs=trace".to_string(), /// custom_layer: |_| None, /// fmt_layer: |_| None, /// })) /// .run(); /// } /// ``` /// /// Log level can also be changed using the `RUST_LOG` environment variable. /// For example, using `RUST_LOG=wgpu=error,bevy_render=info,bevy_ecs=trace cargo run ..` /// /// It has the same syntax as the field [`LogPlugin::filter`], see [`EnvFilter`]. /// If you define the `RUST_LOG` environment variable, the [`LogPlugin`] settings /// will be ignored. /// /// Also, to disable color terminal output (ANSI escape codes), you can /// set the environment variable `NO_COLOR` to any value. This common /// convention is documented at [no-color.org](https://no-color.org/). /// For example: /// ```no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup}; /// # use bevy_log::LogPlugin; /// fn main() { /// # // SAFETY: Single-threaded /// # unsafe { /// std::env::set_var("NO_COLOR", "1"); /// # } /// App::new() /// .add_plugins(DefaultPlugins) /// .run(); /// } /// ``` /// /// If you want to setup your own tracing collector, you should disable this /// plugin from `DefaultPlugins`: /// ```no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup}; /// # use bevy_log::LogPlugin; /// fn main() { /// App::new() /// .add_plugins(DefaultPlugins.build().disable::<LogPlugin>()) /// .run(); /// } /// ``` /// # Example Setup /// /// For a quick setup that enables all first-party logging while not showing any of your dependencies' /// log data, you can configure the plugin as shown below. /// /// ```no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup}; /// # use bevy_log::*; /// App::new() /// .add_plugins(DefaultPlugins.set(LogPlugin { /// filter: "warn,my_crate=trace".to_string(), //specific filters /// level: Level::TRACE,//Change this to be globally change levels /// ..Default::default() /// })) /// .run(); /// ``` /// The filter (in this case an `EnvFilter`) chooses whether to print the log. The most specific filters apply with higher priority. /// Let's start with an example: `filter: "warn".to_string()` will only print logs with level `warn` level or greater. /// From here, we can change to `filter: "warn,my_crate=trace".to_string()`. Logs will print at level `warn` unless it's in `mycrate`, /// which will instead print at `trace` level because `my_crate=trace` is more specific. /// /// /// ## Log levels /// Events can be logged at various levels of importance. /// Only events at your configured log level and higher will be shown. /// ```no_run /// # use bevy_log::*; /// // here is how you write new logs at each "log level" (in "most important" to /// // "least important" order) /// error!("something failed"); /// warn!("something bad happened that isn't a failure, but that's worth calling out"); /// info!("helpful information that is worth printing by default"); /// debug!("helpful for debugging"); /// trace!("very noisy"); /// ``` /// In addition to `format!` style arguments, you can print a variable's debug /// value by using syntax like: `trace(?my_value)`. /// /// ## Per module logging levels /// Modules can have different logging levels using syntax like `crate_name::module_name=debug`. /// /// /// ```no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup}; /// # use bevy_log::*; /// App::new() /// .add_plugins(DefaultPlugins.set(LogPlugin { /// filter: "warn,my_crate=trace,my_crate::my_module=debug".to_string(), // Specific filters /// level: Level::TRACE, // Change this to be globally change levels /// ..Default::default() /// })) /// .run(); /// ``` /// The idea is that instead of deleting logs when they are no longer immediately applicable, /// you just disable them. If you do need to log in the future, then you can enable the logs instead of having to rewrite them. /// /// ## Further reading /// /// The `tracing` crate has much more functionality than these examples can show. /// Much of this configuration can be done with "layers" in the `log` crate. /// Check out: /// - Using spans to add more fine grained filters to logs /// - Adding instruments to capture more function information /// - Creating layers to add additional context such as line numbers /// # Panics /// /// This plugin should not be added multiple times in the same process. This plugin /// sets up global logging configuration for **all** Apps in a given process, and /// rerunning the same initialization multiple times will lead to a panic. /// /// # Performance /// /// Filters applied through this plugin are computed at _runtime_, which will /// have a non-zero impact on performance. /// To achieve maximum performance, consider using /// [_compile time_ filters](https://docs.rs/log/#compile-time-filters) /// provided by the [`log`](https://crates.io/crates/log) crate. /// /// ```toml /// # cargo.toml /// [dependencies] /// log = { version = "0.4", features = ["max_level_debug", "release_max_level_warn"] } /// ``` pub struct LogPlugin { /// Filters logs using the [`EnvFilter`] format pub filter: String, /// Filters out logs that are "less than" the given level. /// This can be further filtered using the `filter` setting. pub level: Level, /// Optionally add an extra [`Layer`] to the tracing subscriber /// /// This function is only called once, when the plugin is built. /// /// Because [`BoxedLayer`] takes a `dyn Layer`, `Vec<Layer>` is also an acceptable return value. /// /// Access to [`App`] is also provided to allow for communication between the /// [`Subscriber`](tracing::Subscriber) and the [`App`]. /// /// Please see the `examples/app/log_layers.rs` for a complete example. pub custom_layer: fn(app: &mut App) -> Option<BoxedLayer>, /// Override the default [`tracing_subscriber::fmt::Layer`] with a custom one. /// /// This differs from [`custom_layer`](Self::custom_layer) in that /// [`fmt_layer`](Self::fmt_layer) allows you to overwrite the default formatter layer, while /// `custom_layer` only allows you to add additional layers (which are unable to modify the /// default formatter). /// /// For example, you can use [`tracing_subscriber::fmt::Layer::without_time`] to remove the /// timestamp from the log output. /// /// Please see the `examples/app/log_layers.rs` for a complete example. pub fmt_layer: fn(app: &mut App) -> Option<BoxedFmtLayer>, } /// A boxed [`Layer`] that can be used with [`LogPlugin::custom_layer`]. pub type BoxedLayer = Box<dyn Layer<Registry> + Send + Sync + 'static>; #[cfg(feature = "trace")] type BaseSubscriber = Layered<EnvFilter, Layered<Option<Box<dyn Layer<Registry> + Send + Sync>>, Registry>>; #[cfg(feature = "trace")] type PreFmtSubscriber = Layered<tracing_error::ErrorLayer<BaseSubscriber>, BaseSubscriber>; #[cfg(not(feature = "trace"))] type PreFmtSubscriber = Layered<EnvFilter, Layered<Option<Box<dyn Layer<Registry> + Send + Sync>>, Registry>>; /// A boxed [`Layer`] that can be used with [`LogPlugin::fmt_layer`]. pub type BoxedFmtLayer = Box<dyn Layer<PreFmtSubscriber> + Send + Sync + 'static>; /// The default [`LogPlugin`] [`EnvFilter`]. pub const DEFAULT_FILTER: &str = concat!( "wgpu=error,", "naga=warn,", "symphonia_bundle_mp3::demuxer=warn,", "symphonia_format_caf::demuxer=warn,", "symphonia_format_isompf4::demuxer=warn,", "symphonia_format_mkv::demuxer=warn,", "symphonia_format_ogg::demuxer=warn,", "symphonia_format_riff::demuxer=warn,", "symphonia_format_wav::demuxer=warn,", "calloop::loop_logic=error,", ); impl Default for LogPlugin { fn default() -> Self { Self { filter: DEFAULT_FILTER.to_string(), level: Level::INFO, custom_layer: |_| None, fmt_layer: |_| None, } } } impl Plugin for LogPlugin { #[expect(clippy::print_stderr, reason = "Allowed during logger setup")] fn build(&self, app: &mut App) { #[cfg(feature = "trace")] { let old_handler = std::panic::take_hook(); std::panic::set_hook(Box::new(move |infos| { eprintln!("{}", tracing_error::SpanTrace::capture()); old_handler(infos); })); } let finished_subscriber; let subscriber = Registry::default(); // add optional layer provided by user let subscriber = subscriber.with((self.custom_layer)(app)); let default_filter = { format!("{},{}", self.level, self.filter) }; let filter_layer = EnvFilter::try_from_default_env() .or_else(|from_env_error| { _ = from_env_error .source() .and_then(|source| source.downcast_ref::<ParseError>()) .map(|parse_err| { // we cannot use the `error!` macro here because the logger is not ready yet. eprintln!("LogPlugin failed to parse filter from env: {parse_err}"); }); Ok::<EnvFilter, FromEnvError>(EnvFilter::builder().parse_lossy(&default_filter)) }) .unwrap(); let subscriber = subscriber.with(filter_layer); #[cfg(feature = "trace")] let subscriber = subscriber.with(tracing_error::ErrorLayer::default()); #[cfg(all(not(target_arch = "wasm32"), not(target_os = "ios")))] { #[cfg(all(feature = "tracing-chrome", not(target_os = "android")))] let chrome_layer = { let mut layer = tracing_chrome::ChromeLayerBuilder::new(); if let Ok(path) = std::env::var("TRACE_CHROME") { layer = layer.file(path); } let (chrome_layer, guard) = layer .name_fn(Box::new(|event_or_span| match event_or_span { tracing_chrome::EventOrSpan::Event(event) => event.metadata().name().into(), tracing_chrome::EventOrSpan::Span(span) => { if let Some(fields) = span.extensions().get::<FormattedFields<DefaultFields>>() { format!("{}: {}", span.metadata().name(), fields.fields.as_str()) } else { span.metadata().name().into() } } })) .build(); app.insert_resource(FlushGuard(SyncCell::new(guard))); chrome_layer }; #[cfg(feature = "tracing-tracy")] let tracy_layer = tracing_tracy::TracyLayer::default(); let fmt_layer = (self.fmt_layer)(app).unwrap_or_else(|| { // note: the implementation of `Default` reads from the env var NO_COLOR // to decide whether to use ANSI color codes, which is common convention // https://no-color.org/ Box::new(tracing_subscriber::fmt::Layer::default().with_writer(std::io::stderr)) }); // bevy_render::renderer logs a `tracy.frame_mark` event every frame // at Level::INFO. Formatted logs should omit it. #[cfg(feature = "tracing-tracy")] let fmt_layer = fmt_layer.with_filter(tracing_subscriber::filter::FilterFn::new(|meta| { meta.fields().field("tracy.frame_mark").is_none() })); let subscriber = subscriber.with(fmt_layer); #[cfg(all(feature = "tracing-chrome", not(target_os = "android")))] let subscriber = subscriber.with(chrome_layer); #[cfg(feature = "tracing-tracy")] let subscriber = subscriber.with(tracy_layer); #[cfg(target_os = "android")] let subscriber = subscriber.with(android_tracing::AndroidLayer::default()); finished_subscriber = subscriber; } #[cfg(target_arch = "wasm32")] { finished_subscriber = subscriber.with(tracing_wasm::WASMLayer::new( tracing_wasm::WASMLayerConfig::default(), )); } #[cfg(target_os = "ios")] { finished_subscriber = subscriber.with(tracing_oslog::OsLogger::default()); } let logger_already_set = LogTracer::init().is_err(); let subscriber_already_set = tracing::subscriber::set_global_default(finished_subscriber).is_err(); #[cfg(feature = "tracing-tracy")] warn!("Tracing with Tracy is active, memory consumption will grow until a client is connected"); match (logger_already_set, subscriber_already_set) { (true, true) => error!( "Could not set global logger and tracing subscriber as they are already set. Consider disabling LogPlugin." ), (true, false) => error!("Could not set global logger as it is already set. Consider disabling LogPlugin."), (false, true) => error!("Could not set global tracing subscriber as it is already set. Consider disabling LogPlugin."), (false, false) => (), } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_log/src/once.rs
crates/bevy_log/src/once.rs
/// Call [`trace!`](crate::trace) once per call site. /// /// Useful for logging within systems which are called every frame. #[macro_export] macro_rules! trace_once { ($($arg:tt)+) => ({ $crate::once!($crate::trace!($($arg)+)) }); } /// Call [`debug!`](crate::debug) once per call site. /// /// Useful for logging within systems which are called every frame. #[macro_export] macro_rules! debug_once { ($($arg:tt)+) => ({ $crate::once!($crate::debug!($($arg)+)) }); } /// Call [`info!`](crate::info) once per call site. /// /// Useful for logging within systems which are called every frame. #[macro_export] macro_rules! info_once { ($($arg:tt)+) => ({ $crate::once!($crate::info!($($arg)+)) }); } /// Call [`warn!`](crate::warn) once per call site. /// /// Useful for logging within systems which are called every frame. #[macro_export] macro_rules! warn_once { ($($arg:tt)+) => ({ $crate::once!($crate::warn!($($arg)+)) }); } /// Call [`error!`](crate::error) once per call site. /// /// Useful for logging within systems which are called every frame. #[macro_export] macro_rules! error_once { ($($arg:tt)+) => ({ $crate::once!($crate::error!($($arg)+)) }); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_log/src/android_tracing.rs
crates/bevy_log/src/android_tracing.rs
use alloc::ffi::CString; use core::fmt::{Debug, Write}; use tracing::{ field::Field, span::{Attributes, Record}, Event, Id, Level, Subscriber, }; use tracing_subscriber::{field::Visit, layer::Context, registry::LookupSpan, Layer}; #[derive(Default)] pub(crate) struct AndroidLayer; struct StringRecorder(String, bool); impl StringRecorder { fn new() -> Self { StringRecorder(String::new(), false) } } impl Visit for StringRecorder { fn record_debug(&mut self, field: &Field, value: &dyn Debug) { if field.name() == "message" { if !self.0.is_empty() { self.0 = format!("{:?}\n{}", value, self.0) } else { self.0 = format!("{:?}", value) } } else { if self.1 { // following args write!(self.0, " ").unwrap(); } else { // first arg self.1 = true; } write!(self.0, "{} = {:?};", field.name(), value).unwrap(); } } } impl Default for StringRecorder { fn default() -> Self { StringRecorder::new() } } impl<S: Subscriber + for<'a> LookupSpan<'a>> Layer<S> for AndroidLayer { fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) { let mut new_debug_record = StringRecorder::new(); attrs.record(&mut new_debug_record); if let Some(span_ref) = ctx.span(id) { span_ref .extensions_mut() .insert::<StringRecorder>(new_debug_record); } } fn on_record(&self, id: &Id, values: &Record<'_>, ctx: Context<'_, S>) { if let Some(span_ref) = ctx.span(id) { if let Some(debug_record) = span_ref.extensions_mut().get_mut::<StringRecorder>() { values.record(debug_record); } } } #[allow(unsafe_code)] fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) { fn sanitize(string: &str) -> CString { let bytes: Vec<u8> = string .as_bytes() .into_iter() .copied() .filter(|byte| *byte != 0) .collect(); CString::new(bytes).unwrap() } let mut recorder = StringRecorder::new(); event.record(&mut recorder); let meta = event.metadata(); let priority = match *meta.level() { Level::TRACE => android_log_sys::LogPriority::VERBOSE, Level::DEBUG => android_log_sys::LogPriority::DEBUG, Level::INFO => android_log_sys::LogPriority::INFO, Level::WARN => android_log_sys::LogPriority::WARN, Level::ERROR => android_log_sys::LogPriority::ERROR, }; // SAFETY: Called only on Android platforms. priority is guaranteed to be in range of c_int. // The provided tag and message are null terminated properly. unsafe { android_log_sys::__android_log_write( priority as android_log_sys::c_int, sanitize(meta.name()).as_ptr(), sanitize(&recorder.0).as_ptr(), ); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_text/src/glyph.rs
crates/bevy_text/src/glyph.rs
//! This module exports types related to rendering glyphs. use bevy_asset::AssetId; use bevy_image::prelude::*; use bevy_math::{IVec2, Vec2}; use bevy_reflect::Reflect; /// A glyph of a font, typically representing a single character, positioned in screen space. /// /// Contains information about how and where to render a glyph. /// /// Used in [`TextPipeline::update_text_layout_info`](crate::TextPipeline::update_text_layout_info) and [`TextLayoutInfo`](`crate::TextLayoutInfo`) for rendering glyphs. #[derive(Debug, Clone, Reflect)] #[reflect(Clone)] pub struct PositionedGlyph { /// The position of the glyph in the text block's bounding box. pub position: Vec2, /// The width and height of the glyph in logical pixels. pub size: Vec2, /// Information about the glyph's atlas. pub atlas_info: GlyphAtlasInfo, /// The index of the glyph in the [`ComputedTextBlock`](crate::ComputedTextBlock)'s tracked spans. pub span_index: usize, /// The index of the glyph's line. pub line_index: usize, /// The byte index of the glyph in its line. pub byte_index: usize, /// The byte length of the glyph. pub byte_length: usize, } /// Information about a glyph in an atlas. /// /// Rasterized glyphs are stored as rectangles /// in one or more [`FontAtlas`](crate::FontAtlas)es. /// /// Used in [`PositionedGlyph`] and [`FontAtlasSet`](crate::FontAtlasSet). #[derive(Debug, Clone, Reflect)] #[reflect(Clone)] pub struct GlyphAtlasInfo { /// An asset ID to the [`Image`] data for the texture atlas this glyph was placed in. /// /// An asset ID of the handle held by the [`FontAtlas`](crate::FontAtlas). pub texture: AssetId<Image>, /// An asset ID to the [`TextureAtlasLayout`] map for the texture atlas this glyph was placed /// in. /// /// An asset ID of the handle held by the [`FontAtlas`](crate::FontAtlas). pub texture_atlas: AssetId<TextureAtlasLayout>, /// Location and offset of a glyph within the texture atlas. pub location: GlyphAtlasLocation, } /// The location of a glyph in an atlas, /// and how it should be positioned when placed. /// /// Used in [`GlyphAtlasInfo`] and [`FontAtlas`](crate::FontAtlas). #[derive(Debug, Clone, Copy, Reflect)] #[reflect(Clone)] pub struct GlyphAtlasLocation { /// The index of the glyph in the atlas pub glyph_index: usize, /// The required offset (relative positioning) when placed pub offset: IVec2, }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_text/src/font_loader.rs
crates/bevy_text/src/font_loader.rs
use crate::Font; use bevy_asset::{io::Reader, AssetLoader, LoadContext}; use bevy_reflect::TypePath; use cosmic_text::skrifa::raw::ReadError; use thiserror::Error; #[derive(Default, TypePath)] /// An [`AssetLoader`] for [`Font`]s, for use by the [`AssetServer`](bevy_asset::AssetServer) pub struct FontLoader; /// Possible errors that can be produced by [`FontLoader`] #[non_exhaustive] #[derive(Debug, Error)] pub enum FontLoaderError { /// The contents that could not be parsed #[error(transparent)] Content(#[from] ReadError), /// An [IO](std::io) Error #[error(transparent)] Io(#[from] std::io::Error), } impl AssetLoader for FontLoader { type Asset = Font; type Settings = (); type Error = FontLoaderError; async fn load( &self, reader: &mut dyn Reader, _settings: &(), _load_context: &mut LoadContext<'_>, ) -> Result<Font, Self::Error> { let mut bytes = Vec::new(); reader.read_to_end(&mut bytes).await?; let font = Font::try_from_bytes(bytes)?; Ok(font) } fn extensions(&self) -> &[&str] { &["ttf", "otf"] } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_text/src/lib.rs
crates/bevy_text/src/lib.rs
//! This crate provides the tools for positioning and rendering text in Bevy. //! //! # `Font` //! //! Fonts contain information for drawing glyphs, which are shapes that typically represent a single character, //! but in some cases part of a "character" (grapheme clusters) or more than one character (ligatures). //! //! A font *face* is part of a font family, //! and is distinguished by its style (e.g. italic), its weight (e.g. bold) and its stretch (e.g. condensed). //! //! In Bevy, [`Font`]s are loaded by the [`FontLoader`] as [assets](bevy_asset::AssetPlugin). //! //! # `TextPipeline` //! //! The [`TextPipeline`] resource does all of the heavy lifting for rendering text. //! //! UI `Text` is first measured by creating a [`TextMeasureInfo`] in [`TextPipeline::create_text_measure`], //! which is called by the `measure_text_system` system of `bevy_ui`. //! //! Note that text measurement is only relevant in a UI context. //! //! With the actual text bounds defined, the `bevy_ui::widget::text::text_system` system (in a UI context) //! or `bevy_sprite::text2d::update_text2d_layout` system (in a 2d world space context) //! passes it into [`TextPipeline::update_text_layout_info`], which: //! //! 1. updates a [`Buffer`](cosmic_text::Buffer) from the [`TextSpan`]s, generating new [`FontAtlas`]es if necessary. //! 2. iterates over each glyph in the [`Buffer`](cosmic_text::Buffer) to create a [`PositionedGlyph`], //! retrieving glyphs from the cache, or rasterizing to a [`FontAtlas`] if necessary. //! 3. [`PositionedGlyph`]s are stored in a [`TextLayoutInfo`], //! which contains all the information that downstream systems need for rendering. extern crate alloc; mod bounds; mod error; mod font; mod font_atlas; mod font_atlas_set; mod font_loader; mod glyph; mod pipeline; mod text; mod text_access; use bevy_asset::AssetEventSystems; pub use bounds::*; pub use error::*; pub use font::*; pub use font_atlas::*; pub use font_atlas_set::*; pub use font_loader::*; pub use glyph::*; pub use pipeline::*; pub use text::*; pub use text_access::*; /// The text prelude. /// /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { #[doc(hidden)] pub use crate::{ Font, FontHinting, FontSource, FontStyle, FontWeight, FontWidth, Justify, LineBreak, Strikethrough, StrikethroughColor, TextColor, TextError, TextFont, TextLayout, TextSpan, Underline, UnderlineColor, }; } use bevy_app::prelude::*; use bevy_asset::AssetApp; use bevy_ecs::prelude::*; /// The raw data for the default font used by `bevy_text` #[cfg(feature = "default_font")] pub const DEFAULT_FONT_DATA: &[u8] = include_bytes!("FiraMono-subset.ttf"); /// Adds text rendering support to an app. /// /// When the `bevy_text` feature is enabled with the `bevy` crate, this /// plugin is included by default in the `DefaultPlugins`. #[derive(Default)] pub struct TextPlugin; /// System set in [`PostUpdate`] where all 2d text update systems are executed. #[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)] pub struct Text2dUpdateSystems; impl Plugin for TextPlugin { fn build(&self, app: &mut App) { app.init_asset::<Font>() .init_asset_loader::<FontLoader>() .init_resource::<FontAtlasSet>() .init_resource::<TextPipeline>() .init_resource::<CosmicFontSystem>() .init_resource::<SwashCache>() .init_resource::<TextIterScratch>() .add_systems( PostUpdate, load_font_assets_into_fontdb_system.after(AssetEventSystems), ) .add_systems(Last, trim_cosmic_cache); #[cfg(feature = "default_font")] { use bevy_asset::{AssetId, Assets}; let mut assets = app.world_mut().resource_mut::<Assets<_>>(); let asset = Font::try_from_bytes(DEFAULT_FONT_DATA.to_vec()).unwrap(); assets.insert(AssetId::default(), asset).unwrap(); }; } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_text/src/font_atlas.rs
crates/bevy_text/src/font_atlas.rs
use bevy_asset::{Assets, Handle, RenderAssetUsages}; use bevy_image::{prelude::*, ImageSampler, ToExtents}; use bevy_math::{IVec2, UVec2}; use bevy_platform::collections::HashMap; use wgpu_types::{Extent3d, TextureDimension, TextureFormat}; use crate::{FontSmoothing, GlyphAtlasInfo, GlyphAtlasLocation, TextError}; /// Rasterized glyphs are cached, stored in, and retrieved from, a `FontAtlas`. /// /// A `FontAtlas` contains one or more textures, each of which contains one or more glyphs packed into them. /// /// A [`FontAtlasSet`](crate::FontAtlasSet) contains a `FontAtlas` for each font size in the same font face. /// /// For the same font face and font size, a glyph will be rasterized differently for different subpixel offsets. /// In practice, ranges of subpixel offsets are grouped into subpixel bins to limit the number of rasterized glyphs, /// providing a trade-off between visual quality and performance. /// /// A [`CacheKey`](cosmic_text::CacheKey) encodes all of the information of a subpixel-offset glyph and is used to /// find that glyphs raster in a [`TextureAtlas`] through its corresponding [`GlyphAtlasLocation`]. pub struct FontAtlas { /// Used to update the [`TextureAtlasLayout`]. pub dynamic_texture_atlas_builder: DynamicTextureAtlasBuilder, /// A mapping between subpixel-offset glyphs and their [`GlyphAtlasLocation`]. pub glyph_to_atlas_index: HashMap<cosmic_text::CacheKey, GlyphAtlasLocation>, /// The handle to the [`TextureAtlasLayout`] that holds the rasterized glyphs. pub texture_atlas: Handle<TextureAtlasLayout>, /// The texture where this font atlas is located pub texture: Handle<Image>, } impl FontAtlas { /// Create a new [`FontAtlas`] with the given size, adding it to the appropriate asset collections. pub fn new( textures: &mut Assets<Image>, texture_atlases_layout: &mut Assets<TextureAtlasLayout>, size: UVec2, font_smoothing: FontSmoothing, ) -> FontAtlas { let mut image = Image::new_fill( size.to_extents(), TextureDimension::D2, &[0, 0, 0, 0], TextureFormat::Rgba8UnormSrgb, // Need to keep this image CPU persistent in order to add additional glyphs later on RenderAssetUsages::MAIN_WORLD | RenderAssetUsages::RENDER_WORLD, ); if font_smoothing == FontSmoothing::None { image.sampler = ImageSampler::nearest(); } let texture = textures.add(image); let texture_atlas = texture_atlases_layout.add(TextureAtlasLayout::new_empty(size)); Self { texture_atlas, glyph_to_atlas_index: HashMap::default(), dynamic_texture_atlas_builder: DynamicTextureAtlasBuilder::new(size, 1), texture, } } /// Get the [`GlyphAtlasLocation`] for a subpixel-offset glyph. pub fn get_glyph_index(&self, cache_key: cosmic_text::CacheKey) -> Option<GlyphAtlasLocation> { self.glyph_to_atlas_index.get(&cache_key).copied() } /// Checks if the given subpixel-offset glyph is contained in this [`FontAtlas`]. pub fn has_glyph(&self, cache_key: cosmic_text::CacheKey) -> bool { self.glyph_to_atlas_index.contains_key(&cache_key) } /// Add a glyph to the atlas, updating both its texture and layout. /// /// The glyph is represented by `glyph`, and its image content is `glyph_texture`. /// This content is copied into the atlas texture, and the atlas layout is updated /// to store the location of that glyph into the atlas. /// /// # Returns /// /// Returns `()` if the glyph is successfully added, or [`TextError::FailedToAddGlyph`] otherwise. /// In that case, neither the atlas texture nor the atlas layout are /// modified. pub fn add_glyph( &mut self, textures: &mut Assets<Image>, atlas_layouts: &mut Assets<TextureAtlasLayout>, cache_key: cosmic_text::CacheKey, texture: &Image, offset: IVec2, ) -> Result<(), TextError> { let atlas_layout = atlas_layouts .get_mut(&self.texture_atlas) .ok_or(TextError::MissingAtlasLayout)?; let atlas_texture = textures .get_mut(&self.texture) .ok_or(TextError::MissingAtlasTexture)?; if let Ok(glyph_index) = self.dynamic_texture_atlas_builder .add_texture(atlas_layout, texture, atlas_texture) { self.glyph_to_atlas_index.insert( cache_key, GlyphAtlasLocation { glyph_index, offset, }, ); Ok(()) } else { Err(TextError::FailedToAddGlyph(cache_key.glyph_id)) } } } impl core::fmt::Debug for FontAtlas { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("FontAtlas") .field("glyph_to_atlas_index", &self.glyph_to_atlas_index) .field("texture_atlas", &self.texture_atlas) .field("texture", &self.texture) .field("dynamic_texture_atlas_builder", &"[...]") .finish() } } /// Adds the given subpixel-offset glyph to the given font atlases pub fn add_glyph_to_atlas( font_atlases: &mut Vec<FontAtlas>, texture_atlases: &mut Assets<TextureAtlasLayout>, textures: &mut Assets<Image>, font_system: &mut cosmic_text::FontSystem, swash_cache: &mut cosmic_text::SwashCache, layout_glyph: &cosmic_text::LayoutGlyph, font_smoothing: FontSmoothing, ) -> Result<GlyphAtlasInfo, TextError> { let physical_glyph = layout_glyph.physical((0., 0.), 1.0); let (glyph_texture, offset) = get_outlined_glyph_texture(font_system, swash_cache, &physical_glyph, font_smoothing)?; let mut add_char_to_font_atlas = |atlas: &mut FontAtlas| -> Result<(), TextError> { atlas.add_glyph( textures, texture_atlases, physical_glyph.cache_key, &glyph_texture, offset, ) }; if !font_atlases .iter_mut() .any(|atlas| add_char_to_font_atlas(atlas).is_ok()) { // Find the largest dimension of the glyph, either its width or its height let glyph_max_size: u32 = glyph_texture .texture_descriptor .size .height .max(glyph_texture.width()); // Pick the higher of 512 or the smallest power of 2 greater than glyph_max_size let containing = (1u32 << (32 - glyph_max_size.leading_zeros())).max(512); let mut new_atlas = FontAtlas::new( textures, texture_atlases, UVec2::splat(containing), font_smoothing, ); new_atlas.add_glyph( textures, texture_atlases, physical_glyph.cache_key, &glyph_texture, offset, )?; font_atlases.push(new_atlas); } get_glyph_atlas_info(font_atlases, physical_glyph.cache_key) .ok_or(TextError::InconsistentAtlasState) } /// Get the texture of the glyph as a rendered image, and its offset pub fn get_outlined_glyph_texture( font_system: &mut cosmic_text::FontSystem, swash_cache: &mut cosmic_text::SwashCache, physical_glyph: &cosmic_text::PhysicalGlyph, font_smoothing: FontSmoothing, ) -> Result<(Image, IVec2), TextError> { // NOTE: Ideally, we'd ask COSMIC Text to honor the font smoothing setting directly. // However, since it currently doesn't support that, we render the glyph with antialiasing // and apply a threshold to the alpha channel to simulate the effect. // // This has the side effect of making regular vector fonts look quite ugly when font smoothing // is turned off, but for fonts that are specifically designed for pixel art, it works well. // // See: https://github.com/pop-os/cosmic-text/issues/279 let image = swash_cache .get_image_uncached(font_system, physical_glyph.cache_key) .ok_or(TextError::FailedToGetGlyphImage(physical_glyph.cache_key))?; let cosmic_text::Placement { left, top, width, height, } = image.placement; let data = match image.content { cosmic_text::SwashContent::Mask => { if font_smoothing == FontSmoothing::None { image .data .iter() // Apply a 50% threshold to the alpha channel .flat_map(|a| [255, 255, 255, if *a > 127 { 255 } else { 0 }]) .collect() } else { image .data .iter() .flat_map(|a| [255, 255, 255, *a]) .collect() } } cosmic_text::SwashContent::Color => image.data, cosmic_text::SwashContent::SubpixelMask => { // TODO: implement todo!() } }; Ok(( Image::new( Extent3d { width, height, depth_or_array_layers: 1, }, TextureDimension::D2, data, TextureFormat::Rgba8UnormSrgb, RenderAssetUsages::MAIN_WORLD, ), IVec2::new(left, top), )) } /// Generates the [`GlyphAtlasInfo`] for the given subpixel-offset glyph. pub fn get_glyph_atlas_info( font_atlases: &mut [FontAtlas], cache_key: cosmic_text::CacheKey, ) -> Option<GlyphAtlasInfo> { font_atlases.iter().find_map(|atlas| { atlas .get_glyph_index(cache_key) .map(|location| GlyphAtlasInfo { location, texture_atlas: atlas.texture_atlas.id(), texture: atlas.texture.id(), }) }) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_text/src/bounds.rs
crates/bevy_text/src/bounds.rs
use bevy_ecs::{component::Component, reflect::ReflectComponent}; use bevy_math::Vec2; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; /// The maximum width and height of text. The text will wrap according to the specified size. /// /// Characters out of the bounds after wrapping will be truncated. Text is aligned according to the /// specified [`Justify`](crate::text::Justify). /// /// Note: only characters that are completely out of the bounds will be truncated, so this is not a /// reliable limit if it is necessary to contain the text strictly in the bounds. Currently this /// component is mainly useful for text wrapping only. #[derive(Component, Copy, Clone, Debug, Reflect)] #[reflect(Component, Default, Debug, Clone)] pub struct TextBounds { /// The maximum width of text in logical pixels. /// If `None`, the width is unbounded. pub width: Option<f32>, /// The maximum height of text in logical pixels. /// If `None`, the height is unbounded. pub height: Option<f32>, } impl Default for TextBounds { #[inline] fn default() -> Self { Self::UNBOUNDED } } impl TextBounds { /// Unbounded text will not be truncated or wrapped. pub const UNBOUNDED: Self = Self { width: None, height: None, }; /// Creates a new `TextBounds`, bounded with the specified width and height values. #[inline] pub const fn new(width: f32, height: f32) -> Self { Self { width: Some(width), height: Some(height), } } /// Creates a new `TextBounds`, bounded with the specified width value and unbounded on height. #[inline] pub const fn new_horizontal(width: f32) -> Self { Self { width: Some(width), height: None, } } /// Creates a new `TextBounds`, bounded with the specified height value and unbounded on width. #[inline] pub const fn new_vertical(height: f32) -> Self { Self { width: None, height: Some(height), } } } impl From<Vec2> for TextBounds { #[inline] fn from(v: Vec2) -> Self { Self::new(v.x, v.y) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_text/src/text.rs
crates/bevy_text/src/text.rs
use crate::{Font, TextLayoutInfo, TextSpanAccess, TextSpanComponent}; use bevy_asset::Handle; use bevy_color::Color; use bevy_derive::{Deref, DerefMut}; use bevy_ecs::{prelude::*, reflect::ReflectComponent}; use bevy_reflect::prelude::*; use bevy_utils::{default, once}; use core::fmt::{Debug, Formatter}; use core::str::from_utf8; use cosmic_text::{Buffer, Metrics, Stretch}; use serde::{Deserialize, Serialize}; use smallvec::SmallVec; use smol_str::SmolStr; use tracing::warn; /// Wrapper for [`cosmic_text::Buffer`] #[derive(Deref, DerefMut, Debug, Clone)] pub struct CosmicBuffer(pub Buffer); impl Default for CosmicBuffer { fn default() -> Self { Self(Buffer::new_empty(Metrics::new(20.0, 20.0))) } } /// A sub-entity of a [`ComputedTextBlock`]. /// /// Returned by [`ComputedTextBlock::entities`]. #[derive(Debug, Copy, Clone, Reflect)] #[reflect(Debug, Clone)] pub struct TextEntity { /// The entity. pub entity: Entity, /// Records the hierarchy depth of the entity within a `TextLayout`. pub depth: usize, } /// Computed information for a text block. /// /// See [`TextLayout`]. /// /// Automatically updated by 2d and UI text systems. #[derive(Component, Debug, Clone, Reflect)] #[reflect(Component, Debug, Default, Clone)] pub struct ComputedTextBlock { /// Buffer for managing text layout and creating [`TextLayoutInfo`]. /// /// This is private because buffer contents are always refreshed from ECS state when writing glyphs to /// `TextLayoutInfo`. If you want to control the buffer contents manually or use the `cosmic-text` /// editor, then you need to not use `TextLayout` and instead manually implement the conversion to /// `TextLayoutInfo`. #[reflect(ignore, clone)] pub(crate) buffer: CosmicBuffer, /// Entities for all text spans in the block, including the root-level text. /// /// The [`TextEntity::depth`] field can be used to reconstruct the hierarchy. pub(crate) entities: SmallVec<[TextEntity; 1]>, /// Flag set when any change has been made to this block that should cause it to be rerendered. /// /// Includes: /// - [`TextLayout`] changes. /// - [`TextFont`] or `Text2d`/`Text`/`TextSpan` changes anywhere in the block's entity hierarchy. // TODO: This encompasses both structural changes like font size or justification and non-structural // changes like text color and font smoothing. This field currently causes UI to 'remeasure' text, even if // the actual changes are non-structural and can be handled by only rerendering and not remeasuring. A full // solution would probably require splitting TextLayout and TextFont into structural/non-structural // components for more granular change detection. A cost/benefit analysis is needed. pub(crate) needs_rerender: bool, } impl ComputedTextBlock { /// Accesses entities in this block. /// /// Can be used to look up [`TextFont`] components for glyphs in [`TextLayoutInfo`] using the `span_index` /// stored there. pub fn entities(&self) -> &[TextEntity] { &self.entities } /// Indicates if the text needs to be refreshed in [`TextLayoutInfo`]. /// /// Updated automatically by [`detect_text_needs_rerender`] and cleared /// by [`TextPipeline`](crate::TextPipeline) methods. pub fn needs_rerender(&self) -> bool { self.needs_rerender } /// Accesses the underlying buffer which can be used for `cosmic-text` APIs such as accessing layout information /// or calculating a cursor position. /// /// Mutable access is not offered because changes would be overwritten during the automated layout calculation. /// If you want to control the buffer contents manually or use the `cosmic-text` /// editor, then you need to not use `TextLayout` and instead manually implement the conversion to /// `TextLayoutInfo`. pub fn buffer(&self) -> &CosmicBuffer { &self.buffer } } impl Default for ComputedTextBlock { fn default() -> Self { Self { buffer: CosmicBuffer::default(), entities: SmallVec::default(), needs_rerender: true, } } } /// Component with text format settings for a block of text. /// /// A block of text is composed of text spans, which each have a separate string value and [`TextFont`]. Text /// spans associated with a text block are collected into [`ComputedTextBlock`] for layout, and then inserted /// to [`TextLayoutInfo`] for rendering. /// /// See `Text2d` in `bevy_sprite` for the core component of 2d text, and `Text` in `bevy_ui` for UI text. #[derive(Component, Debug, Copy, Clone, Default, Reflect)] #[reflect(Component, Default, Debug, Clone)] #[require(ComputedTextBlock, TextLayoutInfo)] pub struct TextLayout { /// The text's internal alignment. /// Should not affect its position within a container. pub justify: Justify, /// How the text should linebreak when running out of the bounds determined by `max_size`. pub linebreak: LineBreak, } impl TextLayout { /// Makes a new [`TextLayout`]. pub const fn new(justify: Justify, linebreak: LineBreak) -> Self { Self { justify, linebreak } } /// Makes a new [`TextLayout`] with the specified [`Justify`]. pub fn new_with_justify(justify: Justify) -> Self { Self::default().with_justify(justify) } /// Makes a new [`TextLayout`] with the specified [`LineBreak`]. pub fn new_with_linebreak(linebreak: LineBreak) -> Self { Self::default().with_linebreak(linebreak) } /// Makes a new [`TextLayout`] with soft wrapping disabled. /// Hard wrapping, where text contains an explicit linebreak such as the escape sequence `\n`, will still occur. pub fn new_with_no_wrap() -> Self { Self::default().with_no_wrap() } /// Returns this [`TextLayout`] with the specified [`Justify`]. pub const fn with_justify(mut self, justify: Justify) -> Self { self.justify = justify; self } /// Returns this [`TextLayout`] with the specified [`LineBreak`]. pub const fn with_linebreak(mut self, linebreak: LineBreak) -> Self { self.linebreak = linebreak; self } /// Returns this [`TextLayout`] with soft wrapping disabled. /// Hard wrapping, where text contains an explicit linebreak such as the escape sequence `\n`, will still occur. pub const fn with_no_wrap(mut self) -> Self { self.linebreak = LineBreak::NoWrap; self } } /// A span of text in a tree of spans. /// /// A `TextSpan` is only valid when it exists as a child of a parent that has either `Text` or /// `Text2d`. The parent's `Text` / `Text2d` component contains the base text content. Any children /// with `TextSpan` extend this text by appending their content to the parent's text in sequence to /// form a [`ComputedTextBlock`]. The parent's [`TextLayout`] determines the layout of the block /// but each node has its own [`TextFont`] and [`TextColor`]. #[derive(Component, Debug, Default, Clone, Deref, DerefMut, Reflect)] #[reflect(Component, Default, Debug, Clone)] #[require(TextFont, TextColor, LineHeight)] pub struct TextSpan(pub String); impl TextSpan { /// Makes a new text span component. pub fn new(text: impl Into<String>) -> Self { Self(text.into()) } } impl TextSpanComponent for TextSpan {} impl TextSpanAccess for TextSpan { fn read_span(&self) -> &str { self.as_str() } fn write_span(&mut self) -> &mut String { &mut *self } } impl From<&str> for TextSpan { fn from(value: &str) -> Self { Self(String::from(value)) } } impl From<String> for TextSpan { fn from(value: String) -> Self { Self(value) } } /// Describes the horizontal alignment of multiple lines of text relative to each other. /// /// This only affects the internal positioning of the lines of text within a text entity and /// does not affect the text entity's position. /// /// _Has no affect on a single line text entity_, unless used together with a /// [`TextBounds`](super::bounds::TextBounds) component with an explicit `width` value. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)] #[reflect(Serialize, Deserialize, Clone, PartialEq, Hash)] #[doc(alias = "JustifyText")] pub enum Justify { /// Leftmost character is immediately to the right of the render position. /// Bounds start from the render position and advance rightwards. #[default] Left, /// Leftmost & rightmost characters are equidistant to the render position. /// Bounds start from the render position and advance equally left & right. Center, /// Rightmost character is immediately to the left of the render position. /// Bounds start from the render position and advance leftwards. Right, /// Words are spaced so that leftmost & rightmost characters /// align with their margins. /// Bounds start from the render position and advance equally left & right. Justified, } impl From<Justify> for cosmic_text::Align { fn from(justify: Justify) -> Self { match justify { Justify::Left => cosmic_text::Align::Left, Justify::Center => cosmic_text::Align::Center, Justify::Right => cosmic_text::Align::Right, Justify::Justified => cosmic_text::Align::Justified, } } } #[derive(Component, Clone, Debug, Reflect, PartialEq)] /// Specifies how the font face for a text span is sourced. /// /// A `FontSource` can either reference a font asset or identify a font by family name to be /// resolved by the font systems. pub enum FontSource { /// Use a specific font face referenced by a [`Font`] asset handle. /// /// If the default font handle is used, then /// * if `default_font` feature is enabled (enabled by default in `bevy` crate), /// `FiraMono-subset.ttf` compiled into the library is used. /// * otherwise no text will be rendered, unless a custom font is loaded into the default font /// handle. Handle(Handle<Font>), /// Resolve the font by family name using the font database. Family(SmolStr), } impl Default for FontSource { fn default() -> Self { Self::Handle(Handle::default()) } } impl From<Handle<Font>> for FontSource { fn from(handle: Handle<Font>) -> Self { Self::Handle(handle) } } impl From<&Handle<Font>> for FontSource { fn from(handle: &Handle<Font>) -> Self { Self::Handle(handle.clone()) } } impl From<SmolStr> for FontSource { fn from(family: SmolStr) -> Self { FontSource::Family(family) } } impl From<&str> for FontSource { fn from(family: &str) -> Self { FontSource::Family(family.into()) } } /// `TextFont` determines the style of a text span within a [`ComputedTextBlock`], specifically /// the font face, the font size, the line height, and the antialiasing method. #[derive(Component, Clone, Debug, Reflect, PartialEq)] #[reflect(Component, Default, Debug, Clone)] pub struct TextFont { /// Specifies how the font face for a text span is sourced. /// /// A `FontSource` can either reference a font asset or identify a font by family name to be /// resolved by the text systems. pub font: FontSource, /// The vertical height of rasterized glyphs in the font atlas in pixels. /// /// This is multiplied by the window scale factor and `UiScale`, but not the text entity /// transform or camera projection. /// /// A new font atlas is generated for every combination of font handle and scaled font size /// which can have a strong performance impact. pub font_size: f32, /// How thick or bold the strokes of a font appear. /// /// Font weights can be any value between 1 and 1000, inclusive. /// /// Only supports variable weight fonts. pub weight: FontWeight, /// How condensed or expanded the glyphs appear horizontally. pub width: FontWidth, /// The slant style of a font face: normal, italic, or oblique. pub style: FontStyle, /// The antialiasing method to use when rendering text. pub font_smoothing: FontSmoothing, /// OpenType features for .otf fonts that support them. pub font_features: FontFeatures, } impl TextFont { /// Returns a new [`TextFont`] with the specified font size. pub fn from_font_size(font_size: f32) -> Self { Self::default().with_font_size(font_size) } /// Returns this [`TextFont`] with the specified font face handle. pub fn with_font(mut self, font: Handle<Font>) -> Self { self.font = FontSource::Handle(font); self } /// Returns this [`TextFont`] with the specified font family. pub fn with_family(mut self, family: impl Into<SmolStr>) -> Self { self.font = FontSource::Family(family.into()); self } /// Returns this [`TextFont`] with the specified font size. pub const fn with_font_size(mut self, font_size: f32) -> Self { self.font_size = font_size; self } /// Returns this [`TextFont`] with the specified [`FontSmoothing`]. pub const fn with_font_smoothing(mut self, font_smoothing: FontSmoothing) -> Self { self.font_smoothing = font_smoothing; self } } impl<T: Into<FontSource>> From<T> for TextFont { fn from(source: T) -> Self { Self { font: source.into(), ..default() } } } impl Default for TextFont { fn default() -> Self { Self { font: Default::default(), font_size: 20.0, style: FontStyle::Normal, weight: FontWeight::NORMAL, width: FontWidth::NORMAL, font_features: FontFeatures::default(), font_smoothing: Default::default(), } } } /// How thick or bold the strokes of a font appear. /// /// Valid font weights range from 1 to 1000, inclusive. /// Weights above 1000 are clamped to 1000. /// A weight of 0 is treated as [`FontWeight::DEFAULT`]. /// /// `<https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/font-weight>` #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect)] pub struct FontWeight(pub u16); impl FontWeight { /// Weight 100. pub const THIN: FontWeight = FontWeight(100); /// Weight 200. pub const EXTRA_LIGHT: FontWeight = FontWeight(200); /// Weight 300. pub const LIGHT: FontWeight = FontWeight(300); /// Weight 400. pub const NORMAL: FontWeight = FontWeight(400); /// Weight 500. pub const MEDIUM: FontWeight = FontWeight(500); /// Weight 600. pub const SEMIBOLD: FontWeight = FontWeight(600); /// Weight 700. pub const BOLD: FontWeight = FontWeight(700); /// Weight 800 pub const EXTRA_BOLD: FontWeight = FontWeight(800); /// Weight 900. pub const BLACK: FontWeight = FontWeight(900); /// Weight 950. pub const EXTRA_BLACK: FontWeight = FontWeight(950); /// The default font weight. pub const DEFAULT: FontWeight = Self::NORMAL; /// Clamp the weight value to between 1 and 1000. /// Values of 0 are mapped to `Weight::DEFAULT`. pub const fn clamp(mut self) -> Self { if self.0 == 0 { self = Self::DEFAULT; } else if 1000 < self.0 { self.0 = 1000; } Self(self.0) } } impl Default for FontWeight { fn default() -> Self { Self::DEFAULT } } impl From<FontWeight> for cosmic_text::Weight { fn from(value: FontWeight) -> Self { cosmic_text::Weight(value.clamp().0) } } /// `<https://docs.microsoft.com/en-us/typography/opentype/spec/os2#uswidthclass>` #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Debug, Hash, Reflect)] pub struct FontWidth(u16); impl FontWidth { /// 50% of normal width. pub const ULTRA_CONDENSED: Self = Self(1); /// 62.5% of normal width. pub const EXTRA_CONDENSED: Self = Self(2); /// 75% of normal width. pub const CONDENSED: Self = Self(3); /// 87.5% of normal width. pub const SEMI_CONDENSED: Self = Self(4); /// 100% of normal width. This is the default. pub const NORMAL: Self = Self(5); /// 112.5% of normal width. pub const SEMI_EXPANDED: Self = Self(6); /// 125% of normal width. pub const EXPANDED: Self = Self(7); /// 150% of normal width. pub const EXTRA_EXPANDED: Self = Self(8); /// 200% of normal width. pub const ULTRA_EXPANDED: Self = Self(9); } impl Default for FontWidth { fn default() -> Self { Self::NORMAL } } impl From<FontWidth> for Stretch { fn from(value: FontWidth) -> Self { match value.0 { 1 => Stretch::UltraCondensed, 2 => Stretch::ExtraCondensed, 3 => Stretch::Condensed, 4 => Stretch::SemiCondensed, 6 => Stretch::SemiExpanded, 7 => Stretch::Expanded, 8 => Stretch::ExtraExpanded, 9 => Stretch::UltraExpanded, _ => Stretch::Normal, } } } /// The slant style of a font face: normal, italic, or oblique. #[derive(Clone, Copy, Default, PartialEq, Eq, Debug, Hash, Reflect)] pub enum FontStyle { /// A face that is neither italic nor obliqued. #[default] Normal, /// A form that is generally cursive in nature. Italic, /// A typically sloped version of the regular face. Oblique, } impl From<FontStyle> for cosmic_text::Style { fn from(value: FontStyle) -> Self { match value { FontStyle::Normal => cosmic_text::Style::Normal, FontStyle::Italic => cosmic_text::Style::Italic, FontStyle::Oblique => cosmic_text::Style::Oblique, } } } /// An OpenType font feature tag. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect)] pub struct FontFeatureTag([u8; 4]); impl FontFeatureTag { /// Replaces character combinations like fi, fl with ligatures. pub const STANDARD_LIGATURES: FontFeatureTag = FontFeatureTag::new(b"liga"); /// Enables ligatures based on character context. pub const CONTEXTUAL_LIGATURES: FontFeatureTag = FontFeatureTag::new(b"clig"); /// Enables optional ligatures for stylistic use (e.g., ct, st). pub const DISCRETIONARY_LIGATURES: FontFeatureTag = FontFeatureTag::new(b"dlig"); /// Adjust glyph shapes based on surrounding letters. pub const CONTEXTUAL_ALTERNATES: FontFeatureTag = FontFeatureTag::new(b"calt"); /// Use alternate glyph designs. pub const STYLISTIC_ALTERNATES: FontFeatureTag = FontFeatureTag::new(b"salt"); /// Replaces lowercase letters with small caps. pub const SMALL_CAPS: FontFeatureTag = FontFeatureTag::new(b"smcp"); /// Replaces uppercase letters with small caps. pub const CAPS_TO_SMALL_CAPS: FontFeatureTag = FontFeatureTag::new(b"c2sc"); /// Replaces characters with swash versions (often decorative). pub const SWASH: FontFeatureTag = FontFeatureTag::new(b"swsh"); /// Enables alternate glyphs for large sizes or titles. pub const TITLING_ALTERNATES: FontFeatureTag = FontFeatureTag::new(b"titl"); /// Converts numbers like 1/2 into true fractions (½). pub const FRACTIONS: FontFeatureTag = FontFeatureTag::new(b"frac"); /// Formats characters like 1st, 2nd properly. pub const ORDINALS: FontFeatureTag = FontFeatureTag::new(b"ordn"); /// Uses a slashed version of zero (0) to differentiate from O. pub const SLASHED_ZERO: FontFeatureTag = FontFeatureTag::new(b"ordn"); /// Replaces figures with superscript figures, e.g. for indicating footnotes. pub const SUPERSCRIPT: FontFeatureTag = FontFeatureTag::new(b"sups"); /// Replaces figures with subscript figures. pub const SUBSCRIPT: FontFeatureTag = FontFeatureTag::new(b"subs"); /// Changes numbers to "oldstyle" form, which fit better in the flow of sentences or other text. pub const OLDSTYLE_FIGURES: FontFeatureTag = FontFeatureTag::new(b"onum"); /// Changes numbers to "lining" form, which are better suited for standalone numbers. When /// enabled, the bottom of all numbers will be aligned with each other. pub const LINING_FIGURES: FontFeatureTag = FontFeatureTag::new(b"lnum"); /// Changes numbers to be of proportional width. When enabled, numbers may have varying widths. pub const PROPORTIONAL_FIGURES: FontFeatureTag = FontFeatureTag::new(b"pnum"); /// Changes numbers to be of uniform (tabular) width. When enabled, all numbers will have the /// same width. pub const TABULAR_FIGURES: FontFeatureTag = FontFeatureTag::new(b"tnum"); /// Varies the stroke thickness. Values must be in the range of 0 to 1000. pub const WEIGHT: FontFeatureTag = FontFeatureTag::new(b"wght"); /// Varies the width of text from narrower to wider. Must be a value greater than 0. A value of /// 100 is typically considered standard width. pub const WIDTH: FontFeatureTag = FontFeatureTag::new(b"wdth"); /// Varies between upright and slanted text. Must be a value greater than -90 and less than +90. /// A value of 0 is upright. pub const SLANT: FontFeatureTag = FontFeatureTag::new(b"slnt"); /// Create a new [`FontFeatureTag`] from raw bytes. pub const fn new(src: &[u8; 4]) -> Self { Self(*src) } } impl Debug for FontFeatureTag { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { // OpenType tags are always ASCII, so this match will succeed for valid tags. This gives us // human-readable debug output, e.g. FontFeatureTag("liga"). match from_utf8(&self.0) { Ok(s) => write!(f, "FontFeatureTag(\"{}\")", s), Err(_) => write!(f, "FontFeatureTag({:?})", self.0), } } } /// OpenType features for .otf fonts that support them. /// /// Examples features include ligatures, small-caps, and fractional number display. For the complete /// list of OpenType features, see the spec at /// `<https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist>`. /// /// # Usage: /// ``` /// use bevy_text::{FontFeatureTag, FontFeatures}; /// /// // Create using the builder /// let font_features = FontFeatures::builder() /// .enable(FontFeatureTag::STANDARD_LIGATURES) /// .set(FontFeatureTag::WEIGHT, 300) /// .build(); /// /// // Create from a list /// let more_font_features: FontFeatures = [ /// FontFeatureTag::STANDARD_LIGATURES, /// FontFeatureTag::OLDSTYLE_FIGURES, /// FontFeatureTag::TABULAR_FIGURES /// ].into(); /// ``` #[derive(Clone, Debug, Default, Reflect, PartialEq)] pub struct FontFeatures { features: Vec<(FontFeatureTag, u32)>, } impl FontFeatures { /// Create a new [`FontFeaturesBuilder`]. pub fn builder() -> FontFeaturesBuilder { FontFeaturesBuilder::default() } } /// A builder for [`FontFeatures`]. #[derive(Clone, Default)] pub struct FontFeaturesBuilder { features: Vec<(FontFeatureTag, u32)>, } impl FontFeaturesBuilder { /// Enable an OpenType feature. /// /// Most OpenType features are on/off switches, so this is a convenience method that sets the /// feature's value to "1" (enabled). For non-boolean features, see [`FontFeaturesBuilder::set`]. pub fn enable(self, feature_tag: FontFeatureTag) -> Self { self.set(feature_tag, 1) } /// Set an OpenType feature to a specific value. /// /// For most features, the [`FontFeaturesBuilder::enable`] method should be used instead. A few /// features, such as "wght", take numeric values, so this method may be used for these cases. pub fn set(mut self, feature_tag: FontFeatureTag, value: u32) -> Self { self.features.push((feature_tag, value)); self } /// Build a [`FontFeatures`] from the values set within this builder. pub fn build(self) -> FontFeatures { FontFeatures { features: self.features, } } } /// Allow [`FontFeatures`] to be built from a list. This is suitable for the standard case when each /// listed feature is a boolean type. If any features require a numeric value (like "wght"), use /// [`FontFeaturesBuilder`] instead. impl<T> From<T> for FontFeatures where T: IntoIterator<Item = FontFeatureTag>, { fn from(value: T) -> Self { FontFeatures { features: value.into_iter().map(|x| (x, 1)).collect(), } } } impl From<&FontFeatures> for cosmic_text::FontFeatures { fn from(font_features: &FontFeatures) -> Self { cosmic_text::FontFeatures { features: font_features .features .iter() .map(|(tag, value)| cosmic_text::Feature { tag: cosmic_text::FeatureTag::new(&tag.0), value: *value, }) .collect(), } } } /// Specifies the height of each line of text for `Text` and `Text2d` /// /// Default is 1.2x the font size #[derive(Component, Debug, Clone, Copy, PartialEq, Reflect)] #[reflect(Component, Debug, Clone, PartialEq)] pub enum LineHeight { /// Set line height to a specific number of pixels Px(f32), /// Set line height to a multiple of the font size RelativeToFont(f32), } impl LineHeight { pub(crate) fn eval(self, font_size: f32) -> f32 { match self { LineHeight::Px(px) => px, LineHeight::RelativeToFont(scale) => scale * font_size, } } } impl Default for LineHeight { fn default() -> Self { LineHeight::RelativeToFont(1.2) } } /// The color of the text for this section. #[derive(Component, Copy, Clone, Debug, Deref, DerefMut, Reflect, PartialEq)] #[reflect(Component, Default, Debug, PartialEq, Clone)] pub struct TextColor(pub Color); impl Default for TextColor { fn default() -> Self { Self::WHITE } } impl<T: Into<Color>> From<T> for TextColor { fn from(color: T) -> Self { Self(color.into()) } } impl TextColor { /// Black colored text pub const BLACK: Self = TextColor(Color::BLACK); /// White colored text pub const WHITE: Self = TextColor(Color::WHITE); } /// The background color of the text for this section. #[derive(Component, Copy, Clone, Debug, Deref, DerefMut, Reflect, PartialEq)] #[reflect(Component, Default, Debug, PartialEq, Clone)] pub struct TextBackgroundColor(pub Color); impl Default for TextBackgroundColor { fn default() -> Self { Self(Color::BLACK) } } impl<T: Into<Color>> From<T> for TextBackgroundColor { fn from(color: T) -> Self { Self(color.into()) } } impl TextBackgroundColor { /// Black background pub const BLACK: Self = TextBackgroundColor(Color::BLACK); /// White background pub const WHITE: Self = TextBackgroundColor(Color::WHITE); } /// Determines how lines will be broken when preventing text from running out of bounds. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Reflect, Serialize, Deserialize)] #[reflect(Serialize, Deserialize, Clone, PartialEq, Hash, Default)] pub enum LineBreak { /// Uses the [Unicode Line Breaking Algorithm](https://www.unicode.org/reports/tr14/). /// Lines will be broken up at the nearest suitable word boundary, usually a space. /// This behavior suits most cases, as it keeps words intact across linebreaks. #[default] WordBoundary, /// Lines will be broken without discrimination on any character that would leave bounds. /// This is closer to the behavior one might expect from text in a terminal. /// However it may lead to words being broken up across linebreaks. AnyCharacter, /// Wraps at the word level, or fallback to character level if a word can’t fit on a line by itself WordOrCharacter, /// No soft wrapping, where text is automatically broken up into separate lines when it overflows a boundary, will ever occur. /// Hard wrapping, where text contains an explicit linebreak such as the escape sequence `\n`, is still enabled. NoWrap, } /// A text entity with this component is drawn with strikethrough. #[derive(Component, Copy, Clone, Debug, Reflect, Default, Serialize, Deserialize)] #[reflect(Serialize, Deserialize, Clone, Default)] pub struct Strikethrough; /// Color for the text's strikethrough. If this component is not present, its `TextColor` will be used. #[derive(Component, Copy, Clone, Debug, Deref, DerefMut, Reflect, PartialEq)] #[reflect(Component, Default, Debug, PartialEq, Clone)] pub struct StrikethroughColor(pub Color); impl Default for StrikethroughColor { fn default() -> Self { Self(Color::WHITE) } } impl<T: Into<Color>> From<T> for StrikethroughColor { fn from(color: T) -> Self { Self(color.into()) } } /// Add to a text entity to draw its text with underline. #[derive(Component, Copy, Clone, Debug, Reflect, Default, Serialize, Deserialize)] #[reflect(Serialize, Deserialize, Clone, Default)] pub struct Underline; /// Color for the text's underline. If this component is not present, its `TextColor` will be used. #[derive(Component, Copy, Clone, Debug, Deref, DerefMut, Reflect, PartialEq)] #[reflect(Component, Default, Debug, PartialEq, Clone)] pub struct UnderlineColor(pub Color); impl Default for UnderlineColor { fn default() -> Self { Self(Color::WHITE) } } impl<T: Into<Color>> From<T> for UnderlineColor { fn from(color: T) -> Self { Self(color.into()) } } /// Determines which antialiasing method to use when rendering text. By default, text is /// rendered with grayscale antialiasing, but this can be changed to achieve a pixelated look. /// /// **Note:** Subpixel antialiasing is not currently supported. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Reflect, Serialize, Deserialize)] #[reflect(Serialize, Deserialize, Clone, PartialEq, Hash, Default)] #[doc(alias = "antialiasing")] #[doc(alias = "pixelated")] pub enum FontSmoothing { /// No antialiasing. Useful for when you want to render text with a pixel art aesthetic. /// /// Combine this with `UiAntiAlias::Off` and `Msaa::Off` on your 2D camera for a fully pixelated look. /// /// **Note:** Due to limitations of the underlying text rendering library, /// this may require specially-crafted pixel fonts to look good, especially at small sizes. None, /// The default grayscale antialiasing. Produces text that looks smooth, /// even at small font sizes and low resolutions with modern vector fonts. #[default] AntiAliased, // TODO: Add subpixel antialias support // SubpixelAntiAliased, } /// System that detects changes to text blocks and sets `ComputedTextBlock::should_rerender`. /// /// Generic over the root text component and text span component. For example, `Text2d`/[`TextSpan`] for /// 2d or `Text`/[`TextSpan`] for UI. pub fn detect_text_needs_rerender<Root: Component>( changed_roots: Query< Entity, ( Or<( Changed<Root>, Changed<TextFont>, Changed<TextLayout>, Changed<LineHeight>, Changed<Children>, )>, With<Root>, With<TextFont>, With<TextLayout>, ), >, changed_spans: Query< (Entity, Option<&ChildOf>, Has<TextLayout>), ( Or<( Changed<TextSpan>, Changed<TextFont>, Changed<LineHeight>, Changed<Children>, Changed<ChildOf>, // Included to detect broken text block hierarchies. Added<TextLayout>, )>, With<TextSpan>, With<TextFont>, ), >, mut computed: Query<( Option<&ChildOf>, Option<&mut ComputedTextBlock>, Has<TextSpan>, )>, ) { // Root entity: // - Root component changed. // - TextFont on root changed. // - TextLayout changed. // - Root children changed (can include additions and removals). for root in changed_roots.iter() { let Ok((_, Some(mut computed), _)) = computed.get_mut(root) else { once!(warn!("found entity {} with a root text component ({}) but no ComputedTextBlock; this warning only \ prints once", root, core::any::type_name::<Root>())); continue; }; computed.needs_rerender = true; } // Span entity: // - Span component changed. // - Span TextFont changed. // - Span children changed (can include additions and removals).
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_text/src/font.rs
crates/bevy_text/src/font.rs
use alloc::sync::Arc; use bevy_asset::Asset; use bevy_asset::AssetEvent; use bevy_asset::Assets; use bevy_ecs::message::MessageReader; use bevy_ecs::system::Query; use bevy_ecs::system::ResMut; use bevy_reflect::TypePath; use cosmic_text::fontdb::ID; use cosmic_text::skrifa::raw::ReadError; use cosmic_text::skrifa::FontRef; use smallvec::SmallVec; use crate::ComputedTextBlock; use crate::CosmicFontSystem; /// An [`Asset`] that contains the data for a loaded font, if loaded as an asset. /// /// Loaded by [`FontLoader`](crate::FontLoader). /// /// # A note on fonts /// /// `Font` may differ from the everyday notion of what a "font" is. /// A font *face* (e.g. Fira Sans Semibold Italic) is part of a font *family* (e.g. Fira Sans), /// and is distinguished from other font faces in the same family /// by its style (e.g. italic), its weight (e.g. bold) and its stretch (e.g. condensed). /// /// Bevy currently loads a single font face as a single `Font` asset. #[derive(Debug, TypePath, Clone, Asset)] pub struct Font { /// Content of a font file as bytes pub data: Arc<Vec<u8>>, /// Ids for fonts in font file pub ids: SmallVec<[ID; 8]>, } impl Font { /// Creates a [`Font`] from bytes pub fn try_from_bytes(font_data: Vec<u8>) -> Result<Self, ReadError> { let _ = FontRef::from_index(&font_data, 0)?; Ok(Self { data: Arc::new(font_data), ids: SmallVec::new(), }) } } /// Add new font assets to the font system's database. pub fn load_font_assets_into_fontdb_system( mut fonts: ResMut<Assets<Font>>, mut events: MessageReader<AssetEvent<Font>>, mut cosmic_font_system: ResMut<CosmicFontSystem>, mut text_block_query: Query<&mut ComputedTextBlock>, ) { let mut new_fonts_added = false; let font_system = &mut cosmic_font_system.0; for event in events.read() { if let AssetEvent::Added { id } = event && let Some(font) = fonts.get_mut(*id) { let data = Arc::clone(&font.data); font.ids = font_system .db_mut() .load_font_source(cosmic_text::fontdb::Source::Binary(data)) .into_iter() .collect(); new_fonts_added = true; } } // Whenever new fonts are added, update all text blocks so they use the new fonts. if new_fonts_added { for mut block in text_block_query.iter_mut() { block.needs_rerender = true; } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_text/src/error.rs
crates/bevy_text/src/error.rs
use cosmic_text::CacheKey; use thiserror::Error; #[derive(Debug, PartialEq, Eq, Error)] /// Errors related to the textsystem pub enum TextError { /// Font was not found, this could be that the font has not yet been loaded, or /// that the font failed to load for some other reason #[error("font not found")] NoSuchFont, /// Failed to add glyph to a newly created atlas for some reason #[error("failed to add glyph to newly-created atlas {0:?}")] FailedToAddGlyph(u16), /// Failed to get scaled glyph image for cache key #[error("failed to get scaled glyph image for cache key: {0:?}")] FailedToGetGlyphImage(CacheKey), /// Missing texture atlas layout for the font #[error("missing texture atlas layout for the font")] MissingAtlasLayout, /// Missing texture for the font atlas #[error("missing texture for the font atlas")] MissingAtlasTexture, /// Failed to find glyph in atlas after it was added #[error("failed to find glyph in atlas after it was added")] InconsistentAtlasState, }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_text/src/pipeline.rs
crates/bevy_text/src/pipeline.rs
use alloc::sync::Arc; use bevy_asset::{AssetId, Assets}; use bevy_color::Color; use bevy_derive::{Deref, DerefMut}; use bevy_ecs::{ component::Component, entity::Entity, reflect::ReflectComponent, resource::Resource, system::ResMut, }; use bevy_image::prelude::*; use bevy_log::{once, warn}; use bevy_math::{Rect, UVec2, Vec2}; use bevy_platform::collections::HashMap; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use smol_str::SmolStr; use crate::{ add_glyph_to_atlas, error::TextError, get_glyph_atlas_info, ComputedTextBlock, Font, FontAtlasKey, FontAtlasSet, FontHinting, FontSmoothing, FontSource, Justify, LineBreak, LineHeight, PositionedGlyph, TextBounds, TextEntity, TextFont, TextLayout, }; use cosmic_text::{fontdb::ID, Attrs, Buffer, Family, Metrics, Shaping, Wrap}; /// A wrapper resource around a [`cosmic_text::FontSystem`] /// /// The font system is used to retrieve fonts and their information, including glyph outlines. /// /// This resource is updated by the [`TextPipeline`] resource. #[derive(Resource, Deref, DerefMut)] pub struct CosmicFontSystem(pub cosmic_text::FontSystem); impl Default for CosmicFontSystem { fn default() -> Self { let locale = sys_locale::get_locale().unwrap_or_else(|| String::from("en-US")); let db = cosmic_text::fontdb::Database::new(); // TODO: consider using `cosmic_text::FontSystem::new()` (load system fonts by default) Self(cosmic_text::FontSystem::new_with_locale_and_db(locale, db)) } } /// A wrapper resource around a [`cosmic_text::SwashCache`] /// /// The swash cache rasterizer is used to rasterize glyphs /// /// This resource is updated by the [`TextPipeline`] resource. #[derive(Resource)] pub struct SwashCache(pub cosmic_text::SwashCache); impl Default for SwashCache { fn default() -> Self { Self(cosmic_text::SwashCache::new()) } } /// Information about a font collected as part of preparing for text layout. #[derive(Clone)] pub struct FontFaceInfo { /// Font family name pub family_name: SmolStr, } /// The `TextPipeline` is used to layout and render text blocks (see `Text`/`Text2d`). /// /// See the [crate-level documentation](crate) for more information. #[derive(Default, Resource)] pub struct TextPipeline { /// Identifies a font [`ID`] by its [`Font`] [`Asset`](bevy_asset::Asset). pub map_handle_to_font_id: HashMap<AssetId<Font>, (ID, Arc<str>)>, /// Buffered vec for collecting spans. /// /// See [this dark magic](https://users.rust-lang.org/t/how-to-cache-a-vectors-capacity/94478/10). spans_buffer: Vec<( usize, &'static str, &'static TextFont, FontFaceInfo, LineHeight, )>, } impl TextPipeline { /// Utilizes [`cosmic_text::Buffer`] to shape and layout text /// /// Negative or 0.0 font sizes will not be laid out. pub fn update_buffer<'a>( &mut self, fonts: &Assets<Font>, text_spans: impl Iterator<Item = (Entity, usize, &'a str, &'a TextFont, Color, LineHeight)>, linebreak: LineBreak, justify: Justify, bounds: TextBounds, scale_factor: f64, computed: &mut ComputedTextBlock, font_system: &mut CosmicFontSystem, hinting: FontHinting, ) -> Result<(), TextError> { computed.needs_rerender = false; let font_system = &mut font_system.0; // Collect span information into a vec. This is necessary because font loading requires mut access // to FontSystem, which the cosmic-text Buffer also needs. let mut spans: Vec<(usize, &str, &TextFont, FontFaceInfo, Color, LineHeight)> = core::mem::take(&mut self.spans_buffer) .into_iter() .map( |_| -> (usize, &str, &TextFont, FontFaceInfo, Color, LineHeight) { unreachable!() }, ) .collect(); computed.entities.clear(); for (span_index, (entity, depth, span, text_font, color, line_height)) in text_spans.enumerate() { // Save this span entity in the computed text block. computed.entities.push(TextEntity { entity, depth }); if span.is_empty() { continue; } let family_name: SmolStr = match &text_font.font { FontSource::Handle(handle) => { if let Some(font) = fonts.get(handle.id()) { let data = Arc::clone(&font.data); let ids = font_system .db_mut() .load_font_source(cosmic_text::fontdb::Source::Binary(data)); // TODO: it is assumed this is the right font face font_system .db() .face(*ids.last().unwrap()) .unwrap() .families[0] .0 .as_str() .into() } else { // Return early if a font is not loaded yet. spans.clear(); self.spans_buffer = spans .into_iter() .map( |_| -> ( usize, &'static str, &'static TextFont, FontFaceInfo, LineHeight, ) { unreachable!() }, ) .collect(); return Err(TextError::NoSuchFont); } } FontSource::Family(family) => family.clone(), }; let face_info = FontFaceInfo { family_name }; // Save spans that aren't zero-sized. if scale_factor <= 0.0 || text_font.font_size <= 0.0 { once!(warn!( "Text span {entity} has a font size <= 0.0. Nothing will be displayed.", )); continue; } spans.push((span_index, span, text_font, face_info, color, line_height)); } // Map text sections to cosmic-text spans, and ignore sections with negative or zero fontsizes, // since they cannot be rendered by cosmic-text. // // The section index is stored in the metadata of the spans, and could be used // to look up the section the span came from and is not used internally // in cosmic-text. let spans_iter = spans.iter().map( |(span_index, span, text_font, font_info, color, line_height)| { ( *span, get_attrs( *span_index, text_font, *line_height, *color, font_info, scale_factor, ), ) }, ); // Update the buffer. let buffer = &mut computed.buffer; // Set the metrics hinting strategy buffer.set_hinting(font_system, hinting.into()); buffer.set_wrap( font_system, match linebreak { LineBreak::WordBoundary => Wrap::Word, LineBreak::AnyCharacter => Wrap::Glyph, LineBreak::WordOrCharacter => Wrap::WordOrGlyph, LineBreak::NoWrap => Wrap::None, }, ); buffer.set_rich_text( font_system, spans_iter, &Attrs::new(), Shaping::Advanced, Some(justify.into()), ); // Workaround for alignment not working for unbounded text. // See https://github.com/pop-os/cosmic-text/issues/343 let width = (bounds.width.is_none() && justify != Justify::Left) .then(|| buffer_dimensions(buffer).x) .or(bounds.width); buffer.set_size(font_system, width, bounds.height); // Recover the spans buffer. spans.clear(); self.spans_buffer = spans .into_iter() .map( |_| -> ( usize, &'static str, &'static TextFont, FontFaceInfo, LineHeight, ) { unreachable!() }, ) .collect(); Ok(()) } /// Queues text for measurement /// /// Produces a [`TextMeasureInfo`] which can be used by a layout system /// to measure the text area on demand. pub fn create_text_measure<'a>( &mut self, entity: Entity, fonts: &Assets<Font>, text_spans: impl Iterator<Item = (Entity, usize, &'a str, &'a TextFont, Color, LineHeight)>, scale_factor: f64, layout: &TextLayout, computed: &mut ComputedTextBlock, font_system: &mut CosmicFontSystem, hinting: FontHinting, ) -> Result<TextMeasureInfo, TextError> { const MIN_WIDTH_CONTENT_BOUNDS: TextBounds = TextBounds::new_horizontal(0.0); // Clear this here at the focal point of measured text rendering to ensure the field's lifecycle has // strong boundaries. computed.needs_rerender = false; self.update_buffer( fonts, text_spans, layout.linebreak, layout.justify, MIN_WIDTH_CONTENT_BOUNDS, scale_factor, computed, font_system, hinting, )?; let buffer = &mut computed.buffer; let min_width_content_size = buffer_dimensions(buffer); let max_width_content_size = { let font_system = &mut font_system.0; buffer.set_size(font_system, None, None); buffer_dimensions(buffer) }; Ok(TextMeasureInfo { min: min_width_content_size, max: max_width_content_size, entity, }) } /// Returns the [`cosmic_text::fontdb::ID`] for a given [`Font`] asset. pub fn get_font_id(&self, asset_id: AssetId<Font>) -> Option<ID> { self.map_handle_to_font_id .get(&asset_id) .cloned() .map(|(id, _)| id) } /// Update [`TextLayoutInfo`] with the new [`PositionedGlyph`] layout. pub fn update_text_layout_info( &mut self, layout_info: &mut TextLayoutInfo, font_atlas_set: &mut FontAtlasSet, texture_atlases: &mut Assets<TextureAtlasLayout>, textures: &mut Assets<Image>, computed: &mut ComputedTextBlock, font_system: &mut CosmicFontSystem, swash_cache: &mut SwashCache, bounds: TextBounds, justify: Justify, ) -> Result<(), TextError> { computed.needs_rerender = false; layout_info.clear(); let buffer = &mut computed.buffer; // Workaround for alignment not working for unbounded text. // See https://github.com/pop-os/cosmic-text/issues/343 let width = (bounds.width.is_none() && justify != Justify::Left) .then(|| buffer_dimensions(buffer).x) .or(bounds.width); buffer.set_size(font_system, width, bounds.height); let mut box_size = Vec2::ZERO; for run in buffer.layout_runs() { box_size.x = box_size.x.max(run.line_w); box_size.y += run.line_height; let mut maybe_run_geometry: Option<RunGeometry> = None; let mut end: f32 = 0.; for layout_glyph in run.glyphs { if maybe_run_geometry .as_ref() .is_some_and(|run_geometry| run_geometry.span_index != layout_glyph.metadata) { layout_info .run_geometry .push(maybe_run_geometry.take().unwrap()); } if maybe_run_geometry.is_none() { let metrics = font_system .get_font(layout_glyph.font_id, layout_glyph.font_weight) .ok_or(TextError::NoSuchFont)? .as_swash() .metrics(&[]); let scalar = layout_glyph.font_size / metrics.units_per_em as f32; let stroke_size = (metrics.stroke_size * scalar).round().max(1.); let start = end.max(layout_glyph.x); maybe_run_geometry = Some(RunGeometry { span_index: layout_glyph.metadata, bounds: Rect::new( start, run.line_top, start, run.line_top + run.line_height, ), strikethrough_y: (run.line_y - metrics.strikeout_offset * scalar).round(), strikethrough_thickness: stroke_size, underline_y: (run.line_y - metrics.underline_offset * scalar).round(), underline_thickness: stroke_size, }); } end = layout_glyph.x + layout_glyph.w; maybe_run_geometry.as_mut().unwrap().bounds.max.x = end; let mut temp_glyph; let span_index = layout_glyph.metadata; let font_smoothing = FontSmoothing::AntiAliased; let layout_glyph = if font_smoothing == FontSmoothing::None { // If font smoothing is disabled, round the glyph positions and sizes, // effectively discarding all subpixel layout. temp_glyph = layout_glyph.clone(); temp_glyph.x = temp_glyph.x.round(); temp_glyph.y = temp_glyph.y.round(); temp_glyph.w = temp_glyph.w.round(); temp_glyph.x_offset = temp_glyph.x_offset.round(); temp_glyph.y_offset = temp_glyph.y_offset.round(); temp_glyph.line_height_opt = temp_glyph.line_height_opt.map(f32::round); &temp_glyph } else { layout_glyph }; let physical_glyph = layout_glyph.physical((0., 0.), 1.); let font_atlases = font_atlas_set .entry(FontAtlasKey { id: physical_glyph.cache_key.font_id, font_size_bits: physical_glyph.cache_key.font_size_bits, font_smoothing, }) .or_default(); let atlas_info = get_glyph_atlas_info(font_atlases, physical_glyph.cache_key) .map(Ok) .unwrap_or_else(|| { add_glyph_to_atlas( font_atlases, texture_atlases, textures, &mut font_system.0, &mut swash_cache.0, layout_glyph, font_smoothing, ) })?; let texture_atlas = texture_atlases.get(atlas_info.texture_atlas).unwrap(); let location = atlas_info.location; let glyph_rect = texture_atlas.textures[location.glyph_index]; let left = location.offset.x as f32; let top = location.offset.y as f32; let glyph_size = UVec2::new(glyph_rect.width(), glyph_rect.height()); // offset by half the size because the origin is center let x = glyph_size.x as f32 / 2.0 + left + physical_glyph.x as f32; let y = run.line_y.round() + physical_glyph.y as f32 - top + glyph_size.y as f32 / 2.0; let position = Vec2::new(x, y); let pos_glyph = PositionedGlyph { position, size: glyph_size.as_vec2(), atlas_info, span_index, byte_index: layout_glyph.start, byte_length: layout_glyph.end - layout_glyph.start, line_index: run.line_i, }; layout_info.glyphs.push(pos_glyph); } if let Some(run_geometry) = maybe_run_geometry.take() { layout_info.run_geometry.push(run_geometry); } } layout_info.size = box_size.ceil(); Ok(()) } } /// Render information for a corresponding text block. /// /// Contains scaled glyphs and their size. Generated via [`TextPipeline::update_text_layout_info`] when an entity has /// [`TextLayout`] and [`ComputedTextBlock`] components. #[derive(Component, Clone, Default, Debug, Reflect)] #[reflect(Component, Default, Debug, Clone)] pub struct TextLayoutInfo { /// The target scale factor for this text layout pub scale_factor: f32, /// Scaled and positioned glyphs in screenspace pub glyphs: Vec<PositionedGlyph>, /// Geometry of each text run used to render text decorations like background colors, strikethrough, and underline. /// A run in `bevy_text` is a contiguous sequence of glyphs on a line that share the same text attributes like font, /// font size, and line height. A text entity that extends over multiple lines will have multiple corresponding runs. /// /// The coordinates are unscaled and relative to the top left corner of the text layout. pub run_geometry: Vec<RunGeometry>, /// The glyphs resulting size pub size: Vec2, } impl TextLayoutInfo { /// Clear the layout, retaining capacity pub fn clear(&mut self) { self.scale_factor = 1.; self.glyphs.clear(); self.run_geometry.clear(); self.size = Vec2::ZERO; } } /// Geometry of a text run used to render text decorations like background colors, strikethrough, and underline. /// A run in `bevy_text` is a contiguous sequence of glyphs on a line that share the same text attributes like font, /// font size, and line height. #[derive(Default, Debug, Clone, Reflect)] pub struct RunGeometry { /// The index of the text entity in [`ComputedTextBlock`] that this run belongs to. pub span_index: usize, /// Bounding box around the text run pub bounds: Rect, /// Y position of the strikethrough in the text layout. pub strikethrough_y: f32, /// Strikethrough stroke thickness. pub strikethrough_thickness: f32, /// Y position of the underline in the text layout. pub underline_y: f32, /// Underline stroke thickness. pub underline_thickness: f32, } impl RunGeometry { /// Returns the center of the strikethrough in the text layout. pub fn strikethrough_position(&self) -> Vec2 { Vec2::new( self.bounds.center().x, self.strikethrough_y + 0.5 * self.strikethrough_thickness, ) } /// Returns the size of the strikethrough. pub fn strikethrough_size(&self) -> Vec2 { Vec2::new(self.bounds.size().x, self.strikethrough_thickness) } /// Get the center of the underline in the text layout. pub fn underline_position(&self) -> Vec2 { Vec2::new( self.bounds.center().x, self.underline_y + 0.5 * self.underline_thickness, ) } /// Returns the size of the underline. pub fn underline_size(&self) -> Vec2 { Vec2::new(self.bounds.size().x, self.underline_thickness) } } /// Size information for a corresponding [`ComputedTextBlock`] component. /// /// Generated via [`TextPipeline::create_text_measure`]. #[derive(Debug)] pub struct TextMeasureInfo { /// Minimum size for a text area in pixels, to be used when laying out widgets with taffy pub min: Vec2, /// Maximum size for a text area in pixels, to be used when laying out widgets with taffy pub max: Vec2, /// The entity that is measured. pub entity: Entity, } impl TextMeasureInfo { /// Computes the size of the text area within the provided bounds. pub fn compute_size( &mut self, bounds: TextBounds, computed: &mut ComputedTextBlock, font_system: &mut CosmicFontSystem, ) -> Vec2 { // Note that this arbitrarily adjusts the buffer layout. We assume the buffer is always 'refreshed' // whenever a canonical state is required. computed .buffer .set_size(&mut font_system.0, bounds.width, bounds.height); buffer_dimensions(&computed.buffer) } } /// Translates [`TextFont`] to [`Attrs`]. fn get_attrs<'a>( span_index: usize, text_font: &TextFont, line_height: LineHeight, color: Color, face_info: &'a FontFaceInfo, scale_factor: f64, ) -> Attrs<'a> { Attrs::new() .metadata(span_index) .family(Family::Name(&face_info.family_name)) .stretch(text_font.width.into()) .style(text_font.style.into()) .weight(text_font.weight.into()) .metrics( Metrics { font_size: text_font.font_size, line_height: line_height.eval(text_font.font_size), } .scale(scale_factor as f32), ) .font_features((&text_font.font_features).into()) .color(cosmic_text::Color(color.to_linear().as_u32())) } /// Calculate the size of the text area for the given buffer. fn buffer_dimensions(buffer: &Buffer) -> Vec2 { let mut size = Vec2::ZERO; for run in buffer.layout_runs() { size.x = size.x.max(run.line_w); size.y += run.line_height; } size.ceil() } /// Discards stale data cached in `FontSystem`. pub(crate) fn trim_cosmic_cache(mut font_system: ResMut<CosmicFontSystem>) { // A trim age of 2 was found to reduce frame time variance vs age of 1 when tested with dynamic text. // See https://github.com/bevyengine/bevy/pull/15037 // // We assume only text updated frequently benefits from the shape cache (e.g. animated text, or // text that is dynamically measured for UI). font_system.0.shape_run_cache.trim(2); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_text/src/text_access.rs
crates/bevy_text/src/text_access.rs
use bevy_color::Color; use bevy_ecs::{ component::Mutable, prelude::*, system::{Query, SystemParam}, }; use crate::{LineHeight, TextColor, TextFont, TextSpan}; /// Helper trait for using the [`TextReader`] and [`TextWriter`] system params. pub trait TextSpanAccess: Component<Mutability = Mutable> { /// Gets the text span's string. fn read_span(&self) -> &str; /// Gets mutable reference to the text span's string. fn write_span(&mut self) -> &mut String; } /// Helper trait for the root text component in a text block. pub trait TextRoot: TextSpanAccess + From<String> {} /// Helper trait for the text span components in a text block. pub trait TextSpanComponent: TextSpanAccess + From<String> {} /// Scratch buffer used to store intermediate state when iterating over text spans. #[derive(Resource, Default)] pub struct TextIterScratch { stack: Vec<(&'static Children, usize)>, } impl TextIterScratch { fn take<'a>(&mut self) -> Vec<(&'a Children, usize)> { core::mem::take(&mut self.stack) .into_iter() .map(|_| -> (&Children, usize) { unreachable!() }) .collect() } fn recover(&mut self, mut stack: Vec<(&Children, usize)>) { stack.clear(); self.stack = stack .into_iter() .map(|_| -> (&'static Children, usize) { unreachable!() }) .collect(); } } /// System parameter for reading text spans in a text block. /// /// `R` is the root text component. #[derive(SystemParam)] pub struct TextReader<'w, 's, R: TextRoot> { // This is a local to avoid system ambiguities when TextReaders run in parallel. scratch: Local<'s, TextIterScratch>, roots: Query< 'w, 's, ( &'static R, &'static TextFont, &'static TextColor, &'static LineHeight, Option<&'static Children>, ), >, spans: Query< 'w, 's, ( &'static TextSpan, &'static TextFont, &'static TextColor, &'static LineHeight, Option<&'static Children>, ), >, } impl<'w, 's, R: TextRoot> TextReader<'w, 's, R> { /// Returns an iterator over text spans in a text block, starting with the root entity. pub fn iter(&mut self, root_entity: Entity) -> TextSpanIter<'_, R> { let stack = self.scratch.take(); TextSpanIter { scratch: &mut self.scratch, root_entity: Some(root_entity), stack, roots: &self.roots, spans: &self.spans, } } /// Gets a text span within a text block at a specific index in the flattened span list. pub fn get( &mut self, root_entity: Entity, index: usize, ) -> Option<(Entity, usize, &str, &TextFont, Color, LineHeight)> { self.iter(root_entity).nth(index) } /// Gets the text value of a text span within a text block at a specific index in the flattened span list. pub fn get_text(&mut self, root_entity: Entity, index: usize) -> Option<&str> { self.get(root_entity, index) .map(|(_, _, text, _, _, _)| text) } /// Gets the [`TextFont`] of a text span within a text block at a specific index in the flattened span list. pub fn get_font(&mut self, root_entity: Entity, index: usize) -> Option<&TextFont> { self.get(root_entity, index) .map(|(_, _, _, font, _, _)| font) } /// Gets the [`TextColor`] of a text span within a text block at a specific index in the flattened span list. pub fn get_color(&mut self, root_entity: Entity, index: usize) -> Option<Color> { self.get(root_entity, index) .map(|(_, _, _, _, color, _)| color) } /// Gets the [`LineHeight`] of a text span within a text block at a specific index in the flattened span list. pub fn get_line_height(&mut self, root_entity: Entity, index: usize) -> Option<LineHeight> { self.get(root_entity, index) .map(|(_, _, _, _, _, line_height)| line_height) } /// Gets the text value of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. pub fn text(&mut self, root_entity: Entity, index: usize) -> &str { self.get_text(root_entity, index).unwrap() } /// Gets the [`TextFont`] of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. pub fn font(&mut self, root_entity: Entity, index: usize) -> &TextFont { self.get_font(root_entity, index).unwrap() } /// Gets the [`TextColor`] of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. pub fn color(&mut self, root_entity: Entity, index: usize) -> Color { self.get_color(root_entity, index).unwrap() } /// Gets the [`LineHeight`] of a text span within a text block at a specific index in the flattened span list. pub fn line_height(&mut self, root_entity: Entity, index: usize) -> LineHeight { self.get_line_height(root_entity, index).unwrap() } } /// Iterator returned by [`TextReader::iter`]. /// /// Iterates all spans in a text block according to hierarchy traversal order. /// Does *not* flatten interspersed ghost nodes. Only contiguous spans are traversed. // TODO: Use this iterator design in UiChildrenIter to reduce allocations. pub struct TextSpanIter<'a, R: TextRoot> { scratch: &'a mut TextIterScratch, root_entity: Option<Entity>, /// Stack of (children, next index into children). stack: Vec<(&'a Children, usize)>, roots: &'a Query< 'a, 'a, ( &'static R, &'static TextFont, &'static TextColor, &'static LineHeight, Option<&'static Children>, ), >, spans: &'a Query< 'a, 'a, ( &'static TextSpan, &'static TextFont, &'static TextColor, &'static LineHeight, Option<&'static Children>, ), >, } impl<'a, R: TextRoot> Iterator for TextSpanIter<'a, R> { /// Item = (entity in text block, hierarchy depth in the block, span text, span style). type Item = (Entity, usize, &'a str, &'a TextFont, Color, LineHeight); fn next(&mut self) -> Option<Self::Item> { // Root if let Some(root_entity) = self.root_entity.take() { if let Ok((text, text_font, color, line_height, maybe_children)) = self.roots.get(root_entity) { if let Some(children) = maybe_children { self.stack.push((children, 0)); } return Some(( root_entity, 0, text.read_span(), text_font, color.0, *line_height, )); } return None; } // Span loop { let (children, idx) = self.stack.last_mut()?; loop { let Some(child) = children.get(*idx) else { break; }; // Increment to prep the next entity in this stack level. *idx += 1; let entity = *child; let Ok((span, text_font, color, line_height, maybe_children)) = self.spans.get(entity) else { continue; }; let depth = self.stack.len(); if let Some(children) = maybe_children { self.stack.push((children, 0)); } return Some(( entity, depth, span.read_span(), text_font, color.0, *line_height, )); } // All children at this stack entry have been iterated. self.stack.pop(); } } } impl<'a, R: TextRoot> Drop for TextSpanIter<'a, R> { fn drop(&mut self) { // Return the internal stack. let stack = core::mem::take(&mut self.stack); self.scratch.recover(stack); } } /// System parameter for reading and writing text spans in a text block. /// /// `R` is the root text component, and `S` is the text span component on children. #[derive(SystemParam)] pub struct TextWriter<'w, 's, R: TextRoot> { // This is a resource because two TextWriters can't run in parallel. scratch: ResMut<'w, TextIterScratch>, roots: Query< 'w, 's, ( &'static mut R, &'static mut TextFont, &'static mut TextColor, &'static mut LineHeight, ), Without<TextSpan>, >, spans: Query< 'w, 's, ( &'static mut TextSpan, &'static mut TextFont, &'static mut TextColor, &'static mut LineHeight, ), Without<R>, >, children: Query<'w, 's, &'static Children>, } impl<'w, 's, R: TextRoot> TextWriter<'w, 's, R> { /// Gets a mutable reference to a text span within a text block at a specific index in the flattened span list. pub fn get( &mut self, root_entity: Entity, index: usize, ) -> Option<( Entity, usize, Mut<'_, String>, Mut<'_, TextFont>, Mut<'_, TextColor>, Mut<'_, LineHeight>, )> { // Root if index == 0 { let (text, font, color, line_height) = self.roots.get_mut(root_entity).ok()?; return Some(( root_entity, 0, text.map_unchanged(|t| t.write_span()), font, color, line_height, )); } // Prep stack. let mut stack: Vec<(&Children, usize)> = self.scratch.take(); if let Ok(children) = self.children.get(root_entity) { stack.push((children, 0)); } // Span let mut count = 1; let (depth, entity) = 'l: loop { let Some((children, idx)) = stack.last_mut() else { self.scratch.recover(stack); return None; }; loop { let Some(child) = children.get(*idx) else { // All children at this stack entry have been iterated. stack.pop(); break; }; // Increment to prep the next entity in this stack level. *idx += 1; if !self.spans.contains(*child) { continue; }; count += 1; if count - 1 == index { let depth = stack.len(); self.scratch.recover(stack); break 'l (depth, *child); } if let Ok(children) = self.children.get(*child) { stack.push((children, 0)); break; } } }; // Note: We do this outside the loop due to borrow checker limitations. let (text, font, color, line_height) = self.spans.get_mut(entity).unwrap(); Some(( entity, depth, text.map_unchanged(|t| t.write_span()), font, color, line_height, )) } /// Gets the text value of a text span within a text block at a specific index in the flattened span list. pub fn get_text(&mut self, root_entity: Entity, index: usize) -> Option<Mut<'_, String>> { self.get(root_entity, index).map(|(_, _, text, ..)| text) } /// Gets the [`TextFont`] of a text span within a text block at a specific index in the flattened span list. pub fn get_font(&mut self, root_entity: Entity, index: usize) -> Option<Mut<'_, TextFont>> { self.get(root_entity, index).map(|(_, _, _, font, ..)| font) } /// Gets the [`TextColor`] of a text span within a text block at a specific index in the flattened span list. pub fn get_color(&mut self, root_entity: Entity, index: usize) -> Option<Mut<'_, TextColor>> { self.get(root_entity, index) .map(|(_, _, _, _, color, ..)| color) } /// Gets the [`LineHeight`] of a text span within a text block at a specific index in the flattened span list. pub fn get_line_height( &mut self, root_entity: Entity, index: usize, ) -> Option<Mut<'_, LineHeight>> { self.get(root_entity, index) .map(|(_, _, _, _, _, line_height)| line_height) } /// Gets the text value of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. pub fn text(&mut self, root_entity: Entity, index: usize) -> Mut<'_, String> { self.get_text(root_entity, index).unwrap() } /// Gets the [`TextFont`] of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. pub fn font(&mut self, root_entity: Entity, index: usize) -> Mut<'_, TextFont> { self.get_font(root_entity, index).unwrap() } /// Gets the [`TextColor`] of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. pub fn color(&mut self, root_entity: Entity, index: usize) -> Mut<'_, TextColor> { self.get_color(root_entity, index).unwrap() } /// Gets the [`LineHeight`] of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. pub fn line_height(&mut self, root_entity: Entity, index: usize) -> Mut<'_, LineHeight> { self.get_line_height(root_entity, index).unwrap() } /// Invokes a callback on each span in a text block, starting with the root entity. pub fn for_each( &mut self, root_entity: Entity, mut callback: impl FnMut( Entity, usize, Mut<String>, Mut<TextFont>, Mut<TextColor>, Mut<LineHeight>, ), ) { self.for_each_until(root_entity, |a, b, c, d, e, f| { (callback)(a, b, c, d, e, f); true }); } /// Invokes a callback on each span's string value in a text block, starting with the root entity. pub fn for_each_text(&mut self, root_entity: Entity, mut callback: impl FnMut(Mut<String>)) { self.for_each(root_entity, |_, _, text, _, _, _| { (callback)(text); }); } /// Invokes a callback on each span's [`TextFont`] in a text block, starting with the root entity. pub fn for_each_font(&mut self, root_entity: Entity, mut callback: impl FnMut(Mut<TextFont>)) { self.for_each(root_entity, |_, _, _, font, _, _| { (callback)(font); }); } /// Invokes a callback on each span's [`TextColor`] in a text block, starting with the root entity. pub fn for_each_color( &mut self, root_entity: Entity, mut callback: impl FnMut(Mut<TextColor>), ) { self.for_each(root_entity, |_, _, _, _, color, _| { (callback)(color); }); } /// Invokes a callback on each span's [`LineHeight`] in a text block, starting with the root entity. pub fn for_each_line_height( &mut self, root_entity: Entity, mut callback: impl FnMut(Mut<LineHeight>), ) { self.for_each(root_entity, |_, _, _, _, _, line_height| { (callback)(line_height); }); } /// Invokes a callback on each span in a text block, starting with the root entity. /// /// Traversal will stop when the callback returns `false`. // TODO: find a way to consolidate get and for_each_until, or provide a real iterator. Lifetime issues are challenging here. pub fn for_each_until( &mut self, root_entity: Entity, mut callback: impl FnMut( Entity, usize, Mut<String>, Mut<TextFont>, Mut<TextColor>, Mut<LineHeight>, ) -> bool, ) { // Root let Ok((text, font, color, line_height)) = self.roots.get_mut(root_entity) else { return; }; if !(callback)( root_entity, 0, text.map_unchanged(|t| t.write_span()), font, color, line_height, ) { return; } // Prep stack. let mut stack: Vec<(&Children, usize)> = self.scratch.take(); if let Ok(children) = self.children.get(root_entity) { stack.push((children, 0)); } // Span loop { let depth = stack.len(); let Some((children, idx)) = stack.last_mut() else { self.scratch.recover(stack); return; }; loop { let Some(child) = children.get(*idx) else { // All children at this stack entry have been iterated. stack.pop(); break; }; // Increment to prep the next entity in this stack level. *idx += 1; let entity = *child; let Ok((text, font, color, line_height)) = self.spans.get_mut(entity) else { continue; }; if !(callback)( entity, depth, text.map_unchanged(|t| t.write_span()), font, color, line_height, ) { self.scratch.recover(stack); return; } if let Ok(children) = self.children.get(entity) { stack.push((children, 0)); break; } } } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_text/src/font_atlas_set.rs
crates/bevy_text/src/font_atlas_set.rs
use crate::{FontAtlas, FontSmoothing}; use bevy_derive::{Deref, DerefMut}; use bevy_ecs::resource::Resource; use bevy_platform::collections::HashMap; use cosmic_text::fontdb::ID; /// Identifies the font atlases for a particular font in [`FontAtlasSet`] /// /// Allows an `f32` font size to be used as a key in a `HashMap`, by its binary representation. #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] pub struct FontAtlasKey { /// Font asset id pub id: ID, /// Font size via `f32::to_bits` pub font_size_bits: u32, /// Antialiasing method pub font_smoothing: FontSmoothing, } /// Set of rasterized fonts stored in [`FontAtlas`]es. #[derive(Debug, Default, Resource, Deref, DerefMut)] pub struct FontAtlasSet(HashMap<FontAtlasKey, Vec<FontAtlas>>); impl FontAtlasSet { /// Checks whether the given subpixel-offset glyph is contained in any of the [`FontAtlas`]es for the font identified by the given [`FontAtlasKey`]. pub fn has_glyph(&self, cache_key: cosmic_text::CacheKey, font_key: &FontAtlasKey) -> bool { self.get(font_key) .is_some_and(|font_atlas| font_atlas.iter().any(|atlas| atlas.has_glyph(cache_key))) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_sprite/src/lib.rs
crates/bevy_sprite/src/lib.rs
#![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")] #![cfg_attr(docsrs, feature(doc_cfg))] #![forbid(unsafe_code)] #![doc( html_logo_url = "https://bevy.org/assets/icon.png", html_favicon_url = "https://bevy.org/assets/icon.png" )] //! Provides 2D sprite functionality. extern crate alloc; #[cfg(feature = "bevy_picking")] mod picking_backend; mod sprite; #[cfg(feature = "bevy_text")] mod text2d; mod texture_slice; /// The sprite prelude. /// /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { #[cfg(feature = "bevy_picking")] #[doc(hidden)] pub use crate::picking_backend::{ SpritePickingCamera, SpritePickingMode, SpritePickingPlugin, SpritePickingSettings, }; #[cfg(feature = "bevy_text")] #[doc(hidden)] pub use crate::text2d::{Text2d, Text2dReader, Text2dWriter}; #[doc(hidden)] pub use crate::{ sprite::{Sprite, SpriteImageMode}, texture_slice::{BorderRect, SliceScaleMode, TextureSlice, TextureSlicer}, SpriteScalingMode, }; } use bevy_asset::Assets; use bevy_camera::{ primitives::{Aabb, MeshAabb}, visibility::NoFrustumCulling, visibility::VisibilitySystems, }; use bevy_mesh::{Mesh, Mesh2d}; #[cfg(feature = "bevy_picking")] pub use picking_backend::*; pub use sprite::*; #[cfg(feature = "bevy_text")] pub use text2d::*; pub use texture_slice::*; use bevy_app::prelude::*; use bevy_asset::prelude::AssetChanged; use bevy_camera::visibility::NoAutoAabb; use bevy_ecs::prelude::*; use bevy_image::{Image, TextureAtlasLayout, TextureAtlasPlugin}; use bevy_math::Vec2; /// Adds support for 2D sprites. #[derive(Default)] pub struct SpritePlugin; /// System set for sprite rendering. #[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)] pub enum SpriteSystems { ExtractSprites, ComputeSlices, } impl Plugin for SpritePlugin { fn build(&self, app: &mut App) { if !app.is_plugin_added::<TextureAtlasPlugin>() { app.add_plugins(TextureAtlasPlugin); } app.add_systems( PostUpdate, calculate_bounds_2d.in_set(VisibilitySystems::CalculateBounds), ); #[cfg(feature = "bevy_text")] app.add_systems( PostUpdate, ( bevy_text::detect_text_needs_rerender::<Text2d>, update_text2d_layout.after(bevy_camera::CameraUpdateSystems), calculate_bounds_text2d.in_set(VisibilitySystems::CalculateBounds), ) .chain() .after(bevy_text::load_font_assets_into_fontdb_system) .in_set(bevy_text::Text2dUpdateSystems) .after(bevy_app::AnimationSystems), ); #[cfg(feature = "bevy_picking")] app.add_plugins(SpritePickingPlugin); } } /// System calculating and inserting an [`Aabb`] component to entities with either: /// - a `Mesh2d` component, /// - a `Sprite` and `Handle<Image>` components, /// and without a [`NoFrustumCulling`] component. /// /// Used in system set [`VisibilitySystems::CalculateBounds`]. pub fn calculate_bounds_2d( mut commands: Commands, meshes: Res<Assets<Mesh>>, images: Res<Assets<Image>>, atlases: Res<Assets<TextureAtlasLayout>>, new_mesh_aabb: Query< (Entity, &Mesh2d), ( Without<Aabb>, Without<NoFrustumCulling>, Without<NoAutoAabb>, ), >, mut update_mesh_aabb: Query< (&Mesh2d, &mut Aabb), ( Or<(AssetChanged<Mesh2d>, Changed<Mesh2d>)>, Without<NoFrustumCulling>, Without<NoAutoAabb>, Without<Sprite>, // disjoint mutable query ), >, new_sprite_aabb: Query< (Entity, &Sprite, &Anchor), ( Without<Aabb>, Without<NoFrustumCulling>, Without<NoAutoAabb>, ), >, mut update_sprite_aabb: Query< (&Sprite, &mut Aabb, &Anchor), ( Or<(Changed<Sprite>, Changed<Anchor>)>, Without<NoFrustumCulling>, Without<NoAutoAabb>, Without<Mesh2d>, // disjoint mutable query ), >, ) { // New meshes require inserting a component for (entity, mesh_handle) in &new_mesh_aabb { if let Some(mesh) = meshes.get(mesh_handle) && let Some(aabb) = mesh.compute_aabb() { commands.entity(entity).try_insert(aabb); } } // Updated meshes can take the fast path with parallel component mutation update_mesh_aabb .par_iter_mut() .for_each(|(mesh_handle, mut aabb)| { if let Some(new_aabb) = meshes.get(mesh_handle).and_then(MeshAabb::compute_aabb) { aabb.set_if_neq(new_aabb); } }); // Sprite helper let sprite_size = |sprite: &Sprite| -> Option<Vec2> { sprite .custom_size .or_else(|| sprite.rect.map(|rect| rect.size())) .or_else(|| match &sprite.texture_atlas { // We default to the texture size for regular sprites None => images.get(&sprite.image).map(Image::size_f32), // We default to the drawn rect for atlas sprites Some(atlas) => atlas .texture_rect(&atlases) .map(|rect| rect.size().as_vec2()), }) }; // New sprites require inserting a component for (size, (entity, anchor)) in new_sprite_aabb .iter() .filter_map(|(entity, sprite, anchor)| sprite_size(sprite).zip(Some((entity, anchor)))) { let aabb = Aabb { center: (-anchor.as_vec() * size).extend(0.0).into(), half_extents: (0.5 * size).extend(0.0).into(), }; commands.entity(entity).try_insert(aabb); } // Updated sprites can take the fast path with parallel component mutation update_sprite_aabb .par_iter_mut() .for_each(|(sprite, mut aabb, anchor)| { if let Some(size) = sprite_size(sprite) { aabb.set_if_neq(Aabb { center: (-anchor.as_vec() * size).extend(0.0).into(), half_extents: (0.5 * size).extend(0.0).into(), }); } }); } #[cfg(test)] mod test { use super::*; use bevy_math::{Rect, Vec2, Vec3A}; #[test] fn calculate_bounds_2d_create_aabb_for_image_sprite_entity() { // Setup app let mut app = App::new(); // Add resources and get handle to image let mut image_assets = Assets::<Image>::default(); let image_handle = image_assets.add(Image::default()); app.insert_resource(image_assets); let mesh_assets = Assets::<Mesh>::default(); app.insert_resource(mesh_assets); let texture_atlas_assets = Assets::<TextureAtlasLayout>::default(); app.insert_resource(texture_atlas_assets); // Add system app.add_systems(Update, calculate_bounds_2d); // Add entities let entity = app.world_mut().spawn(Sprite::from_image(image_handle)).id(); // Verify that the entity does not have an AABB assert!(!app .world() .get_entity(entity) .expect("Could not find entity") .contains::<Aabb>()); // Run system app.update(); // Verify the AABB exists assert!(app .world() .get_entity(entity) .expect("Could not find entity") .contains::<Aabb>()); } #[test] fn calculate_bounds_2d_update_aabb_when_sprite_custom_size_changes_to_some() { // Setup app let mut app = App::new(); // Add resources and get handle to image let mut image_assets = Assets::<Image>::default(); let image_handle = image_assets.add(Image::default()); app.insert_resource(image_assets); let mesh_assets = Assets::<Mesh>::default(); app.insert_resource(mesh_assets); let texture_atlas_assets = Assets::<TextureAtlasLayout>::default(); app.insert_resource(texture_atlas_assets); // Add system app.add_systems(Update, calculate_bounds_2d); // Add entities let entity = app .world_mut() .spawn(Sprite { custom_size: Some(Vec2::ZERO), image: image_handle, ..Sprite::default() }) .id(); // Create initial AABB app.update(); // Get the initial AABB let first_aabb = *app .world() .get_entity(entity) .expect("Could not find entity") .get::<Aabb>() .expect("Could not find initial AABB"); // Change `custom_size` of sprite let mut binding = app .world_mut() .get_entity_mut(entity) .expect("Could not find entity"); let mut sprite = binding .get_mut::<Sprite>() .expect("Could not find sprite component of entity"); sprite.custom_size = Some(Vec2::ONE); // Re-run the `calculate_bounds_2d` system to get the new AABB app.update(); // Get the re-calculated AABB let second_aabb = *app .world() .get_entity(entity) .expect("Could not find entity") .get::<Aabb>() .expect("Could not find second AABB"); // Check that the AABBs are not equal assert_ne!(first_aabb, second_aabb); } #[test] fn calculate_bounds_2d_correct_aabb_for_sprite_with_custom_rect() { // Setup app let mut app = App::new(); // Add resources and get handle to image let mut image_assets = Assets::<Image>::default(); let image_handle = image_assets.add(Image::default()); app.insert_resource(image_assets); let mesh_assets = Assets::<Mesh>::default(); app.insert_resource(mesh_assets); let texture_atlas_assets = Assets::<TextureAtlasLayout>::default(); app.insert_resource(texture_atlas_assets); // Add system app.add_systems(Update, calculate_bounds_2d); // Add entities let entity = app .world_mut() .spawn(( Sprite { rect: Some(Rect::new(0., 0., 0.5, 1.)), image: image_handle, ..Sprite::default() }, Anchor::TOP_RIGHT, )) .id(); // Create AABB app.update(); // Get the AABB let aabb = *app .world_mut() .get_entity(entity) .expect("Could not find entity") .get::<Aabb>() .expect("Could not find AABB"); // Verify that the AABB is at the expected position assert_eq!(aabb.center, Vec3A::new(-0.25, -0.5, 0.)); // Verify that the AABB has the expected size assert_eq!(aabb.half_extents, Vec3A::new(0.25, 0.5, 0.)); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_sprite/src/text2d.rs
crates/bevy_sprite/src/text2d.rs
use crate::{Anchor, Sprite}; use bevy_asset::Assets; use bevy_camera::primitives::Aabb; use bevy_camera::visibility::{ self, NoFrustumCulling, RenderLayers, Visibility, VisibilityClass, VisibleEntities, }; use bevy_camera::Camera; use bevy_color::Color; use bevy_derive::{Deref, DerefMut}; use bevy_ecs::entity::EntityHashSet; use bevy_ecs::{ change_detection::{DetectChanges, Ref}, component::Component, entity::Entity, prelude::ReflectComponent, query::{Changed, Without}, system::{Commands, Local, Query, Res, ResMut}, }; use bevy_image::prelude::*; use bevy_math::{FloatOrd, Vec2, Vec3}; use bevy_reflect::{prelude::ReflectDefault, Reflect}; use bevy_text::{ ComputedTextBlock, CosmicFontSystem, Font, FontAtlasSet, FontHinting, LineBreak, LineHeight, SwashCache, TextBounds, TextColor, TextError, TextFont, TextLayout, TextLayoutInfo, TextPipeline, TextReader, TextRoot, TextSpanAccess, TextWriter, }; use bevy_transform::components::Transform; use core::any::TypeId; /// The top-level 2D text component. /// /// Adding `Text2d` to an entity will pull in required components for setting up 2d text. /// [Example usage.](https://github.com/bevyengine/bevy/blob/latest/examples/2d/text2d.rs) /// /// The string in this component is the first 'text span' in a hierarchy of text spans that are collected into /// a [`ComputedTextBlock`]. See `TextSpan` for the component used by children of entities with [`Text2d`]. /// /// With `Text2d` the `justify` field of [`TextLayout`] only affects the internal alignment of a block of text and not its /// relative position, which is controlled by the [`Anchor`] component. /// This means that for a block of text consisting of only one line that doesn't wrap, the `justify` field will have no effect. /// /// /// ``` /// # use bevy_asset::Handle; /// # use bevy_color::Color; /// # use bevy_color::palettes::basic::BLUE; /// # use bevy_ecs::world::World; /// # use bevy_text::{Font, Justify, TextLayout, TextFont, TextColor, TextSpan}; /// # use bevy_sprite::Text2d; /// # /// # let font_handle: Handle<Font> = Default::default(); /// # let mut world = World::default(); /// # /// // Basic usage. /// world.spawn(Text2d::new("hello world!")); /// /// // With non-default style. /// world.spawn(( /// Text2d::new("hello world!"), /// TextFont { /// font: font_handle.clone().into(), /// font_size: 60.0, /// ..Default::default() /// }, /// TextColor(BLUE.into()), /// )); /// /// // With text justification. /// world.spawn(( /// Text2d::new("hello world\nand bevy!"), /// TextLayout::new_with_justify(Justify::Center) /// )); /// /// // With spans /// world.spawn(Text2d::new("hello ")).with_children(|parent| { /// parent.spawn(TextSpan::new("world")); /// parent.spawn((TextSpan::new("!"), TextColor(BLUE.into()))); /// }); /// ``` #[derive(Component, Clone, Debug, Default, Deref, DerefMut, Reflect)] #[reflect(Component, Default, Debug, Clone)] #[require( TextLayout, TextFont, TextColor, LineHeight, TextBounds, Anchor, Visibility, VisibilityClass, Transform, // Disable hinting as `Text2d` text is not always pixel-aligned FontHinting::Disabled )] #[component(on_add = visibility::add_visibility_class::<Sprite>)] pub struct Text2d(pub String); impl Text2d { /// Makes a new 2d text component. pub fn new(text: impl Into<String>) -> Self { Self(text.into()) } } impl TextRoot for Text2d {} impl TextSpanAccess for Text2d { fn read_span(&self) -> &str { self.as_str() } fn write_span(&mut self) -> &mut String { &mut *self } } impl From<&str> for Text2d { fn from(value: &str) -> Self { Self(String::from(value)) } } impl From<String> for Text2d { fn from(value: String) -> Self { Self(value) } } /// 2d alias for [`TextReader`]. pub type Text2dReader<'w, 's> = TextReader<'w, 's, Text2d>; /// 2d alias for [`TextWriter`]. pub type Text2dWriter<'w, 's> = TextWriter<'w, 's, Text2d>; /// Adds a shadow behind `Text2d` text /// /// Use `TextShadow` for text drawn with `bevy_ui` #[derive(Component, Copy, Clone, Debug, PartialEq, Reflect)] #[reflect(Component, Default, Debug, Clone, PartialEq)] pub struct Text2dShadow { /// Shadow displacement /// With a value of zero the shadow will be hidden directly behind the text pub offset: Vec2, /// Color of the shadow pub color: Color, } impl Default for Text2dShadow { fn default() -> Self { Self { offset: Vec2::new(4., -4.), color: Color::BLACK, } } } /// Updates the layout and size information whenever the text or style is changed. /// This information is computed by the [`TextPipeline`] on insertion, then stored. /// /// ## World Resources /// /// [`ResMut<Assets<Image>>`](Assets<Image>) -- This system only adds new [`Image`] assets. /// It does not modify or observe existing ones. pub fn update_text2d_layout( mut target_scale_factors: Local<Vec<(f32, RenderLayers)>>, // Text2d entities from the previous frame which need to be reprocessed, usually because the font hadn't loaded yet. mut reprocess_queue: Local<EntityHashSet>, mut textures: ResMut<Assets<Image>>, fonts: Res<Assets<Font>>, camera_query: Query<(&Camera, &VisibleEntities, Option<&RenderLayers>)>, mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>, mut font_atlas_set: ResMut<FontAtlasSet>, mut text_pipeline: ResMut<TextPipeline>, mut text_query: Query<( Entity, Option<&RenderLayers>, Ref<TextLayout>, Ref<TextBounds>, &mut TextLayoutInfo, &mut ComputedTextBlock, Ref<FontHinting>, )>, mut text_reader: Text2dReader, mut font_system: ResMut<CosmicFontSystem>, mut swash_cache: ResMut<SwashCache>, ) { target_scale_factors.clear(); target_scale_factors.extend( camera_query .iter() .filter(|(_, visible_entities, _)| { !visible_entities.get(TypeId::of::<Sprite>()).is_empty() }) .filter_map(|(camera, _, maybe_camera_mask)| { camera.target_scaling_factor().map(|scale_factor| { (scale_factor, maybe_camera_mask.cloned().unwrap_or_default()) }) }), ); let mut previous_scale_factor = 0.; let mut previous_mask = &RenderLayers::none(); for (entity, maybe_entity_mask, block, bounds, mut text_layout_info, mut computed, hinting) in &mut text_query { let entity_mask = maybe_entity_mask.unwrap_or_default(); let scale_factor = if entity_mask == previous_mask && 0. < previous_scale_factor { previous_scale_factor } else { // `Text2d` only supports generating a single text layout per Text2d entity. If a `Text2d` entity has multiple // render targets with different scale factors, then we use the maximum of the scale factors. let Some((scale_factor, mask)) = target_scale_factors .iter() .filter(|(_, camera_mask)| camera_mask.intersects(entity_mask)) .max_by_key(|(scale_factor, _)| FloatOrd(*scale_factor)) else { continue; }; previous_scale_factor = *scale_factor; previous_mask = mask; *scale_factor }; let text_changed = scale_factor != text_layout_info.scale_factor || block.is_changed() || hinting.is_changed() || computed.needs_rerender() || (!reprocess_queue.is_empty() && reprocess_queue.remove(&entity)); if !(text_changed || bounds.is_changed()) { continue; } let text_bounds = TextBounds { width: if block.linebreak == LineBreak::NoWrap { None } else { bounds.width.map(|width| width * scale_factor) }, height: bounds.height.map(|height| height * scale_factor), }; if text_changed { match text_pipeline.update_buffer( &fonts, text_reader.iter(entity), block.linebreak, block.justify, text_bounds, scale_factor as f64, &mut computed, &mut font_system, *hinting, ) { Err(TextError::NoSuchFont) => { // There was an error processing the text layout. // Add this entity to the queue and reprocess it in the following frame reprocess_queue.insert(entity); continue; } Err( e @ (TextError::FailedToAddGlyph(_) | TextError::FailedToGetGlyphImage(_) | TextError::MissingAtlasLayout | TextError::MissingAtlasTexture | TextError::InconsistentAtlasState), ) => { panic!("Fatal error when processing text: {e}."); } Ok(()) => {} } } match text_pipeline.update_text_layout_info( &mut text_layout_info, &mut font_atlas_set, &mut texture_atlases, &mut textures, &mut computed, &mut font_system, &mut swash_cache, text_bounds, block.justify, ) { Err(TextError::NoSuchFont) => { // There was an error processing the text layout. // Add this entity to the queue and reprocess it in the following frame. reprocess_queue.insert(entity); continue; } Err( e @ (TextError::FailedToAddGlyph(_) | TextError::FailedToGetGlyphImage(_) | TextError::MissingAtlasLayout | TextError::MissingAtlasTexture | TextError::InconsistentAtlasState), ) => { panic!("Fatal error when processing text: {e}."); } Ok(()) => { text_layout_info.scale_factor = scale_factor; text_layout_info.size *= scale_factor.recip(); } } } } /// System calculating and inserting an [`Aabb`] component to entities with some /// [`TextLayoutInfo`] and [`Anchor`] components, and without a [`NoFrustumCulling`] component. /// /// Used in system set [`VisibilitySystems::CalculateBounds`](bevy_camera::visibility::VisibilitySystems::CalculateBounds). pub fn calculate_bounds_text2d( mut commands: Commands, mut text_to_update_aabb: Query< ( Entity, &TextLayoutInfo, &Anchor, &TextBounds, Option<&mut Aabb>, ), (Changed<TextLayoutInfo>, Without<NoFrustumCulling>), >, ) { for (entity, layout_info, anchor, text_bounds, aabb) in &mut text_to_update_aabb { let size = Vec2::new( text_bounds.width.unwrap_or(layout_info.size.x), text_bounds.height.unwrap_or(layout_info.size.y), ); let x1 = (Anchor::TOP_LEFT.0.x - anchor.as_vec().x) * size.x; let x2 = (Anchor::TOP_LEFT.0.x - anchor.as_vec().x + 1.) * size.x; let y1 = (Anchor::TOP_LEFT.0.y - anchor.as_vec().y - 1.) * size.y; let y2 = (Anchor::TOP_LEFT.0.y - anchor.as_vec().y) * size.y; let new_aabb = Aabb::from_min_max(Vec3::new(x1, y1, 0.), Vec3::new(x2, y2, 0.)); if let Some(mut aabb) = aabb { *aabb = new_aabb; } else { commands.entity(entity).try_insert(new_aabb); } } } #[cfg(test)] mod tests { use bevy_app::{App, Update}; use bevy_asset::{load_internal_binary_asset, Handle}; use bevy_camera::{ComputedCameraValues, RenderTargetInfo}; use bevy_ecs::schedule::IntoScheduleConfigs; use bevy_math::UVec2; use bevy_text::{detect_text_needs_rerender, TextIterScratch}; use super::*; const FIRST_TEXT: &str = "Sample text."; const SECOND_TEXT: &str = "Another, longer sample text."; fn setup() -> (App, Entity) { let mut app = App::new(); app.init_resource::<Assets<Font>>() .init_resource::<Assets<Image>>() .init_resource::<Assets<TextureAtlasLayout>>() .init_resource::<FontAtlasSet>() .init_resource::<TextPipeline>() .init_resource::<CosmicFontSystem>() .init_resource::<SwashCache>() .init_resource::<TextIterScratch>() .add_systems( Update, ( detect_text_needs_rerender::<Text2d>, update_text2d_layout, calculate_bounds_text2d, ) .chain(), ); let mut visible_entities = VisibleEntities::default(); visible_entities.push(Entity::PLACEHOLDER, TypeId::of::<Sprite>()); app.world_mut().spawn(( Camera { computed: ComputedCameraValues { target_info: Some(RenderTargetInfo { physical_size: UVec2::splat(1000), scale_factor: 1., }), ..Default::default() }, ..Default::default() }, visible_entities, )); // A font is needed to ensure the text is laid out with an actual size. load_internal_binary_asset!( app, Handle::default(), "../../bevy_text/src/FiraMono-subset.ttf", |bytes: &[u8], _path: String| { Font::try_from_bytes(bytes.to_vec()).unwrap() } ); let entity = app.world_mut().spawn(Text2d::new(FIRST_TEXT)).id(); (app, entity) } #[test] fn calculate_bounds_text2d_create_aabb() { let (mut app, entity) = setup(); assert!(!app .world() .get_entity(entity) .expect("Could not find entity") .contains::<Aabb>()); // Creates the AABB after text layouting. app.update(); let aabb = app .world() .get_entity(entity) .expect("Could not find entity") .get::<Aabb>() .expect("Text should have an AABB"); // Text2D AABB does not have a depth. assert_eq!(aabb.center.z, 0.0); assert_eq!(aabb.half_extents.z, 0.0); // AABB has an actual size. assert!(aabb.half_extents.x > 0.0 && aabb.half_extents.y > 0.0); } #[test] fn calculate_bounds_text2d_update_aabb() { let (mut app, entity) = setup(); // Creates the initial AABB after text layouting. app.update(); let first_aabb = *app .world() .get_entity(entity) .expect("Could not find entity") .get::<Aabb>() .expect("Could not find initial AABB"); let mut entity_ref = app .world_mut() .get_entity_mut(entity) .expect("Could not find entity"); *entity_ref .get_mut::<Text2d>() .expect("Missing Text2d on entity") = Text2d::new(SECOND_TEXT); // Recomputes the AABB. app.update(); let second_aabb = *app .world() .get_entity(entity) .expect("Could not find entity") .get::<Aabb>() .expect("Could not find second AABB"); // Check that the height is the same, but the width is greater. approx::assert_abs_diff_eq!(first_aabb.half_extents.y, second_aabb.half_extents.y); assert!(FIRST_TEXT.len() < SECOND_TEXT.len()); assert!(first_aabb.half_extents.x < second_aabb.half_extents.x); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_sprite/src/picking_backend.rs
crates/bevy_sprite/src/picking_backend.rs
//! A [`bevy_picking`] backend for sprites. Works for simple sprites and sprite atlases. Works for //! sprites with arbitrary transforms. //! //! By default, picking for sprites is based on pixel opacity. //! A sprite is picked only when a pointer is over an opaque pixel. //! Alternatively, you can configure picking to be based on sprite bounds. //! //! ## Implementation Notes //! //! - The `position` reported in `HitData` in world space, and the `normal` is a normalized //! vector provided by the target's `GlobalTransform::back()`. use crate::{Anchor, Sprite}; use bevy_app::prelude::*; use bevy_asset::prelude::*; use bevy_camera::{ visibility::{RenderLayers, ViewVisibility}, Camera, Projection, RenderTarget, }; use bevy_color::Alpha; use bevy_ecs::prelude::*; use bevy_image::prelude::*; use bevy_math::{prelude::*, FloatExt}; use bevy_picking::backend::prelude::*; use bevy_reflect::prelude::*; use bevy_transform::prelude::*; use bevy_window::PrimaryWindow; /// An optional component that marks cameras that should be used in the [`SpritePickingPlugin`]. /// /// Only needed if [`SpritePickingSettings::require_markers`] is set to `true`, and ignored /// otherwise. #[derive(Debug, Clone, Default, Component, Reflect)] #[reflect(Debug, Default, Component, Clone)] pub struct SpritePickingCamera; /// How should the [`SpritePickingPlugin`] handle picking and how should it handle transparent pixels #[derive(Debug, Clone, Copy, Reflect)] #[reflect(Debug, Clone)] pub enum SpritePickingMode { /// Even if a sprite is picked on a transparent pixel, it should still count within the backend. /// Only consider the rect of a given sprite. BoundingBox, /// Ignore any part of a sprite which has a lower alpha value than the threshold (inclusive) /// Threshold is given as an f32 representing the alpha value in a Bevy Color Value AlphaThreshold(f32), } /// Runtime settings for the [`SpritePickingPlugin`]. #[derive(Resource, Reflect)] #[reflect(Resource, Default)] pub struct SpritePickingSettings { /// When set to `true` sprite picking will only consider cameras marked with /// [`SpritePickingCamera`]. Defaults to `false`. /// Regardless of this setting, only sprites marked with [`Pickable`] will be considered. /// /// This setting is provided to give you fine-grained control over which cameras /// should be used by the sprite picking backend at runtime. pub require_markers: bool, /// Should the backend count transparent pixels as part of the sprite for picking purposes or should it use the bounding box of the sprite alone. /// /// Defaults to an inclusive alpha threshold of 0.1 pub picking_mode: SpritePickingMode, } impl Default for SpritePickingSettings { fn default() -> Self { Self { require_markers: false, picking_mode: SpritePickingMode::AlphaThreshold(0.1), } } } /// Enables the sprite picking backend, allowing you to click on, hover over and drag sprites. #[derive(Clone)] pub struct SpritePickingPlugin; impl Plugin for SpritePickingPlugin { fn build(&self, app: &mut App) { app.init_resource::<SpritePickingSettings>() .add_systems(PreUpdate, sprite_picking.in_set(PickingSystems::Backend)); } } fn sprite_picking( pointers: Query<(&PointerId, &PointerLocation)>, cameras: Query<( Entity, &Camera, &RenderTarget, &GlobalTransform, &Projection, Has<SpritePickingCamera>, Option<&RenderLayers>, )>, primary_window: Query<Entity, With<PrimaryWindow>>, images: Res<Assets<Image>>, texture_atlas_layout: Res<Assets<TextureAtlasLayout>>, settings: Res<SpritePickingSettings>, sprite_query: Query<( Entity, &Sprite, &GlobalTransform, &Anchor, &Pickable, &ViewVisibility, Option<&RenderLayers>, )>, mut pointer_hits_writer: MessageWriter<PointerHits>, ray_map: Res<RayMap>, ) { let mut sorted_sprites: Vec<_> = sprite_query .iter() .filter_map( |(entity, sprite, transform, anchor, pickable, vis, render_layers)| { if !transform.affine().is_nan() && vis.get() { Some((entity, sprite, transform, anchor, pickable, render_layers)) } else { None } }, ) .collect(); // radsort is a stable radix sort that performed better than `slice::sort_by_key` radsort::sort_by_key(&mut sorted_sprites, |(_, _, transform, _, _, _)| { -transform.translation().z }); let primary_window = primary_window.single().ok(); let pick_sets = ray_map.iter().flat_map(|(ray_id, ray)| { let mut blocked = false; let Ok(( cam_entity, camera, render_target, cam_transform, Projection::Orthographic(cam_ortho), cam_can_pick, cam_render_layers, )) = cameras.get(ray_id.camera) else { return None; }; let marker_requirement = !settings.require_markers || cam_can_pick; if !camera.is_active || !marker_requirement { return None; } let location = pointers.iter().find_map(|(id, loc)| { if *id == ray_id.pointer { return loc.location.as_ref(); } None })?; if render_target .normalize(primary_window) .is_none_or(|x| x != location.target) { return None; } let viewport_pos = location.position; if let Some(viewport) = camera.logical_viewport_rect() && !viewport.contains(viewport_pos) { // The pointer is outside the viewport, skip it return None; } let cursor_ray_len = cam_ortho.far - cam_ortho.near; let cursor_ray_end = ray.origin + ray.direction * cursor_ray_len; let picks: Vec<(Entity, HitData)> = sorted_sprites .iter() .copied() .filter_map( |(entity, sprite, sprite_transform, anchor, pickable, sprite_render_layers)| { if blocked { return None; } // Filter out sprites based on whether they share RenderLayers with the current // ray's associated camera. // Any entity without a RenderLayers component will by default be // on RenderLayers::layer(0) only. if !cam_render_layers .unwrap_or_default() .intersects(sprite_render_layers.unwrap_or_default()) { return None; } // Transform cursor line segment to sprite coordinate system let world_to_sprite = sprite_transform.affine().inverse(); let cursor_start_sprite = world_to_sprite.transform_point3(ray.origin); let cursor_end_sprite = world_to_sprite.transform_point3(cursor_ray_end); // Find where the cursor segment intersects the plane Z=0 (which is the sprite's // plane in sprite-local space). It may not intersect if, for example, we're // viewing the sprite side-on if cursor_start_sprite.z == cursor_end_sprite.z { // Cursor ray is parallel to the sprite and misses it return None; } let lerp_factor = f32::inverse_lerp(cursor_start_sprite.z, cursor_end_sprite.z, 0.0); if !(0.0..=1.0).contains(&lerp_factor) { // Lerp factor is out of range, meaning that while an infinite line cast by // the cursor would intersect the sprite, the sprite is not between the // camera's near and far planes return None; } // Otherwise we can interpolate the xy of the start and end positions by the // lerp factor to get the cursor position in sprite space! let cursor_pos_sprite = cursor_start_sprite .lerp(cursor_end_sprite, lerp_factor) .xy(); let Ok(cursor_pixel_space) = sprite.compute_pixel_space_point( cursor_pos_sprite, *anchor, &images, &texture_atlas_layout, ) else { return None; }; // Since the pixel space coordinate is `Ok`, we know the cursor is in the bounds of // the sprite. let cursor_in_valid_pixels_of_sprite = 'valid_pixel: { match settings.picking_mode { SpritePickingMode::AlphaThreshold(cutoff) => { let Some(image) = images.get(&sprite.image) else { // [`Sprite::from_color`] returns a defaulted handle. // This handle doesn't return a valid image, so returning false here would make picking "color sprites" impossible break 'valid_pixel true; }; // grab pixel and check alpha let Ok(color) = image.get_color_at( cursor_pixel_space.x as u32, cursor_pixel_space.y as u32, ) else { // We don't know how to interpret the pixel. break 'valid_pixel false; }; // Check the alpha is above the cutoff. color.alpha() > cutoff } SpritePickingMode::BoundingBox => true, } }; blocked = cursor_in_valid_pixels_of_sprite && pickable.should_block_lower; cursor_in_valid_pixels_of_sprite.then(|| { let hit_pos_world = sprite_transform.transform_point(cursor_pos_sprite.extend(0.0)); // Transform point from world to camera space to get the Z distance let hit_pos_cam = cam_transform .affine() .inverse() .transform_point3(hit_pos_world); // HitData requires a depth as calculated from the camera's near clipping plane let depth = -cam_ortho.near - hit_pos_cam.z; ( entity, HitData::new( cam_entity, depth, Some(hit_pos_world), Some(*sprite_transform.back()), ), ) }) }, ) .collect(); Some((ray_id.pointer, picks, camera.order)) }); pick_sets.for_each(|(pointer, picks, order)| { pointer_hits_writer.write(PointerHits::new(pointer, picks, order as f32)); }); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_sprite/src/sprite.rs
crates/bevy_sprite/src/sprite.rs
use bevy_asset::{AsAssetId, AssetId, Assets, Handle}; use bevy_camera::visibility::{self, Visibility, VisibilityClass}; use bevy_color::Color; use bevy_derive::{Deref, DerefMut}; use bevy_ecs::{component::Component, reflect::ReflectComponent}; use bevy_image::{Image, TextureAtlas, TextureAtlasLayout}; use bevy_math::{Rect, UVec2, Vec2}; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_transform::components::Transform; use crate::TextureSlicer; /// Describes a sprite to be rendered to a 2D camera #[derive(Component, Debug, Default, Clone, Reflect)] #[require(Transform, Visibility, VisibilityClass, Anchor)] #[reflect(Component, Default, Debug, Clone)] #[component(on_add = visibility::add_visibility_class::<Sprite>)] pub struct Sprite { /// The image used to render the sprite pub image: Handle<Image>, /// The (optional) texture atlas used to render the sprite pub texture_atlas: Option<TextureAtlas>, /// The sprite's color tint pub color: Color, /// Flip the sprite along the `X` axis pub flip_x: bool, /// Flip the sprite along the `Y` axis pub flip_y: bool, /// An optional custom size for the sprite that will be used when rendering, instead of the size /// of the sprite's image pub custom_size: Option<Vec2>, /// An optional rectangle representing the region of the sprite's image to render, instead of rendering /// the full image. This is an easy one-off alternative to using a [`TextureAtlas`]. /// /// When used with a [`TextureAtlas`], the rect /// is offset by the atlas's minimal (top-left) corner position. pub rect: Option<Rect>, /// How the sprite's image will be scaled. pub image_mode: SpriteImageMode, } impl Sprite { /// Create a Sprite with a custom size pub fn sized(custom_size: Vec2) -> Self { Sprite { custom_size: Some(custom_size), ..Default::default() } } /// Create a sprite from an image pub fn from_image(image: Handle<Image>) -> Self { Self { image, ..Default::default() } } /// Create a sprite from an image, with an associated texture atlas pub fn from_atlas_image(image: Handle<Image>, atlas: TextureAtlas) -> Self { Self { image, texture_atlas: Some(atlas), ..Default::default() } } /// Create a sprite from a solid color pub fn from_color(color: impl Into<Color>, size: Vec2) -> Self { Self { color: color.into(), custom_size: Some(size), ..Default::default() } } /// Computes the pixel point where `point_relative_to_sprite` is sampled /// from in this sprite. `point_relative_to_sprite` must be in the sprite's /// local frame. Returns an Ok if the point is inside the bounds of the /// sprite (not just the image), and returns an Err otherwise. pub fn compute_pixel_space_point( &self, point_relative_to_sprite: Vec2, anchor: Anchor, images: &Assets<Image>, texture_atlases: &Assets<TextureAtlasLayout>, ) -> Result<Vec2, Vec2> { let image_size = images .get(&self.image) .map(Image::size) .unwrap_or(UVec2::ONE); let atlas_rect = self .texture_atlas .as_ref() .and_then(|s| s.texture_rect(texture_atlases)) .map(|r| r.as_rect()); let texture_rect = match (atlas_rect, self.rect) { (None, None) => Rect::new(0.0, 0.0, image_size.x as f32, image_size.y as f32), (None, Some(sprite_rect)) => sprite_rect, (Some(atlas_rect), None) => atlas_rect, (Some(atlas_rect), Some(mut sprite_rect)) => { // Make the sprite rect relative to the atlas rect. sprite_rect.min += atlas_rect.min; sprite_rect.max += atlas_rect.min; sprite_rect } }; let sprite_size = self.custom_size.unwrap_or_else(|| texture_rect.size()); let sprite_center = -anchor.as_vec() * sprite_size; let mut point_relative_to_sprite_center = point_relative_to_sprite - sprite_center; if self.flip_x { point_relative_to_sprite_center.x *= -1.0; } // Texture coordinates start at the top left, whereas world coordinates start at the bottom // left. So flip by default, and then don't flip if `flip_y` is set. if !self.flip_y { point_relative_to_sprite_center.y *= -1.0; } if sprite_size.x == 0.0 || sprite_size.y == 0.0 { return Err(point_relative_to_sprite_center); } let sprite_to_texture_ratio = { let texture_size = texture_rect.size(); Vec2::new( texture_size.x / sprite_size.x, texture_size.y / sprite_size.y, ) }; let point_relative_to_texture = point_relative_to_sprite_center * sprite_to_texture_ratio + texture_rect.center(); // TODO: Support `SpriteImageMode`. if texture_rect.contains(point_relative_to_texture) { Ok(point_relative_to_texture) } else { Err(point_relative_to_texture) } } } impl From<Handle<Image>> for Sprite { fn from(image: Handle<Image>) -> Self { Self::from_image(image) } } impl AsAssetId for Sprite { type Asset = Image; fn as_asset_id(&self) -> AssetId<Self::Asset> { self.image.id() } } /// Controls how the image is altered when scaled. #[derive(Default, Debug, Clone, Reflect, PartialEq)] #[reflect(Debug, Default, Clone)] pub enum SpriteImageMode { /// The sprite will take on the size of the image by default, and will be stretched or shrunk if [`Sprite::custom_size`] is set. #[default] Auto, /// The texture will be scaled to fit the rect bounds defined in [`Sprite::custom_size`]. /// Otherwise no scaling will be applied. Scale(SpriteScalingMode), /// The texture will be cut in 9 slices, keeping the texture in proportions on resize Sliced(TextureSlicer), /// The texture will be repeated if stretched beyond `stretched_value` Tiled { /// Should the image repeat horizontally tile_x: bool, /// Should the image repeat vertically tile_y: bool, /// The texture will repeat when the ratio between the *drawing dimensions* of texture and the /// *original texture size* are above this value. stretch_value: f32, }, } impl SpriteImageMode { /// Returns true if this mode uses slices internally ([`SpriteImageMode::Sliced`] or [`SpriteImageMode::Tiled`]) #[inline] pub fn uses_slices(&self) -> bool { matches!( self, SpriteImageMode::Sliced(..) | SpriteImageMode::Tiled { .. } ) } /// Returns [`SpriteScalingMode`] if scale is presented or [`Option::None`] otherwise. #[inline] #[must_use] pub const fn scale(&self) -> Option<SpriteScalingMode> { if let SpriteImageMode::Scale(scale) = self { Some(*scale) } else { None } } } /// Represents various modes for proportional scaling of a texture. /// /// Can be used in [`SpriteImageMode::Scale`]. #[derive(Debug, Clone, Copy, PartialEq, Default, Reflect)] #[reflect(Debug, Default, Clone)] pub enum SpriteScalingMode { /// Scale the texture uniformly (maintain the texture's aspect ratio) /// so that both dimensions (width and height) of the texture will be equal /// to or larger than the corresponding dimension of the target rectangle. /// Fill sprite with a centered texture. #[default] FillCenter, /// Scales the texture to fill the target rectangle while maintaining its aspect ratio. /// One dimension of the texture will match the rectangle's size, /// while the other dimension may exceed it. /// The exceeding portion is aligned to the start: /// * Horizontal overflow is left-aligned if the width exceeds the rectangle. /// * Vertical overflow is top-aligned if the height exceeds the rectangle. FillStart, /// Scales the texture to fill the target rectangle while maintaining its aspect ratio. /// One dimension of the texture will match the rectangle's size, /// while the other dimension may exceed it. /// The exceeding portion is aligned to the end: /// * Horizontal overflow is right-aligned if the width exceeds the rectangle. /// * Vertical overflow is bottom-aligned if the height exceeds the rectangle. FillEnd, /// Scaling the texture will maintain the original aspect ratio /// and ensure that the original texture fits entirely inside the rect. /// At least one axis (x or y) will fit exactly. The result is centered inside the rect. FitCenter, /// Scaling the texture will maintain the original aspect ratio /// and ensure that the original texture fits entirely inside rect. /// At least one axis (x or y) will fit exactly. /// Aligns the result to the left and top edges of rect. FitStart, /// Scaling the texture will maintain the original aspect ratio /// and ensure that the original texture fits entirely inside rect. /// At least one axis (x or y) will fit exactly. /// Aligns the result to the right and bottom edges of rect. FitEnd, } /// Normalized (relative to its size) offset of a 2d renderable entity from its [`Transform`]. #[derive(Component, Debug, Clone, Copy, PartialEq, Deref, DerefMut, Reflect)] #[reflect(Component, Default, Debug, PartialEq, Clone)] #[doc(alias = "pivot")] pub struct Anchor(pub Vec2); impl Anchor { pub const BOTTOM_LEFT: Self = Self(Vec2::new(-0.5, -0.5)); pub const BOTTOM_CENTER: Self = Self(Vec2::new(0.0, -0.5)); pub const BOTTOM_RIGHT: Self = Self(Vec2::new(0.5, -0.5)); pub const CENTER_LEFT: Self = Self(Vec2::new(-0.5, 0.0)); pub const CENTER: Self = Self(Vec2::ZERO); pub const CENTER_RIGHT: Self = Self(Vec2::new(0.5, 0.0)); pub const TOP_LEFT: Self = Self(Vec2::new(-0.5, 0.5)); pub const TOP_CENTER: Self = Self(Vec2::new(0.0, 0.5)); pub const TOP_RIGHT: Self = Self(Vec2::new(0.5, 0.5)); pub fn as_vec(&self) -> Vec2 { self.0 } } impl Default for Anchor { fn default() -> Self { Self::CENTER } } impl From<Vec2> for Anchor { fn from(value: Vec2) -> Self { Self(value) } } #[cfg(test)] mod tests { use bevy_asset::{Assets, RenderAssetUsages}; use bevy_color::Color; use bevy_image::{Image, ToExtents}; use bevy_image::{TextureAtlas, TextureAtlasLayout}; use bevy_math::{Rect, URect, UVec2, Vec2}; use wgpu_types::{TextureDimension, TextureFormat}; use crate::Anchor; use super::Sprite; /// Makes a new image of the specified size. fn make_image(size: UVec2) -> Image { Image::new_fill( size.to_extents(), TextureDimension::D2, &[0, 0, 0, 255], TextureFormat::Rgba8Unorm, RenderAssetUsages::all(), ) } #[test] fn compute_pixel_space_point_for_regular_sprite() { let mut image_assets = Assets::<Image>::default(); let texture_atlas_assets = Assets::<TextureAtlasLayout>::default(); let image = image_assets.add(make_image(UVec2::new(5, 10))); let sprite = Sprite { image, ..Default::default() }; let compute = |point| { sprite.compute_pixel_space_point( point, Anchor::default(), &image_assets, &texture_atlas_assets, ) }; assert_eq!(compute(Vec2::new(-2.0, -4.5)), Ok(Vec2::new(0.5, 9.5))); assert_eq!(compute(Vec2::new(0.0, 0.0)), Ok(Vec2::new(2.5, 5.0))); assert_eq!(compute(Vec2::new(0.0, 4.5)), Ok(Vec2::new(2.5, 0.5))); assert_eq!(compute(Vec2::new(3.0, 0.0)), Err(Vec2::new(5.5, 5.0))); assert_eq!(compute(Vec2::new(-3.0, 0.0)), Err(Vec2::new(-0.5, 5.0))); } #[test] fn compute_pixel_space_point_for_color_sprite() { let image_assets = Assets::<Image>::default(); let texture_atlas_assets = Assets::<TextureAtlasLayout>::default(); // This also tests the `custom_size` field. let sprite = Sprite::from_color(Color::BLACK, Vec2::new(50.0, 100.0)); let compute = |point| { sprite .compute_pixel_space_point( point, Anchor::default(), &image_assets, &texture_atlas_assets, ) // Round to remove floating point errors. .map(|x| (x * 1e5).round() / 1e5) .map_err(|x| (x * 1e5).round() / 1e5) }; assert_eq!(compute(Vec2::new(-20.0, -40.0)), Ok(Vec2::new(0.1, 0.9))); assert_eq!(compute(Vec2::new(0.0, 10.0)), Ok(Vec2::new(0.5, 0.4))); assert_eq!(compute(Vec2::new(75.0, 100.0)), Err(Vec2::new(2.0, -0.5))); assert_eq!(compute(Vec2::new(-75.0, -100.0)), Err(Vec2::new(-1.0, 1.5))); assert_eq!(compute(Vec2::new(-30.0, -40.0)), Err(Vec2::new(-0.1, 0.9))); } #[test] fn compute_pixel_space_point_for_sprite_with_anchor_bottom_left() { let mut image_assets = Assets::<Image>::default(); let texture_atlas_assets = Assets::<TextureAtlasLayout>::default(); let image = image_assets.add(make_image(UVec2::new(5, 10))); let sprite = Sprite { image, ..Default::default() }; let anchor = Anchor::BOTTOM_LEFT; let compute = |point| { sprite.compute_pixel_space_point(point, anchor, &image_assets, &texture_atlas_assets) }; assert_eq!(compute(Vec2::new(0.5, 9.5)), Ok(Vec2::new(0.5, 0.5))); assert_eq!(compute(Vec2::new(2.5, 5.0)), Ok(Vec2::new(2.5, 5.0))); assert_eq!(compute(Vec2::new(2.5, 9.5)), Ok(Vec2::new(2.5, 0.5))); assert_eq!(compute(Vec2::new(5.5, 5.0)), Err(Vec2::new(5.5, 5.0))); assert_eq!(compute(Vec2::new(-0.5, 5.0)), Err(Vec2::new(-0.5, 5.0))); } #[test] fn compute_pixel_space_point_for_sprite_with_anchor_top_right() { let mut image_assets = Assets::<Image>::default(); let texture_atlas_assets = Assets::<TextureAtlasLayout>::default(); let image = image_assets.add(make_image(UVec2::new(5, 10))); let sprite = Sprite { image, ..Default::default() }; let anchor = Anchor::TOP_RIGHT; let compute = |point| { sprite.compute_pixel_space_point(point, anchor, &image_assets, &texture_atlas_assets) }; assert_eq!(compute(Vec2::new(-4.5, -0.5)), Ok(Vec2::new(0.5, 0.5))); assert_eq!(compute(Vec2::new(-2.5, -5.0)), Ok(Vec2::new(2.5, 5.0))); assert_eq!(compute(Vec2::new(-2.5, -0.5)), Ok(Vec2::new(2.5, 0.5))); assert_eq!(compute(Vec2::new(0.5, -5.0)), Err(Vec2::new(5.5, 5.0))); assert_eq!(compute(Vec2::new(-5.5, -5.0)), Err(Vec2::new(-0.5, 5.0))); } #[test] fn compute_pixel_space_point_for_sprite_with_anchor_flip_x() { let mut image_assets = Assets::<Image>::default(); let texture_atlas_assets = Assets::<TextureAtlasLayout>::default(); let image = image_assets.add(make_image(UVec2::new(5, 10))); let sprite = Sprite { image, flip_x: true, ..Default::default() }; let anchor = Anchor::BOTTOM_LEFT; let compute = |point| { sprite.compute_pixel_space_point(point, anchor, &image_assets, &texture_atlas_assets) }; assert_eq!(compute(Vec2::new(0.5, 9.5)), Ok(Vec2::new(4.5, 0.5))); assert_eq!(compute(Vec2::new(2.5, 5.0)), Ok(Vec2::new(2.5, 5.0))); assert_eq!(compute(Vec2::new(2.5, 9.5)), Ok(Vec2::new(2.5, 0.5))); assert_eq!(compute(Vec2::new(5.5, 5.0)), Err(Vec2::new(-0.5, 5.0))); assert_eq!(compute(Vec2::new(-0.5, 5.0)), Err(Vec2::new(5.5, 5.0))); } #[test] fn compute_pixel_space_point_for_sprite_with_anchor_flip_y() { let mut image_assets = Assets::<Image>::default(); let texture_atlas_assets = Assets::<TextureAtlasLayout>::default(); let image = image_assets.add(make_image(UVec2::new(5, 10))); let sprite = Sprite { image, flip_y: true, ..Default::default() }; let anchor = Anchor::TOP_RIGHT; let compute = |point| { sprite.compute_pixel_space_point(point, anchor, &image_assets, &texture_atlas_assets) }; assert_eq!(compute(Vec2::new(-4.5, -0.5)), Ok(Vec2::new(0.5, 9.5))); assert_eq!(compute(Vec2::new(-2.5, -5.0)), Ok(Vec2::new(2.5, 5.0))); assert_eq!(compute(Vec2::new(-2.5, -0.5)), Ok(Vec2::new(2.5, 9.5))); assert_eq!(compute(Vec2::new(0.5, -5.0)), Err(Vec2::new(5.5, 5.0))); assert_eq!(compute(Vec2::new(-5.5, -5.0)), Err(Vec2::new(-0.5, 5.0))); } #[test] fn compute_pixel_space_point_for_sprite_with_rect() { let mut image_assets = Assets::<Image>::default(); let texture_atlas_assets = Assets::<TextureAtlasLayout>::default(); let image = image_assets.add(make_image(UVec2::new(5, 10))); let sprite = Sprite { image, rect: Some(Rect::new(1.5, 3.0, 3.0, 9.5)), ..Default::default() }; let anchor = Anchor::BOTTOM_LEFT; let compute = |point| { sprite.compute_pixel_space_point(point, anchor, &image_assets, &texture_atlas_assets) }; assert_eq!(compute(Vec2::new(0.5, 0.5)), Ok(Vec2::new(2.0, 9.0))); // The pixel is outside the rect, but is still a valid pixel in the image. assert_eq!(compute(Vec2::new(2.0, 2.5)), Err(Vec2::new(3.5, 7.0))); } #[test] fn compute_pixel_space_point_for_texture_atlas_sprite() { let mut image_assets = Assets::<Image>::default(); let mut texture_atlas_assets = Assets::<TextureAtlasLayout>::default(); let image = image_assets.add(make_image(UVec2::new(5, 10))); let texture_atlas = texture_atlas_assets.add(TextureAtlasLayout { size: UVec2::new(5, 10), textures: vec![URect::new(1, 1, 4, 4)], }); let sprite = Sprite { image, texture_atlas: Some(TextureAtlas { layout: texture_atlas, index: 0, }), ..Default::default() }; let anchor = Anchor::BOTTOM_LEFT; let compute = |point| { sprite.compute_pixel_space_point(point, anchor, &image_assets, &texture_atlas_assets) }; assert_eq!(compute(Vec2::new(0.5, 0.5)), Ok(Vec2::new(1.5, 3.5))); // The pixel is outside the texture atlas, but is still a valid pixel in the image. assert_eq!(compute(Vec2::new(4.0, 2.5)), Err(Vec2::new(5.0, 1.5))); } #[test] fn compute_pixel_space_point_for_texture_atlas_sprite_with_rect() { let mut image_assets = Assets::<Image>::default(); let mut texture_atlas_assets = Assets::<TextureAtlasLayout>::default(); let image = image_assets.add(make_image(UVec2::new(5, 10))); let texture_atlas = texture_atlas_assets.add(TextureAtlasLayout { size: UVec2::new(5, 10), textures: vec![URect::new(1, 1, 4, 4)], }); let sprite = Sprite { image, texture_atlas: Some(TextureAtlas { layout: texture_atlas, index: 0, }), // The rect is relative to the texture atlas sprite. rect: Some(Rect::new(1.5, 1.5, 3.0, 3.0)), ..Default::default() }; let anchor = Anchor::BOTTOM_LEFT; let compute = |point| { sprite.compute_pixel_space_point(point, anchor, &image_assets, &texture_atlas_assets) }; assert_eq!(compute(Vec2::new(0.5, 0.5)), Ok(Vec2::new(3.0, 3.5))); // The pixel is outside the texture atlas, but is still a valid pixel in the image. assert_eq!(compute(Vec2::new(4.0, 2.5)), Err(Vec2::new(6.5, 1.5))); } #[test] fn compute_pixel_space_point_for_sprite_with_custom_size_and_rect() { let mut image_assets = Assets::<Image>::default(); let texture_atlas_assets = Assets::<TextureAtlasLayout>::default(); let image = image_assets.add(make_image(UVec2::new(5, 10))); let sprite = Sprite { image, custom_size: Some(Vec2::new(100.0, 50.0)), rect: Some(Rect::new(0.0, 0.0, 5.0, 5.0)), ..Default::default() }; let compute = |point| { sprite.compute_pixel_space_point( point, Anchor::default(), &image_assets, &texture_atlas_assets, ) }; assert_eq!(compute(Vec2::new(30.0, 15.0)), Ok(Vec2::new(4.0, 1.0))); assert_eq!(compute(Vec2::new(-10.0, -15.0)), Ok(Vec2::new(2.0, 4.0))); // The pixel is outside the texture atlas, but is still a valid pixel in the image. assert_eq!(compute(Vec2::new(0.0, 35.0)), Err(Vec2::new(2.5, -1.0))); } #[test] fn compute_pixel_space_point_for_sprite_with_zero_custom_size() { let mut image_assets = Assets::<Image>::default(); let texture_atlas_assets = Assets::<TextureAtlasLayout>::default(); let image = image_assets.add(make_image(UVec2::new(5, 10))); let sprite = Sprite { image, custom_size: Some(Vec2::new(0.0, 0.0)), ..Default::default() }; let compute = |point| { sprite.compute_pixel_space_point( point, Anchor::default(), &image_assets, &texture_atlas_assets, ) }; assert_eq!(compute(Vec2::new(30.0, 15.0)), Err(Vec2::new(30.0, -15.0))); assert_eq!( compute(Vec2::new(-10.0, -15.0)), Err(Vec2::new(-10.0, 15.0)) ); // The pixel is outside the texture atlas, but is still a valid pixel in the image. assert_eq!(compute(Vec2::new(0.0, 35.0)), Err(Vec2::new(0.0, -35.0))); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_sprite/src/texture_slice/border_rect.rs
crates/bevy_sprite/src/texture_slice/border_rect.rs
use bevy_math::Vec2; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; /// Defines border insets that shrink a rectangle from its minimum and maximum corners. /// /// This struct is used to represent thickness or offsets from the four edges /// of a rectangle, with values increasing inwards. #[derive(Default, Copy, Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq, Default)] pub struct BorderRect { /// Inset applied to the rectangle’s minimum corner pub min_inset: Vec2, /// Inset applied to the rectangle’s maximum corner pub max_inset: Vec2, } impl BorderRect { /// An empty border with zero thickness along each edge pub const ZERO: Self = Self::all(0.); /// Creates a border with the same `inset` along each edge #[must_use] #[inline] pub const fn all(inset: f32) -> Self { Self { min_inset: Vec2::splat(inset), max_inset: Vec2::splat(inset), } } /// Creates a new border with the `min.x` and `max.x` insets equal to `horizontal`, and the `min.y` and `max.y` insets equal to `vertical`. #[must_use] #[inline] pub const fn axes(horizontal: f32, vertical: f32) -> Self { let insets = Vec2::new(horizontal, vertical); Self { min_inset: insets, max_inset: insets, } } } impl From<f32> for BorderRect { fn from(inset: f32) -> Self { Self::all(inset) } } impl From<[f32; 4]> for BorderRect { fn from([min_x, max_x, min_y, max_y]: [f32; 4]) -> Self { Self { min_inset: Vec2::new(min_x, min_y), max_inset: Vec2::new(max_x, max_y), } } } impl core::ops::Add for BorderRect { type Output = Self; fn add(mut self, rhs: Self) -> Self::Output { self.min_inset += rhs.min_inset; self.max_inset += rhs.max_inset; self } } impl core::ops::Sub for BorderRect { type Output = Self; fn sub(mut self, rhs: Self) -> Self::Output { self.min_inset -= rhs.min_inset; self.max_inset -= rhs.max_inset; self } } impl core::ops::Mul<f32> for BorderRect { type Output = Self; fn mul(mut self, rhs: f32) -> Self::Output { self.min_inset *= rhs; self.max_inset *= rhs; self } } impl core::ops::Div<f32> for BorderRect { type Output = Self; fn div(mut self, rhs: f32) -> Self::Output { self.min_inset /= rhs; self.max_inset /= rhs; self } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_sprite/src/texture_slice/mod.rs
crates/bevy_sprite/src/texture_slice/mod.rs
mod border_rect; mod slicer; use bevy_math::{Rect, Vec2}; pub use border_rect::BorderRect; pub use slicer::{SliceScaleMode, TextureSlicer}; /// Single texture slice, representing a texture rect to draw in a given area #[derive(Debug, Clone, PartialEq)] pub struct TextureSlice { /// texture area to draw pub texture_rect: Rect, /// slice draw size pub draw_size: Vec2, /// offset of the slice pub offset: Vec2, } impl TextureSlice { /// Transforms the given slice in a collection of tiled subdivisions. /// /// # Arguments /// /// * `stretch_value` - The slice will repeat when the ratio between the *drawing dimensions* of texture and the /// *original texture size* (rect) are above `stretch_value`. /// * `tile_x` - should the slice be tiled horizontally /// * `tile_y` - should the slice be tiled vertically #[must_use] pub fn tiled(self, stretch_value: f32, (tile_x, tile_y): (bool, bool)) -> Vec<Self> { if !tile_x && !tile_y { return vec![self]; } let stretch_value = stretch_value.max(0.001); let rect_size = self.texture_rect.size(); // Each tile expected size let expected_size = Vec2::new( if tile_x { // No slice should be less than 1 pixel wide (rect_size.x * stretch_value).max(1.0) } else { self.draw_size.x }, if tile_y { // No slice should be less than 1 pixel high (rect_size.y * stretch_value).max(1.0) } else { self.draw_size.y }, ) .min(self.draw_size); let mut slices = Vec::new(); let base_offset = Vec2::new( -self.draw_size.x / 2.0, self.draw_size.y / 2.0, // Start from top ); let mut offset = base_offset; let mut remaining_columns = self.draw_size.y; while remaining_columns > 0.0 { let size_y = expected_size.y.min(remaining_columns); offset.x = base_offset.x; offset.y -= size_y / 2.0; let mut remaining_rows = self.draw_size.x; while remaining_rows > 0.0 { let size_x = expected_size.x.min(remaining_rows); offset.x += size_x / 2.0; let draw_size = Vec2::new(size_x, size_y); let delta = draw_size / expected_size; slices.push(Self { texture_rect: Rect { min: self.texture_rect.min, max: self.texture_rect.min + self.texture_rect.size() * delta, }, draw_size, offset: self.offset + offset, }); offset.x += size_x / 2.0; remaining_rows -= size_x; } offset.y -= size_y / 2.0; remaining_columns -= size_y; } if slices.len() > 1_000 { tracing::warn!("One of your tiled textures has generated {} slices. You might want to use higher stretch values to avoid a great performance cost", slices.len()); } slices } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_sprite/src/texture_slice/slicer.rs
crates/bevy_sprite/src/texture_slice/slicer.rs
use super::{BorderRect, TextureSlice}; use bevy_math::{vec2, Rect, Vec2}; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; /// Slices a texture using the **9-slicing** technique. This allows to reuse an image at various sizes /// without needing to prepare multiple assets. The associated texture will be split into nine portions, /// so that on resize the different portions scale or tile in different ways to keep the texture in proportion. /// /// For example, when resizing a 9-sliced texture the corners will remain unscaled while the other /// sections will be scaled or tiled. /// /// See [9-sliced](https://en.wikipedia.org/wiki/9-slice_scaling) textures. #[derive(Debug, Clone, Reflect, PartialEq)] #[reflect(Clone, PartialEq)] pub struct TextureSlicer { /// Inset values in pixels that define the four slicing lines dividing the texture into nine sections. pub border: BorderRect, /// Defines how the center part of the 9 slices will scale pub center_scale_mode: SliceScaleMode, /// Defines how the 4 side parts of the 9 slices will scale pub sides_scale_mode: SliceScaleMode, /// Defines the maximum scale of the 4 corner slices (default to `1.0`) pub max_corner_scale: f32, } /// Defines how a texture slice scales when resized #[derive(Debug, Copy, Clone, Default, Reflect, PartialEq)] #[reflect(Clone, PartialEq, Default)] pub enum SliceScaleMode { /// The slice will be stretched to fit the area #[default] Stretch, /// The slice will be tiled to fit the area Tile { /// The slice will repeat when the ratio between the *drawing dimensions* of texture and the /// *original texture size* are above `stretch_value`. /// /// Example: `1.0` means that a 10 pixel wide image would repeat after 10 screen pixels. /// `2.0` means it would repeat after 20 screen pixels. /// /// Note: The value should be inferior or equal to `1.0` to avoid quality loss. /// /// Note: the value will be clamped to `0.001` if lower stretch_value: f32, }, } impl TextureSlicer { /// Computes the 4 corner slices: top left, top right, bottom left, bottom right. #[must_use] fn corner_slices(&self, base_rect: Rect, render_size: Vec2) -> [TextureSlice; 4] { let coef = render_size / base_rect.size(); let BorderRect { min_inset: Vec2 { x: left, y: top }, max_inset: Vec2 { x: right, y: bottom, }, } = self.border; let min_coef = coef.x.min(coef.y).min(self.max_corner_scale); [ // Top Left Corner TextureSlice { texture_rect: Rect { min: base_rect.min, max: base_rect.min + vec2(left, top), }, draw_size: vec2(left, top) * min_coef, offset: vec2( -render_size.x + left * min_coef, render_size.y - top * min_coef, ) / 2.0, }, // Top Right Corner TextureSlice { texture_rect: Rect { min: vec2(base_rect.max.x - right, base_rect.min.y), max: vec2(base_rect.max.x, base_rect.min.y + top), }, draw_size: vec2(right, top) * min_coef, offset: vec2( render_size.x - right * min_coef, render_size.y - top * min_coef, ) / 2.0, }, // Bottom Left TextureSlice { texture_rect: Rect { min: vec2(base_rect.min.x, base_rect.max.y - bottom), max: vec2(base_rect.min.x + left, base_rect.max.y), }, draw_size: vec2(left, bottom) * min_coef, offset: vec2( -render_size.x + left * min_coef, -render_size.y + bottom * min_coef, ) / 2.0, }, // Bottom Right Corner TextureSlice { texture_rect: Rect { min: vec2(base_rect.max.x - right, base_rect.max.y - bottom), max: base_rect.max, }, draw_size: vec2(right, bottom) * min_coef, offset: vec2( render_size.x - right * min_coef, -render_size.y + bottom * min_coef, ) / 2.0, }, ] } /// Computes the 2 horizontal side slices (left and right borders) #[must_use] fn horizontal_side_slices( &self, [tl_corner, tr_corner, bl_corner, br_corner]: &[TextureSlice; 4], base_rect: Rect, render_size: Vec2, ) -> [TextureSlice; 2] { [ // Left TextureSlice { texture_rect: Rect { min: base_rect.min + vec2(0.0, self.border.min_inset.y), max: vec2( base_rect.min.x + self.border.min_inset.x, base_rect.max.y - self.border.max_inset.y, ), }, draw_size: vec2( tl_corner.draw_size.x, render_size.y - (tl_corner.draw_size.y + bl_corner.draw_size.y), ), offset: vec2( tl_corner.draw_size.x - render_size.x, bl_corner.draw_size.y - tl_corner.draw_size.y, ) / 2.0, }, // Right TextureSlice { texture_rect: Rect { min: vec2( base_rect.max.x - self.border.max_inset.x, base_rect.min.y + self.border.min_inset.y, ), max: base_rect.max - vec2(0.0, self.border.max_inset.y), }, draw_size: vec2( tr_corner.draw_size.x, render_size.y - (tr_corner.draw_size.y + br_corner.draw_size.y), ), offset: vec2( render_size.x - tr_corner.draw_size.x, br_corner.draw_size.y - tr_corner.draw_size.y, ) / 2.0, }, ] } /// Computes the 2 vertical side slices (top and bottom borders) #[must_use] fn vertical_side_slices( &self, [tl_corner, tr_corner, bl_corner, br_corner]: &[TextureSlice; 4], base_rect: Rect, render_size: Vec2, ) -> [TextureSlice; 2] { [ // Top TextureSlice { texture_rect: Rect { min: base_rect.min + vec2(self.border.min_inset.x, 0.0), max: vec2( base_rect.max.x - self.border.max_inset.x, base_rect.min.y + self.border.min_inset.y, ), }, draw_size: vec2( render_size.x - (tl_corner.draw_size.x + tr_corner.draw_size.x), tl_corner.draw_size.y, ), offset: vec2( tl_corner.draw_size.x - tr_corner.draw_size.x, render_size.y - tl_corner.draw_size.y, ) / 2.0, }, // Bottom TextureSlice { texture_rect: Rect { min: vec2( base_rect.min.x + self.border.min_inset.x, base_rect.max.y - self.border.max_inset.y, ), max: base_rect.max - vec2(self.border.max_inset.x, 0.0), }, draw_size: vec2( render_size.x - (bl_corner.draw_size.x + br_corner.draw_size.x), bl_corner.draw_size.y, ), offset: vec2( bl_corner.draw_size.x - br_corner.draw_size.x, bl_corner.draw_size.y - render_size.y, ) / 2.0, }, ] } /// Slices the given `rect` into at least 9 sections. If the center and/or side parts are set to tile, /// a bigger number of sections will be computed. /// /// # Arguments /// /// * `rect` - The section of the texture to slice in 9 parts /// * `render_size` - The optional draw size of the texture. If not set the `rect` size will be used. // TODO: Support `URect` and `UVec2` instead (See `https://github.com/bevyengine/bevy/pull/11698`) #[must_use] pub fn compute_slices(&self, rect: Rect, render_size: Option<Vec2>) -> Vec<TextureSlice> { let render_size = render_size.unwrap_or_else(|| rect.size()); if (self.border.min_inset + self.border.max_inset) .cmpge(rect.size()) .any() { tracing::error!( "TextureSlicer::border has out of bounds values. No slicing will be applied" ); return vec![TextureSlice { texture_rect: rect, draw_size: render_size, offset: Vec2::ZERO, }]; } let mut slices = Vec::with_capacity(9); // Corners are in this order: [TL, TR, BL, BR] let corners = self.corner_slices(rect, render_size); // Vertical Sides: [T, B] let vertical_sides = self.vertical_side_slices(&corners, rect, render_size); // Horizontal Sides: [L, R] let horizontal_sides = self.horizontal_side_slices(&corners, rect, render_size); // Center let center = TextureSlice { texture_rect: Rect { min: rect.min + self.border.min_inset, max: rect.max - self.border.max_inset, }, draw_size: vec2( render_size.x - (corners[0].draw_size.x + corners[1].draw_size.x), render_size.y - (corners[0].draw_size.y + corners[2].draw_size.y), ), offset: vec2(vertical_sides[0].offset.x, horizontal_sides[0].offset.y), }; slices.extend(corners); match self.center_scale_mode { SliceScaleMode::Stretch => { slices.push(center); } SliceScaleMode::Tile { stretch_value } => { slices.extend(center.tiled(stretch_value, (true, true))); } } match self.sides_scale_mode { SliceScaleMode::Stretch => { slices.extend(horizontal_sides); slices.extend(vertical_sides); } SliceScaleMode::Tile { stretch_value } => { slices.extend( horizontal_sides .into_iter() .flat_map(|s| s.tiled(stretch_value, (false, true))), ); slices.extend( vertical_sides .into_iter() .flat_map(|s| s.tiled(stretch_value, (true, false))), ); } } slices } } impl Default for TextureSlicer { fn default() -> Self { Self { border: Default::default(), center_scale_mode: Default::default(), sides_scale_mode: Default::default(), max_corner_scale: 1.0, } } } #[cfg(test)] mod test { use super::*; #[test] fn test_horizontal_sizes_uniform() { let slicer = TextureSlicer { border: BorderRect::all(10.), center_scale_mode: SliceScaleMode::Stretch, sides_scale_mode: SliceScaleMode::Stretch, max_corner_scale: 1.0, }; let base_rect = Rect { min: Vec2::ZERO, max: Vec2::splat(50.), }; let render_rect = Vec2::splat(100.); let slices = slicer.corner_slices(base_rect, render_rect); assert_eq!( slices[0], TextureSlice { texture_rect: Rect { min: Vec2::ZERO, max: Vec2::splat(10.0) }, draw_size: Vec2::new(10.0, 10.0), offset: Vec2::new(-45.0, 45.0), } ); } #[test] fn test_horizontal_sizes_non_uniform_bigger() { let slicer = TextureSlicer { border: BorderRect { min_inset: Vec2::new(20., 10.), max_inset: Vec2::splat(10.), }, center_scale_mode: SliceScaleMode::Stretch, sides_scale_mode: SliceScaleMode::Stretch, max_corner_scale: 1.0, }; let base_rect = Rect { min: Vec2::ZERO, max: Vec2::splat(50.), }; let render_rect = Vec2::splat(100.); let slices = slicer.corner_slices(base_rect, render_rect); assert_eq!( slices[0], TextureSlice { texture_rect: Rect { min: Vec2::ZERO, max: Vec2::new(20.0, 10.0) }, draw_size: Vec2::new(20.0, 10.0), offset: Vec2::new(-40.0, 45.0), } ); } #[test] fn test_horizontal_sizes_non_uniform_smaller() { let slicer = TextureSlicer { border: BorderRect { min_inset: Vec2::new(5., 10.), max_inset: Vec2::splat(10.), }, center_scale_mode: SliceScaleMode::Stretch, sides_scale_mode: SliceScaleMode::Stretch, max_corner_scale: 1.0, }; let rect = Rect { min: Vec2::ZERO, max: Vec2::splat(50.), }; let render_size = Vec2::splat(100.); let corners = slicer.corner_slices(rect, render_size); let vertical_sides = slicer.vertical_side_slices(&corners, rect, render_size); assert_eq!( corners[0], TextureSlice { texture_rect: Rect { min: Vec2::ZERO, max: Vec2::new(5.0, 10.0) }, draw_size: Vec2::new(5.0, 10.0), offset: Vec2::new(-47.5, 45.0), } ); assert_eq!( vertical_sides[0], // top TextureSlice { texture_rect: Rect { min: Vec2::new(5.0, 0.0), max: Vec2::new(40.0, 10.0) }, draw_size: Vec2::new(85.0, 10.0), offset: Vec2::new(-2.5, 45.0), } ); } #[test] fn test_horizontal_sizes_non_uniform_zero() { let slicer = TextureSlicer { border: BorderRect { min_inset: Vec2::new(0., 10.), max_inset: Vec2::splat(10.), }, center_scale_mode: SliceScaleMode::Stretch, sides_scale_mode: SliceScaleMode::Stretch, max_corner_scale: 1.0, }; let base_rect = Rect { min: Vec2::ZERO, max: Vec2::splat(50.), }; let render_rect = Vec2::splat(100.); let slices = slicer.corner_slices(base_rect, render_rect); assert_eq!( slices[0], TextureSlice { texture_rect: Rect { min: Vec2::ZERO, max: Vec2::new(0.0, 10.0) }, draw_size: Vec2::new(0.0, 10.0), offset: Vec2::new(-50.0, 45.0), } ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gltf/src/lib.rs
crates/bevy_gltf/src/lib.rs
#![cfg_attr(docsrs, feature(doc_cfg))] #![forbid(unsafe_code)] #![doc( html_logo_url = "https://bevy.org/assets/icon.png", html_favicon_url = "https://bevy.org/assets/icon.png" )] //! Plugin providing an [`AssetLoader`](bevy_asset::AssetLoader) and type definitions //! for loading glTF 2.0 (a standard 3D scene definition format) files in Bevy. //! //! The [glTF 2.0 specification](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html) defines the format of the glTF files. //! //! # Quick Start //! //! Here's how to spawn a simple glTF scene //! //! ``` //! # use bevy_ecs::prelude::*; //! # use bevy_asset::prelude::*; //! # use bevy_scene::prelude::*; //! # use bevy_transform::prelude::*; //! # use bevy_gltf::prelude::*; //! //! fn spawn_gltf(mut commands: Commands, asset_server: Res<AssetServer>) { //! commands.spawn(( //! // This is equivalent to "models/FlightHelmet/FlightHelmet.gltf#Scene0" //! // The `#Scene0` label here is very important because it tells bevy to load the first scene in the glTF file. //! // If this isn't specified bevy doesn't know which part of the glTF file to load. //! SceneRoot(asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf"))), //! // You can use the transform to give it a position //! Transform::from_xyz(2.0, 0.0, -5.0), //! )); //! } //! ``` //! # Loading parts of a glTF asset //! //! ## Using `Gltf` //! //! If you want to access part of the asset, you can load the entire `Gltf` using the `AssetServer`. //! Once the `Handle<Gltf>` is loaded you can then use it to access named parts of it. //! //! ``` //! # use bevy_ecs::prelude::*; //! # use bevy_asset::prelude::*; //! # use bevy_scene::prelude::*; //! # use bevy_transform::prelude::*; //! # use bevy_gltf::Gltf; //! //! // Holds the scene handle //! #[derive(Resource)] //! struct HelmetScene(Handle<Gltf>); //! //! fn load_gltf(mut commands: Commands, asset_server: Res<AssetServer>) { //! let gltf = asset_server.load("models/FlightHelmet/FlightHelmet.gltf"); //! commands.insert_resource(HelmetScene(gltf)); //! } //! //! fn spawn_gltf_objects( //! mut commands: Commands, //! helmet_scene: Res<HelmetScene>, //! gltf_assets: Res<Assets<Gltf>>, //! mut loaded: Local<bool>, //! ) { //! // Only do this once //! if *loaded { //! return; //! } //! // Wait until the scene is loaded //! let Some(gltf) = gltf_assets.get(&helmet_scene.0) else { //! return; //! }; //! *loaded = true; //! //! // Spawns the first scene in the file //! commands.spawn(SceneRoot(gltf.scenes[0].clone())); //! //! // Spawns the scene named "Lenses_low" //! commands.spawn(( //! SceneRoot(gltf.named_scenes["Lenses_low"].clone()), //! Transform::from_xyz(1.0, 2.0, 3.0), //! )); //! } //! ``` //! //! ## Asset Labels //! //! The glTF loader let's you specify labels that let you target specific parts of the glTF. //! //! Be careful when using this feature, if you misspell a label it will simply ignore it without warning. //! //! You can use [`GltfAssetLabel`] to ensure you are using the correct label. //! //! # Supported KHR Extensions //! //! glTF files may use functionality beyond the base glTF specification, specified as a list of //! required extensions. The table below shows which of the ratified Khronos extensions are //! supported by Bevy. //! //! | Extension | Supported | Requires feature | //! | --------------------------------- | --------- | ----------------------------------- | //! | `KHR_animation_pointer` | ❌ | | //! | `KHR_draco_mesh_compression` | ❌ | | //! | `KHR_lights_punctual` | ✅ | | //! | `KHR_materials_anisotropy` | ✅ | `pbr_anisotropy_texture` | //! | `KHR_materials_clearcoat` | ✅ | `pbr_multi_layer_material_textures` | //! | `KHR_materials_dispersion` | ❌ | | //! | `KHR_materials_emissive_strength` | ✅ | | //! | `KHR_materials_ior` | ✅ | | //! | `KHR_materials_iridescence` | ❌ | | //! | `KHR_materials_sheen` | ❌ | | //! | `KHR_materials_specular` | ✅ | `pbr_specular_textures` | //! | `KHR_materials_transmission` | ✅ | `pbr_transmission_textures` | //! | `KHR_materials_unlit` | ✅ | | //! | `KHR_materials_variants` | ❌ | | //! | `KHR_materials_volume` | ✅ | | //! | `KHR_mesh_quantization` | ❌ | | //! | `KHR_texture_basisu` | ❌\* | | //! | `KHR_texture_transform` | ✅\** | | //! | `KHR_xmp_json_ld` | ❌ | | //! | `EXT_mesh_gpu_instancing` | ❌ | | //! | `EXT_meshopt_compression` | ❌ | | //! | `EXT_texture_webp` | ❌\* | | //! //! \*Bevy supports ktx2 and webp formats but doesn't support the extension's syntax, see [#19104](https://github.com/bevyengine/bevy/issues/19104). //! //! \**`KHR_texture_transform` is only supported on `base_color_texture`, see [#15310](https://github.com/bevyengine/bevy/issues/15310). //! //! See the [glTF Extension Registry](https://github.com/KhronosGroup/glTF/blob/main/extensions/README.md) for more information on extensions. mod assets; pub mod convert_coordinates; mod label; mod loader; mod vertex_attributes; extern crate alloc; use alloc::sync::Arc; use std::sync::Mutex; use tracing::warn; use bevy_platform::collections::HashMap; use bevy_app::prelude::*; use bevy_asset::AssetApp; use bevy_ecs::prelude::Resource; use bevy_image::{CompressedImageFormatSupport, CompressedImageFormats, ImageSamplerDescriptor}; use bevy_mesh::MeshVertexAttribute; /// The glTF prelude. /// /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { #[doc(hidden)] pub use crate::{assets::Gltf, assets::GltfExtras, label::GltfAssetLabel}; } use crate::{convert_coordinates::GltfConvertCoordinates, extensions::GltfExtensionHandlers}; pub use {assets::*, label::GltfAssetLabel, loader::*}; // Has to store an Arc<Mutex<...>> as there is no other way to mutate fields of asset loaders. /// Stores default [`ImageSamplerDescriptor`] in main world. #[derive(Resource)] pub struct DefaultGltfImageSampler(Arc<Mutex<ImageSamplerDescriptor>>); impl DefaultGltfImageSampler { /// Creates a new [`DefaultGltfImageSampler`]. pub fn new(descriptor: &ImageSamplerDescriptor) -> Self { Self(Arc::new(Mutex::new(descriptor.clone()))) } /// Returns the current default [`ImageSamplerDescriptor`]. pub fn get(&self) -> ImageSamplerDescriptor { self.0.lock().unwrap().clone() } /// Makes a clone of internal [`Arc`] pointer. /// /// Intended only to be used by code with no access to ECS. pub fn get_internal(&self) -> Arc<Mutex<ImageSamplerDescriptor>> { self.0.clone() } /// Replaces default [`ImageSamplerDescriptor`]. /// /// Doesn't apply to samplers already built on top of it, i.e. `GltfLoader`'s output. /// Assets need to manually be reloaded. pub fn set(&self, descriptor: &ImageSamplerDescriptor) { *self.0.lock().unwrap() = descriptor.clone(); } } /// Adds support for glTF file loading to the app. pub struct GltfPlugin { /// The default image sampler to lay glTF sampler data on top of. /// /// Can be modified with the [`DefaultGltfImageSampler`] resource. pub default_sampler: ImageSamplerDescriptor, /// The default glTF coordinate conversion setting. This can be overridden /// per-load by [`GltfLoaderSettings::convert_coordinates`]. pub convert_coordinates: GltfConvertCoordinates, /// Registry for custom vertex attributes. /// /// To specify, use [`GltfPlugin::add_custom_vertex_attribute`]. pub custom_vertex_attributes: HashMap<Box<str>, MeshVertexAttribute>, } impl Default for GltfPlugin { fn default() -> Self { GltfPlugin { default_sampler: ImageSamplerDescriptor::linear(), custom_vertex_attributes: HashMap::default(), convert_coordinates: GltfConvertCoordinates::default(), } } } impl GltfPlugin { /// Register a custom vertex attribute so that it is recognized when loading a glTF file with the [`GltfLoader`]. /// /// `name` must be the attribute name as found in the glTF data, which must start with an underscore. /// See [this section of the glTF specification](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview) /// for additional details on custom attributes. pub fn add_custom_vertex_attribute( mut self, name: &str, attribute: MeshVertexAttribute, ) -> Self { self.custom_vertex_attributes.insert(name.into(), attribute); self } } impl Plugin for GltfPlugin { fn build(&self, app: &mut App) { app.init_asset::<Gltf>() .init_asset::<GltfNode>() .init_asset::<GltfPrimitive>() .init_asset::<GltfMesh>() .init_asset::<GltfSkin>() .preregister_asset_loader::<GltfLoader>(&["gltf", "glb"]) .init_resource::<GltfExtensionHandlers>(); } fn finish(&self, app: &mut App) { let supported_compressed_formats = if let Some(resource) = app.world().get_resource::<CompressedImageFormatSupport>() { resource.0 } else { warn!("CompressedImageFormatSupport resource not found. It should either be initialized in finish() of \ RenderPlugin, or manually if not using the RenderPlugin or the WGPU backend."); CompressedImageFormats::NONE }; let default_sampler_resource = DefaultGltfImageSampler::new(&self.default_sampler); let default_sampler = default_sampler_resource.get_internal(); app.insert_resource(default_sampler_resource); let extensions = app.world().resource::<GltfExtensionHandlers>(); app.register_asset_loader(GltfLoader { supported_compressed_formats, custom_vertex_attributes: self.custom_vertex_attributes.clone(), default_sampler, default_convert_coordinates: self.convert_coordinates, extensions: extensions.0.clone(), }); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gltf/src/convert_coordinates.rs
crates/bevy_gltf/src/convert_coordinates.rs
//! Utilities for converting from glTF's [standard coordinate system](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#coordinate-system-and-units) //! to Bevy's. use serde::{Deserialize, Serialize}; use bevy_math::{Mat4, Quat, Vec3}; use bevy_transform::components::Transform; pub(crate) trait ConvertCoordinates { /// Converts from glTF coordinates to Bevy's coordinate system. See /// [`GltfConvertCoordinates`] for an explanation of the conversion. fn convert_coordinates(self) -> Self; } impl ConvertCoordinates for Vec3 { fn convert_coordinates(self) -> Self { Vec3::new(-self.x, self.y, -self.z) } } impl ConvertCoordinates for [f32; 3] { fn convert_coordinates(self) -> Self { [-self[0], self[1], -self[2]] } } impl ConvertCoordinates for [f32; 4] { fn convert_coordinates(self) -> Self { // Solution of q' = r q r* [-self[0], self[1], -self[2], self[3]] } } /// Options for converting scenes and assets from glTF's [standard coordinate system](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#coordinate-system-and-units) /// (+Z forward) to Bevy's coordinate system (-Z forward). /// /// The exact coordinate system conversion is as follows: /// - glTF: /// - forward: +Z /// - up: +Y /// - right: -X /// - Bevy: /// - forward: -Z /// - up: +Y /// - right: +X /// /// Note that some glTF files may not follow the glTF standard. /// /// If your glTF scene is +Z forward and you want it converted to match Bevy's /// `Transform::forward`, enable the `rotate_scene_entity` option. If you also want `Mesh` /// assets to be converted, enable the `rotate_meshes` option. /// /// Cameras and lights in glTF files are an exception - they already use Bevy's /// coordinate system. This means cameras and lights will match /// `Transform::forward` even if conversion is disabled. #[derive(Copy, Clone, Default, Debug, Serialize, Deserialize)] pub struct GltfConvertCoordinates { /// If true, convert scenes by rotating the top-level transform of the scene entity. /// /// This will ensure that [`Transform::forward`] of the "root" entity (the one with [`SceneInstance`](bevy_scene::SceneInstance)) /// aligns with the "forward" of the glTF scene. /// /// The glTF loader creates an entity for each glTF scene. Entities are /// then created for each node within the glTF scene. Nodes without a /// parent in the glTF scene become children of the scene entity. /// /// This option only changes the transform of the scene entity. It does not /// directly change the transforms of node entities - it only changes them /// indirectly through transform inheritance. pub rotate_scene_entity: bool, /// If true, convert mesh assets. This includes skinned mesh bind poses. /// /// This option only changes mesh assets and the transforms of entities that /// instance meshes. It does not change the transforms of entities that /// correspond to glTF nodes. pub rotate_meshes: bool, } impl GltfConvertCoordinates { const CONVERSION_TRANSFORM: Transform = Transform::from_rotation(Quat::from_xyzw(0.0, 1.0, 0.0, 0.0)); fn conversion_mat4() -> Mat4 { Mat4::from_scale(Vec3::new(-1.0, 1.0, -1.0)) } pub(crate) fn scene_conversion_transform(&self) -> Transform { if self.rotate_scene_entity { Self::CONVERSION_TRANSFORM } else { Transform::IDENTITY } } pub(crate) fn mesh_conversion_transform(&self) -> Transform { if self.rotate_meshes { Self::CONVERSION_TRANSFORM } else { Transform::IDENTITY } } pub(crate) fn mesh_conversion_transform_inverse(&self) -> Transform { // We magically know that the transform is its own inverse. We still // make a distinction at the interface level in case that changes. self.mesh_conversion_transform() } pub(crate) fn mesh_conversion_mat4(&self) -> Mat4 { if self.rotate_meshes { Self::conversion_mat4() } else { Mat4::IDENTITY } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gltf/src/vertex_attributes.rs
crates/bevy_gltf/src/vertex_attributes.rs
use bevy_mesh::{Mesh, MeshVertexAttribute, VertexAttributeValues as Values, VertexFormat}; use bevy_platform::collections::HashMap; use gltf::{ accessor::{DataType, Dimensions}, mesh::util::{ReadColors, ReadJoints, ReadTexCoords, ReadWeights}, }; use thiserror::Error; use crate::convert_coordinates::ConvertCoordinates; /// Represents whether integer data requires normalization #[derive(Copy, Clone)] struct Normalization(bool); impl Normalization { fn apply_either<T, U>( self, value: T, normalized_ctor: impl Fn(T) -> U, unnormalized_ctor: impl Fn(T) -> U, ) -> U { if self.0 { normalized_ctor(value) } else { unnormalized_ctor(value) } } } /// An error that occurs when accessing buffer data #[derive(Error, Debug)] pub(crate) enum AccessFailed { #[error("Malformed vertex attribute data")] MalformedData, #[error("Unsupported vertex attribute format")] UnsupportedFormat, } /// Helper for reading buffer data struct BufferAccessor<'a> { accessor: gltf::Accessor<'a>, buffer_data: &'a Vec<Vec<u8>>, normalization: Normalization, } impl<'a> BufferAccessor<'a> { /// Creates an iterator over the elements in this accessor fn iter<T: gltf::accessor::Item>(self) -> Result<gltf::accessor::Iter<'a, T>, AccessFailed> { gltf::accessor::Iter::new(self.accessor, |buffer: gltf::Buffer| { self.buffer_data.get(buffer.index()).map(Vec::as_slice) }) .ok_or(AccessFailed::MalformedData) } /// Applies the element iterator to a constructor or fails if normalization is required fn with_no_norm<T: gltf::accessor::Item, U>( self, ctor: impl Fn(gltf::accessor::Iter<'a, T>) -> U, ) -> Result<U, AccessFailed> { if self.normalization.0 { return Err(AccessFailed::UnsupportedFormat); } self.iter().map(ctor) } /// Applies the element iterator and the normalization flag to a constructor fn with_norm<T: gltf::accessor::Item, U>( self, ctor: impl Fn(gltf::accessor::Iter<'a, T>, Normalization) -> U, ) -> Result<U, AccessFailed> { let normalized = self.normalization; self.iter().map(|v| ctor(v, normalized)) } } /// An enum of the iterators user by different vertex attribute formats enum VertexAttributeIter<'a> { // For reading native WGPU formats F32(gltf::accessor::Iter<'a, f32>), U32(gltf::accessor::Iter<'a, u32>), F32x2(gltf::accessor::Iter<'a, [f32; 2]>), U32x2(gltf::accessor::Iter<'a, [u32; 2]>), F32x3(gltf::accessor::Iter<'a, [f32; 3]>), U32x3(gltf::accessor::Iter<'a, [u32; 3]>), F32x4(gltf::accessor::Iter<'a, [f32; 4]>), U32x4(gltf::accessor::Iter<'a, [u32; 4]>), S16x2(gltf::accessor::Iter<'a, [i16; 2]>, Normalization), U16x2(gltf::accessor::Iter<'a, [u16; 2]>, Normalization), S16x4(gltf::accessor::Iter<'a, [i16; 4]>, Normalization), U16x4(gltf::accessor::Iter<'a, [u16; 4]>, Normalization), S8x2(gltf::accessor::Iter<'a, [i8; 2]>, Normalization), U8x2(gltf::accessor::Iter<'a, [u8; 2]>, Normalization), S8x4(gltf::accessor::Iter<'a, [i8; 4]>, Normalization), U8x4(gltf::accessor::Iter<'a, [u8; 4]>, Normalization), // Additional on-disk formats used for RGB colors U16x3(gltf::accessor::Iter<'a, [u16; 3]>, Normalization), U8x3(gltf::accessor::Iter<'a, [u8; 3]>, Normalization), } impl<'a> VertexAttributeIter<'a> { /// Creates an iterator over the elements in a vertex attribute accessor fn from_accessor( accessor: gltf::Accessor<'a>, buffer_data: &'a Vec<Vec<u8>>, ) -> Result<VertexAttributeIter<'a>, AccessFailed> { let normalization = Normalization(accessor.normalized()); let format = (accessor.data_type(), accessor.dimensions()); let acc = BufferAccessor { accessor, buffer_data, normalization, }; match format { (DataType::F32, Dimensions::Scalar) => acc.with_no_norm(VertexAttributeIter::F32), (DataType::U32, Dimensions::Scalar) => acc.with_no_norm(VertexAttributeIter::U32), (DataType::F32, Dimensions::Vec2) => acc.with_no_norm(VertexAttributeIter::F32x2), (DataType::U32, Dimensions::Vec2) => acc.with_no_norm(VertexAttributeIter::U32x2), (DataType::F32, Dimensions::Vec3) => acc.with_no_norm(VertexAttributeIter::F32x3), (DataType::U32, Dimensions::Vec3) => acc.with_no_norm(VertexAttributeIter::U32x3), (DataType::F32, Dimensions::Vec4) => acc.with_no_norm(VertexAttributeIter::F32x4), (DataType::U32, Dimensions::Vec4) => acc.with_no_norm(VertexAttributeIter::U32x4), (DataType::I16, Dimensions::Vec2) => acc.with_norm(VertexAttributeIter::S16x2), (DataType::U16, Dimensions::Vec2) => acc.with_norm(VertexAttributeIter::U16x2), (DataType::I16, Dimensions::Vec4) => acc.with_norm(VertexAttributeIter::S16x4), (DataType::U16, Dimensions::Vec4) => acc.with_norm(VertexAttributeIter::U16x4), (DataType::I8, Dimensions::Vec2) => acc.with_norm(VertexAttributeIter::S8x2), (DataType::U8, Dimensions::Vec2) => acc.with_norm(VertexAttributeIter::U8x2), (DataType::I8, Dimensions::Vec4) => acc.with_norm(VertexAttributeIter::S8x4), (DataType::U8, Dimensions::Vec4) => acc.with_norm(VertexAttributeIter::U8x4), (DataType::U16, Dimensions::Vec3) => acc.with_norm(VertexAttributeIter::U16x3), (DataType::U8, Dimensions::Vec3) => acc.with_norm(VertexAttributeIter::U8x3), _ => Err(AccessFailed::UnsupportedFormat), } } /// Materializes values for any supported format of vertex attribute fn into_any_values(self, convert_coordinates: bool) -> Result<Values, AccessFailed> { match self { VertexAttributeIter::F32(it) => Ok(Values::Float32(it.collect())), VertexAttributeIter::U32(it) => Ok(Values::Uint32(it.collect())), VertexAttributeIter::F32x2(it) => Ok(Values::Float32x2(it.collect())), VertexAttributeIter::U32x2(it) => Ok(Values::Uint32x2(it.collect())), VertexAttributeIter::F32x3(it) => Ok(if convert_coordinates { // The following f32x3 values need to be converted to the correct coordinate system // - Positions // - Normals // // See <https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview> Values::Float32x3(it.map(ConvertCoordinates::convert_coordinates).collect()) } else { Values::Float32x3(it.collect()) }), VertexAttributeIter::U32x3(it) => Ok(Values::Uint32x3(it.collect())), VertexAttributeIter::F32x4(it) => Ok(if convert_coordinates { // The following f32x4 values need to be converted to the correct coordinate system // - Tangents // // See <https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview> Values::Float32x4(it.map(ConvertCoordinates::convert_coordinates).collect()) } else { Values::Float32x4(it.collect()) }), VertexAttributeIter::U32x4(it) => Ok(Values::Uint32x4(it.collect())), VertexAttributeIter::S16x2(it, n) => { Ok(n.apply_either(it.collect(), Values::Snorm16x2, Values::Sint16x2)) } VertexAttributeIter::U16x2(it, n) => { Ok(n.apply_either(it.collect(), Values::Unorm16x2, Values::Uint16x2)) } VertexAttributeIter::S16x4(it, n) => { Ok(n.apply_either(it.collect(), Values::Snorm16x4, Values::Sint16x4)) } VertexAttributeIter::U16x4(it, n) => { Ok(n.apply_either(it.collect(), Values::Unorm16x4, Values::Uint16x4)) } VertexAttributeIter::S8x2(it, n) => { Ok(n.apply_either(it.collect(), Values::Snorm8x2, Values::Sint8x2)) } VertexAttributeIter::U8x2(it, n) => { Ok(n.apply_either(it.collect(), Values::Unorm8x2, Values::Uint8x2)) } VertexAttributeIter::S8x4(it, n) => { Ok(n.apply_either(it.collect(), Values::Snorm8x4, Values::Sint8x4)) } VertexAttributeIter::U8x4(it, n) => { Ok(n.apply_either(it.collect(), Values::Unorm8x4, Values::Uint8x4)) } _ => Err(AccessFailed::UnsupportedFormat), } } /// Materializes RGBA values, converting compatible formats to Float32x4 fn into_rgba_values(self) -> Result<Values, AccessFailed> { match self { VertexAttributeIter::U8x3(it, Normalization(true)) => Ok(Values::Float32x4( ReadColors::RgbU8(it).into_rgba_f32().collect(), )), VertexAttributeIter::U16x3(it, Normalization(true)) => Ok(Values::Float32x4( ReadColors::RgbU16(it).into_rgba_f32().collect(), )), VertexAttributeIter::F32x3(it) => Ok(Values::Float32x4( ReadColors::RgbF32(it).into_rgba_f32().collect(), )), VertexAttributeIter::U8x4(it, Normalization(true)) => Ok(Values::Float32x4( ReadColors::RgbaU8(it).into_rgba_f32().collect(), )), VertexAttributeIter::U16x4(it, Normalization(true)) => Ok(Values::Float32x4( ReadColors::RgbaU16(it).into_rgba_f32().collect(), )), s => s.into_any_values(false), } } /// Materializes joint index values, converting compatible formats to Uint16x4 fn into_joint_index_values(self) -> Result<Values, AccessFailed> { match self { VertexAttributeIter::U8x4(it, Normalization(false)) => { Ok(Values::Uint16x4(ReadJoints::U8(it).into_u16().collect())) } s => s.into_any_values(false), } } /// Materializes joint weight values, converting compatible formats to Float32x4 fn into_joint_weight_values(self) -> Result<Values, AccessFailed> { match self { VertexAttributeIter::U8x4(it, Normalization(true)) => { Ok(Values::Float32x4(ReadWeights::U8(it).into_f32().collect())) } VertexAttributeIter::U16x4(it, Normalization(true)) => { Ok(Values::Float32x4(ReadWeights::U16(it).into_f32().collect())) } s => s.into_any_values(false), } } /// Materializes texture coordinate values, converting compatible formats to Float32x2 fn into_tex_coord_values(self) -> Result<Values, AccessFailed> { match self { VertexAttributeIter::U8x2(it, Normalization(true)) => Ok(Values::Float32x2( ReadTexCoords::U8(it).into_f32().collect(), )), VertexAttributeIter::U16x2(it, Normalization(true)) => Ok(Values::Float32x2( ReadTexCoords::U16(it).into_f32().collect(), )), s => s.into_any_values(false), } } } enum ConversionMode { Any, Rgba, JointIndex, JointWeight, TexCoord, } #[derive(Error, Debug)] pub(crate) enum ConvertAttributeError { #[error("Vertex attribute {0} has format {1:?} but expected {3:?} for target attribute {2}")] WrongFormat(String, VertexFormat, String, VertexFormat), #[error("{0} in accessor {1}")] AccessFailed(AccessFailed, usize), #[error("Unknown vertex attribute {0}")] UnknownName(String), } pub(crate) fn convert_attribute( semantic: gltf::Semantic, accessor: gltf::Accessor, buffer_data: &Vec<Vec<u8>>, custom_vertex_attributes: &HashMap<Box<str>, MeshVertexAttribute>, convert_coordinates: bool, ) -> Result<(MeshVertexAttribute, Values), ConvertAttributeError> { if let Some((attribute, conversion, convert_coordinates)) = match &semantic { gltf::Semantic::Positions => Some(( Mesh::ATTRIBUTE_POSITION, ConversionMode::Any, convert_coordinates, )), gltf::Semantic::Normals => Some(( Mesh::ATTRIBUTE_NORMAL, ConversionMode::Any, convert_coordinates, )), gltf::Semantic::Tangents => Some(( Mesh::ATTRIBUTE_TANGENT, ConversionMode::Any, convert_coordinates, )), gltf::Semantic::Colors(0) => Some((Mesh::ATTRIBUTE_COLOR, ConversionMode::Rgba, false)), gltf::Semantic::TexCoords(0) => { Some((Mesh::ATTRIBUTE_UV_0, ConversionMode::TexCoord, false)) } gltf::Semantic::TexCoords(1) => { Some((Mesh::ATTRIBUTE_UV_1, ConversionMode::TexCoord, false)) } gltf::Semantic::Joints(0) => Some(( Mesh::ATTRIBUTE_JOINT_INDEX, ConversionMode::JointIndex, false, )), gltf::Semantic::Weights(0) => Some(( Mesh::ATTRIBUTE_JOINT_WEIGHT, ConversionMode::JointWeight, false, )), gltf::Semantic::Extras(name) => custom_vertex_attributes .get(name.as_str()) .map(|attr| (*attr, ConversionMode::Any, false)), _ => None, } { let raw_iter = VertexAttributeIter::from_accessor(accessor.clone(), buffer_data); let converted_values = raw_iter.and_then(|iter| match conversion { ConversionMode::Any => iter.into_any_values(convert_coordinates), ConversionMode::Rgba => iter.into_rgba_values(), ConversionMode::TexCoord => iter.into_tex_coord_values(), ConversionMode::JointIndex => iter.into_joint_index_values(), ConversionMode::JointWeight => iter.into_joint_weight_values(), }); match converted_values { Ok(values) => { let loaded_format = VertexFormat::from(&values); if attribute.format == loaded_format { Ok((attribute, values)) } else { Err(ConvertAttributeError::WrongFormat( semantic.to_string(), loaded_format, attribute.name.to_string(), attribute.format, )) } } Err(err) => Err(ConvertAttributeError::AccessFailed(err, accessor.index())), } } else { Err(ConvertAttributeError::UnknownName(semantic.to_string())) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gltf/src/label.rs
crates/bevy_gltf/src/label.rs
//! Labels that can be used to load part of a glTF use bevy_asset::AssetPath; /// Labels that can be used to load part of a glTF /// /// You can use [`GltfAssetLabel::from_asset`] to add it to an asset path /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_asset::prelude::*; /// # use bevy_scene::prelude::*; /// # use bevy_gltf::prelude::*; /// /// fn load_gltf_scene(asset_server: Res<AssetServer>) { /// let gltf_scene: Handle<Scene> = asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf")); /// } /// ``` /// /// Or when formatting a string for the path /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_asset::prelude::*; /// # use bevy_scene::prelude::*; /// # use bevy_gltf::prelude::*; /// /// fn load_gltf_scene(asset_server: Res<AssetServer>) { /// let gltf_scene: Handle<Scene> = asset_server.load(format!("models/FlightHelmet/FlightHelmet.gltf#{}", GltfAssetLabel::Scene(0))); /// } /// ``` #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GltfAssetLabel { /// `Scene{}`: glTF Scene as a Bevy [`Scene`](bevy_scene::Scene) Scene(usize), /// `Node{}`: glTF Node as a [`GltfNode`](crate::GltfNode) Node(usize), /// `Mesh{}`: glTF Mesh as a [`GltfMesh`](crate::GltfMesh) Mesh(usize), /// `Mesh{}/Primitive{}`: glTF Primitive as a Bevy [`Mesh`](bevy_mesh::Mesh) Primitive { /// Index of the mesh for this primitive mesh: usize, /// Index of this primitive in its parent mesh primitive: usize, }, /// `Mesh{}/Primitive{}/MorphTargets`: Morph target animation data for a glTF Primitive /// as a Bevy [`Image`](bevy_image::prelude::Image) MorphTarget { /// Index of the mesh for this primitive mesh: usize, /// Index of this primitive in its parent mesh primitive: usize, }, /// `Texture{}`: glTF Texture as a Bevy [`Image`](bevy_image::prelude::Image) Texture(usize), /// `Material{}`: glTF Material as a Bevy [`StandardMaterial`](bevy_pbr::StandardMaterial) Material { /// Index of this material index: usize, /// Used to set the [`Face`](bevy_render::render_resource::Face) of the material, /// useful if it is used with negative scale is_scale_inverted: bool, }, /// `DefaultMaterial`: glTF's default Material as a /// Bevy [`StandardMaterial`](bevy_pbr::StandardMaterial) DefaultMaterial, /// `Animation{}`: glTF Animation as Bevy [`AnimationClip`](bevy_animation::AnimationClip) Animation(usize), /// `Skin{}`: glTF mesh skin as [`GltfSkin`](crate::GltfSkin) Skin(usize), /// `Skin{}/InverseBindMatrices`: glTF mesh skin matrices as Bevy /// [`SkinnedMeshInverseBindposes`](bevy_mesh::skinning::SkinnedMeshInverseBindposes) InverseBindMatrices(usize), } impl core::fmt::Display for GltfAssetLabel { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { GltfAssetLabel::Scene(index) => f.write_str(&format!("Scene{index}")), GltfAssetLabel::Node(index) => f.write_str(&format!("Node{index}")), GltfAssetLabel::Mesh(index) => f.write_str(&format!("Mesh{index}")), GltfAssetLabel::Primitive { mesh, primitive } => { f.write_str(&format!("Mesh{mesh}/Primitive{primitive}")) } GltfAssetLabel::MorphTarget { mesh, primitive } => { f.write_str(&format!("Mesh{mesh}/Primitive{primitive}/MorphTargets")) } GltfAssetLabel::Texture(index) => f.write_str(&format!("Texture{index}")), GltfAssetLabel::Material { index, is_scale_inverted, } => f.write_str(&format!( "Material{index}{}", if *is_scale_inverted { " (inverted)" } else { "" } )), GltfAssetLabel::DefaultMaterial => f.write_str("DefaultMaterial"), GltfAssetLabel::Animation(index) => f.write_str(&format!("Animation{index}")), GltfAssetLabel::Skin(index) => f.write_str(&format!("Skin{index}")), GltfAssetLabel::InverseBindMatrices(index) => { f.write_str(&format!("Skin{index}/InverseBindMatrices")) } } } } impl GltfAssetLabel { /// Add this label to an asset path /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_asset::prelude::*; /// # use bevy_scene::prelude::*; /// # use bevy_gltf::prelude::*; /// /// fn load_gltf_scene(asset_server: Res<AssetServer>) { /// let gltf_scene: Handle<Scene> = asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf")); /// } /// ``` pub fn from_asset(&self, path: impl Into<AssetPath<'static>>) -> AssetPath<'static> { path.into().with_label(self.to_string()) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gltf/src/assets.rs
crates/bevy_gltf/src/assets.rs
//! Representation of assets present in a glTF file use core::ops::Deref; #[cfg(feature = "bevy_animation")] use bevy_animation::AnimationClip; use bevy_asset::{Asset, Handle}; use bevy_ecs::{component::Component, reflect::ReflectComponent}; use bevy_mesh::{skinning::SkinnedMeshInverseBindposes, Mesh}; use bevy_pbr::StandardMaterial; use bevy_platform::collections::HashMap; use bevy_reflect::{prelude::ReflectDefault, Reflect, TypePath}; use bevy_scene::Scene; use crate::GltfAssetLabel; /// Representation of a loaded glTF file. #[derive(Asset, Debug, TypePath)] pub struct Gltf { /// All scenes loaded from the glTF file. pub scenes: Vec<Handle<Scene>>, /// Named scenes loaded from the glTF file. pub named_scenes: HashMap<Box<str>, Handle<Scene>>, /// All meshes loaded from the glTF file. pub meshes: Vec<Handle<GltfMesh>>, /// Named meshes loaded from the glTF file. pub named_meshes: HashMap<Box<str>, Handle<GltfMesh>>, /// All materials loaded from the glTF file. pub materials: Vec<Handle<StandardMaterial>>, /// Named materials loaded from the glTF file. pub named_materials: HashMap<Box<str>, Handle<StandardMaterial>>, /// All nodes loaded from the glTF file. pub nodes: Vec<Handle<GltfNode>>, /// Named nodes loaded from the glTF file. pub named_nodes: HashMap<Box<str>, Handle<GltfNode>>, /// All skins loaded from the glTF file. pub skins: Vec<Handle<GltfSkin>>, /// Named skins loaded from the glTF file. pub named_skins: HashMap<Box<str>, Handle<GltfSkin>>, /// Default scene to be displayed. pub default_scene: Option<Handle<Scene>>, /// All animations loaded from the glTF file. #[cfg(feature = "bevy_animation")] pub animations: Vec<Handle<AnimationClip>>, /// Named animations loaded from the glTF file. #[cfg(feature = "bevy_animation")] pub named_animations: HashMap<Box<str>, Handle<AnimationClip>>, /// The gltf root of the gltf asset, see <https://docs.rs/gltf/latest/gltf/struct.Gltf.html>. Only has a value when `GltfLoaderSettings::include_source` is true. pub source: Option<gltf::Gltf>, } /// A glTF mesh, which may consist of multiple [`GltfPrimitives`](GltfPrimitive) /// and an optional [`GltfExtras`]. /// /// See [the relevant glTF specification section](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-mesh). #[derive(Asset, Debug, Clone, TypePath)] pub struct GltfMesh { /// Index of the mesh inside the scene pub index: usize, /// Computed name for a mesh - either a user defined mesh name from gLTF or a generated name from index pub name: String, /// Primitives of the glTF mesh. pub primitives: Vec<GltfPrimitive>, /// Additional data. pub extras: Option<GltfExtras>, } impl GltfMesh { /// Create a mesh extracting name and index from glTF def pub fn new( mesh: &gltf::Mesh, primitives: Vec<GltfPrimitive>, extras: Option<GltfExtras>, ) -> Self { Self { index: mesh.index(), name: if let Some(name) = mesh.name() { name.to_string() } else { format!("GltfMesh{}", mesh.index()) }, primitives, extras, } } /// Subasset label for this mesh within the gLTF parent asset. pub fn asset_label(&self) -> GltfAssetLabel { GltfAssetLabel::Mesh(self.index) } } /// A glTF node with all of its child nodes, its [`GltfMesh`], /// [`Transform`](bevy_transform::prelude::Transform), its optional [`GltfSkin`] /// and an optional [`GltfExtras`]. /// /// See [the relevant glTF specification section](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-node). #[derive(Asset, Debug, Clone, TypePath)] pub struct GltfNode { /// Index of the node inside the scene pub index: usize, /// Computed name for a node - either a user defined node name from gLTF or a generated name from index pub name: String, /// Direct children of the node. pub children: Vec<Handle<GltfNode>>, /// Mesh of the node. pub mesh: Option<Handle<GltfMesh>>, /// Skin of the node. pub skin: Option<Handle<GltfSkin>>, /// Local transform. pub transform: bevy_transform::prelude::Transform, /// Is this node used as an animation root #[cfg(feature = "bevy_animation")] pub is_animation_root: bool, /// Additional data. pub extras: Option<GltfExtras>, } impl GltfNode { /// Create a node extracting name and index from glTF def pub fn new( node: &gltf::Node, children: Vec<Handle<GltfNode>>, mesh: Option<Handle<GltfMesh>>, transform: bevy_transform::prelude::Transform, skin: Option<Handle<GltfSkin>>, extras: Option<GltfExtras>, ) -> Self { Self { index: node.index(), name: if let Some(name) = node.name() { name.to_string() } else { format!("GltfNode{}", node.index()) }, children, mesh, transform, skin, #[cfg(feature = "bevy_animation")] is_animation_root: false, extras, } } /// Create a node with animation root mark #[cfg(feature = "bevy_animation")] pub fn with_animation_root(self, is_animation_root: bool) -> Self { Self { is_animation_root, ..self } } /// Subasset label for this node within the gLTF parent asset. pub fn asset_label(&self) -> GltfAssetLabel { GltfAssetLabel::Node(self.index) } } /// Part of a [`GltfMesh`] that consists of a [`Mesh`], an optional [`StandardMaterial`] and [`GltfExtras`]. /// /// See [the relevant glTF specification section](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-mesh-primitive). #[derive(Asset, Debug, Clone, TypePath)] pub struct GltfPrimitive { /// Index of the primitive inside the mesh pub index: usize, /// Index of the parent [`GltfMesh`] of this primitive pub parent_mesh_index: usize, /// Computed name for a primitive - either a user defined primitive name from gLTF or a generated name from index pub name: String, /// Topology to be rendered. pub mesh: Handle<Mesh>, /// Material to apply to the `mesh`. pub material: Option<Handle<StandardMaterial>>, /// Additional data. pub extras: Option<GltfExtras>, /// Additional data of the `material`. pub material_extras: Option<GltfExtras>, } impl GltfPrimitive { /// Create a primitive extracting name and index from glTF def pub fn new( gltf_mesh: &gltf::Mesh, gltf_primitive: &gltf::Primitive, mesh: Handle<Mesh>, material: Option<Handle<StandardMaterial>>, extras: Option<GltfExtras>, material_extras: Option<GltfExtras>, ) -> Self { GltfPrimitive { index: gltf_primitive.index(), parent_mesh_index: gltf_mesh.index(), name: { let mesh_name = gltf_mesh.name().unwrap_or("Mesh"); if gltf_mesh.primitives().len() > 1 { format!("{}.{}", mesh_name, gltf_primitive.index()) } else { mesh_name.to_string() } }, mesh, material, extras, material_extras, } } /// Subasset label for this primitive within its parent [`GltfMesh`] within the gLTF parent asset. pub fn asset_label(&self) -> GltfAssetLabel { GltfAssetLabel::Primitive { mesh: self.parent_mesh_index, primitive: self.index, } } } /// A glTF skin with all of its joint nodes, [`SkinnedMeshInversiveBindposes`](bevy_mesh::skinning::SkinnedMeshInverseBindposes) /// and an optional [`GltfExtras`]. /// /// See [the relevant glTF specification section](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-skin). #[derive(Asset, Debug, Clone, TypePath)] pub struct GltfSkin { /// Index of the skin inside the scene pub index: usize, /// Computed name for a skin - either a user defined skin name from gLTF or a generated name from index pub name: String, /// All the nodes that form this skin. pub joints: Vec<Handle<GltfNode>>, /// Inverse-bind matrices of this skin. pub inverse_bind_matrices: Handle<SkinnedMeshInverseBindposes>, /// Additional data. pub extras: Option<GltfExtras>, } impl GltfSkin { /// Create a skin extracting name and index from glTF def pub fn new( skin: &gltf::Skin, joints: Vec<Handle<GltfNode>>, inverse_bind_matrices: Handle<SkinnedMeshInverseBindposes>, extras: Option<GltfExtras>, ) -> Self { Self { index: skin.index(), name: if let Some(name) = skin.name() { name.to_string() } else { format!("GltfSkin{}", skin.index()) }, joints, inverse_bind_matrices, extras, } } /// Subasset label for this skin within the gLTF parent asset. pub fn asset_label(&self) -> GltfAssetLabel { GltfAssetLabel::Skin(self.index) } } /// Additional untyped data that can be present on most glTF types at the primitive level. /// /// See [the relevant glTF specification section](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-extras). #[derive(Clone, Debug, Reflect, Default, Component)] #[reflect(Component, Clone, Default, Debug)] pub struct GltfExtras { /// Content of the extra data. pub value: String, } impl From<&serde_json::value::RawValue> for GltfExtras { fn from(value: &serde_json::value::RawValue) -> Self { GltfExtras { value: value.get().to_string(), } } } /// Additional untyped data that can be present on most glTF types at the scene level. /// /// See [the relevant glTF specification section](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-extras). #[derive(Clone, Debug, Reflect, Default, Component)] #[reflect(Component, Clone, Default, Debug)] pub struct GltfSceneExtras { /// Content of the extra data. pub value: String, } /// Additional untyped data that can be present on most glTF types at the mesh level. /// /// See [the relevant glTF specification section](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-extras). #[derive(Clone, Debug, Reflect, Default, Component)] #[reflect(Component, Clone, Default, Debug)] pub struct GltfMeshExtras { /// Content of the extra data. pub value: String, } /// The mesh name of a glTF primitive. /// /// See [the relevant glTF specification section](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-mesh). #[derive(Clone, Debug, Reflect, Default, Component)] #[reflect(Component, Clone)] pub struct GltfMeshName(pub String); impl Deref for GltfMeshName { type Target = str; fn deref(&self) -> &Self::Target { self.0.as_ref() } } /// Additional untyped data that can be present on most glTF types at the material level. /// /// See [the relevant glTF specification section](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-extras). #[derive(Clone, Debug, Reflect, Default, Component)] #[reflect(Component, Clone, Default, Debug)] pub struct GltfMaterialExtras { /// Content of the extra data. pub value: String, } /// The material name of a glTF primitive. /// /// See [the relevant glTF specification section](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-material). #[derive(Clone, Debug, Reflect, Default, Component)] #[reflect(Component, Clone)] pub struct GltfMaterialName(pub String); impl Deref for GltfMaterialName { type Target = str; fn deref(&self) -> &Self::Target { self.0.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_gltf/src/loader/mod.rs
crates/bevy_gltf/src/loader/mod.rs
pub mod extensions; mod gltf_ext; use alloc::sync::Arc; use async_lock::RwLock; #[cfg(feature = "bevy_animation")] use bevy_animation::{prelude::*, AnimatedBy, AnimationTargetId}; use bevy_asset::{ io::Reader, AssetLoadError, AssetLoader, AssetPath, Handle, LoadContext, ParseAssetPathError, ReadAssetBytesError, RenderAssetUsages, }; use bevy_camera::{ primitives::Aabb, visibility::Visibility, Camera, Camera3d, OrthographicProjection, PerspectiveProjection, Projection, ScalingMode, }; use bevy_color::{Color, LinearRgba}; use bevy_ecs::{ entity::{Entity, EntityHashMap}, hierarchy::ChildSpawner, name::Name, world::World, }; use bevy_image::{ CompressedImageFormats, Image, ImageLoaderSettings, ImageSampler, ImageSamplerDescriptor, ImageType, TextureError, }; use bevy_light::{DirectionalLight, PointLight, SpotLight}; use bevy_math::{Mat4, Vec3}; use bevy_mesh::{ morph::{MeshMorphWeights, MorphAttributes, MorphTargetImage, MorphWeights}, skinning::{SkinnedMesh, SkinnedMeshInverseBindposes}, Indices, Mesh, Mesh3d, MeshVertexAttribute, PrimitiveTopology, }; #[cfg(feature = "pbr_transmission_textures")] use bevy_pbr::UvChannel; use bevy_pbr::{MeshMaterial3d, StandardMaterial, MAX_JOINTS}; use bevy_platform::collections::{HashMap, HashSet}; use bevy_reflect::TypePath; use bevy_render::render_resource::Face; use bevy_scene::Scene; #[cfg(not(target_arch = "wasm32"))] use bevy_tasks::IoTaskPool; use bevy_transform::components::Transform; use gltf::{ accessor::Iter, image::Source, mesh::{util::ReadIndices, Mode}, Material, Node, Semantic, }; use serde::{Deserialize, Serialize}; #[cfg(feature = "bevy_animation")] use smallvec::SmallVec; use std::{io::Error, sync::Mutex}; use thiserror::Error; use tracing::{error, info_span, warn}; use crate::{ convert_coordinates::ConvertCoordinates as _, vertex_attributes::convert_attribute, Gltf, GltfAssetLabel, GltfExtras, GltfMaterialExtras, GltfMaterialName, GltfMeshExtras, GltfMeshName, GltfNode, GltfSceneExtras, GltfSkin, }; #[cfg(feature = "bevy_animation")] use self::gltf_ext::scene::collect_path; use self::{ extensions::{AnisotropyExtension, ClearcoatExtension, SpecularExtension}, gltf_ext::{ check_for_cycles, get_linear_textures, material::{ alpha_mode, material_label, needs_tangents, uv_channel, warn_on_differing_texture_transforms, }, mesh::{primitive_name, primitive_topology}, scene::{node_name, node_transform}, texture::{texture_sampler, texture_transform_to_affine2}, }, }; use crate::convert_coordinates::GltfConvertCoordinates; /// An error that occurs when loading a glTF file. #[derive(Error, Debug)] pub enum GltfError { /// Unsupported primitive mode. #[error("unsupported primitive mode")] UnsupportedPrimitive { /// The primitive mode. mode: Mode, }, /// Invalid glTF file. #[error("invalid glTF file: {0}")] Gltf(#[from] gltf::Error), /// Binary blob is missing. #[error("binary blob is missing")] MissingBlob, /// Decoding the base64 mesh data failed. #[error("failed to decode base64 mesh data")] Base64Decode(#[from] base64::DecodeError), /// Unsupported buffer format. #[error("unsupported buffer format")] BufferFormatUnsupported, /// The buffer URI was unable to be resolved with respect to the asset path. #[error("invalid buffer uri: {0}. asset path error={1}")] InvalidBufferUri(String, ParseAssetPathError), /// Invalid image mime type. #[error("invalid image mime type: {0}")] #[from(ignore)] InvalidImageMimeType(String), /// Error when loading a texture. Might be due to a disabled image file format feature. #[error("You may need to add the feature for the file format: {0}")] ImageError(#[from] TextureError), /// The image URI was unable to be resolved with respect to the asset path. #[error("invalid image uri: {0}. asset path error={1}")] InvalidImageUri(String, ParseAssetPathError), /// Failed to read bytes from an asset path. #[error("failed to read bytes from an asset path: {0}")] ReadAssetBytesError(#[from] ReadAssetBytesError), /// Failed to load asset from an asset path. #[error("failed to load asset from an asset path: {0}")] AssetLoadError(#[from] AssetLoadError), /// Missing sampler for an animation. #[error("Missing sampler for animation {0}")] #[from(ignore)] MissingAnimationSampler(usize), /// Failed to generate tangents. #[error("failed to generate tangents: {0}")] GenerateTangentsError(#[from] bevy_mesh::GenerateTangentsError), /// Failed to generate morph targets. #[error("failed to generate morph targets: {0}")] MorphTarget(#[from] bevy_mesh::morph::MorphBuildError), /// Circular children in Nodes #[error("GLTF model must be a tree, found cycle instead at node indices: {0:?}")] #[from(ignore)] CircularChildren(String), /// Failed to load a file. #[error("failed to load file: {0}")] Io(#[from] Error), } /// Loads glTF files with all of their data as their corresponding bevy representations. #[derive(TypePath)] pub struct GltfLoader { /// List of compressed image formats handled by the loader. pub supported_compressed_formats: CompressedImageFormats, /// Custom vertex attributes that will be recognized when loading a glTF file. /// /// Keys must be the attribute names as found in the glTF data, which must start with an underscore. /// See [this section of the glTF specification](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview) /// for additional details on custom attributes. pub custom_vertex_attributes: HashMap<Box<str>, MeshVertexAttribute>, /// Arc to default [`ImageSamplerDescriptor`]. pub default_sampler: Arc<Mutex<ImageSamplerDescriptor>>, /// The default glTF coordinate conversion setting. This can be overridden /// per-load by [`GltfLoaderSettings::convert_coordinates`]. pub default_convert_coordinates: GltfConvertCoordinates, /// glTF extension data processors. /// These are Bevy-side processors designed to access glTF /// extension data during the loading process. pub extensions: Arc<RwLock<Vec<Box<dyn extensions::GltfExtensionHandler>>>>, } /// Specifies optional settings for processing gltfs at load time. By default, all recognized contents of /// the gltf will be loaded. /// /// # Example /// /// To load a gltf but exclude the cameras, replace a call to `asset_server.load("my.gltf")` with /// ```no_run /// # use bevy_asset::{AssetServer, Handle}; /// # use bevy_gltf::*; /// # let asset_server: AssetServer = panic!(); /// let gltf_handle: Handle<Gltf> = asset_server.load_with_settings( /// "my.gltf", /// |s: &mut GltfLoaderSettings| { /// s.load_cameras = false; /// } /// ); /// ``` #[derive(Serialize, Deserialize)] pub struct GltfLoaderSettings { /// If empty, the gltf mesh nodes will be skipped. /// /// Otherwise, nodes will be loaded and retained in RAM/VRAM according to the active flags. pub load_meshes: RenderAssetUsages, /// If empty, the gltf materials will be skipped. /// /// Otherwise, materials will be loaded and retained in RAM/VRAM according to the active flags. pub load_materials: RenderAssetUsages, /// If true, the loader will spawn cameras for gltf camera nodes. pub load_cameras: bool, /// If true, the loader will spawn lights for gltf light nodes. pub load_lights: bool, /// If true, the loader will load `AnimationClip` assets, and also add /// `AnimationTarget` and `AnimationPlayer` components to hierarchies /// affected by animation. Requires the `bevy_animation` feature. pub load_animations: bool, /// If true, the loader will include the root of the gltf root node. pub include_source: bool, /// Overrides the default sampler. Data from sampler node is added on top of that. /// /// If None, uses the global default which is stored in the [`DefaultGltfImageSampler`](crate::DefaultGltfImageSampler) resource. pub default_sampler: Option<ImageSamplerDescriptor>, /// If true, the loader will ignore sampler data from gltf and use the default sampler. pub override_sampler: bool, /// Overrides the default glTF coordinate conversion setting. /// /// If `None`, uses the global default set by [`GltfPlugin::convert_coordinates`](crate::GltfPlugin::convert_coordinates). pub convert_coordinates: Option<GltfConvertCoordinates>, } impl Default for GltfLoaderSettings { fn default() -> Self { Self { load_meshes: RenderAssetUsages::default(), load_materials: RenderAssetUsages::default(), load_cameras: true, load_lights: true, load_animations: true, include_source: false, default_sampler: None, override_sampler: false, convert_coordinates: None, } } } impl GltfLoader { /// Loads an entire glTF file. pub async fn load_gltf<'a, 'b, 'c>( loader: &GltfLoader, bytes: &'a [u8], load_context: &'b mut LoadContext<'c>, settings: &'b GltfLoaderSettings, ) -> Result<Gltf, GltfError> { let gltf = gltf::Gltf::from_slice(bytes)?; // clone extensions to start with a fresh processing state let mut extensions = loader.extensions.read().await.clone(); // Extensions can have data on the "root" of the glTF data. // Let extensions process the root data for the extension ids // they've subscribed to. for extension in extensions.iter_mut() { extension.on_root(&gltf); } let file_name = load_context .path() .path() .to_str() .ok_or(GltfError::Gltf(gltf::Error::Io(Error::new( std::io::ErrorKind::InvalidInput, "Gltf file name invalid", ))))? .to_string(); let buffer_data = load_buffers(&gltf, load_context).await?; let linear_textures = get_linear_textures(&gltf.document); #[cfg(feature = "bevy_animation")] let paths = if settings.load_animations { let mut paths = HashMap::<usize, (usize, Vec<Name>)>::default(); for scene in gltf.scenes() { for node in scene.nodes() { let root_index = node.index(); collect_path(&node, &[], &mut paths, root_index, &mut HashSet::default()); } } paths } else { Default::default() }; let convert_coordinates = match settings.convert_coordinates { Some(convert_coordinates) => convert_coordinates, None => loader.default_convert_coordinates, }; #[cfg(feature = "bevy_animation")] let (animations, named_animations, animation_roots) = if settings.load_animations { use bevy_animation::{ animated_field, animation_curves::*, gltf_curves::*, VariableCurve, }; use bevy_math::{ curve::{ConstantCurve, Interval, UnevenSampleAutoCurve}, Quat, Vec4, }; use gltf::animation::util::ReadOutputs; let mut animations = vec![]; let mut named_animations = <HashMap<_, _>>::default(); let mut animation_roots = <HashSet<_>>::default(); for animation in gltf.animations() { let mut animation_clip = AnimationClip::default(); for channel in animation.channels() { let node = channel.target().node(); let interpolation = channel.sampler().interpolation(); let reader = channel.reader(|buffer| Some(&buffer_data[buffer.index()])); let keyframe_timestamps: Vec<f32> = if let Some(inputs) = reader.read_inputs() { match inputs { Iter::Standard(times) => times.collect(), Iter::Sparse(_) => { warn!("Sparse accessor not supported for animation sampler input"); continue; } } } else { warn!("Animations without a sampler input are not supported"); return Err(GltfError::MissingAnimationSampler(animation.index())); }; if keyframe_timestamps.is_empty() { warn!("Tried to load animation with no keyframe timestamps"); continue; } let maybe_curve: Option<VariableCurve> = if let Some(outputs) = reader.read_outputs() { match outputs { ReadOutputs::Translations(tr) => { let translation_property = animated_field!(Transform::translation); let translations: Vec<Vec3> = tr.map(Vec3::from).collect(); if keyframe_timestamps.len() == 1 { Some(VariableCurve::new(AnimatableCurve::new( translation_property, ConstantCurve::new(Interval::EVERYWHERE, translations[0]), ))) } else { match interpolation { gltf::animation::Interpolation::Linear => { UnevenSampleAutoCurve::new( keyframe_timestamps.into_iter().zip(translations), ) .ok() .map( |curve| { VariableCurve::new(AnimatableCurve::new( translation_property, curve, )) }, ) } gltf::animation::Interpolation::Step => { SteppedKeyframeCurve::new( keyframe_timestamps.into_iter().zip(translations), ) .ok() .map( |curve| { VariableCurve::new(AnimatableCurve::new( translation_property, curve, )) }, ) } gltf::animation::Interpolation::CubicSpline => { CubicKeyframeCurve::new( keyframe_timestamps, translations, ) .ok() .map( |curve| { VariableCurve::new(AnimatableCurve::new( translation_property, curve, )) }, ) } } } } ReadOutputs::Rotations(rots) => { let rotation_property = animated_field!(Transform::rotation); let rotations: Vec<Quat> = rots.into_f32().map(Quat::from_array).collect(); if keyframe_timestamps.len() == 1 { Some(VariableCurve::new(AnimatableCurve::new( rotation_property, ConstantCurve::new(Interval::EVERYWHERE, rotations[0]), ))) } else { match interpolation { gltf::animation::Interpolation::Linear => { UnevenSampleAutoCurve::new( keyframe_timestamps.into_iter().zip(rotations), ) .ok() .map( |curve| { VariableCurve::new(AnimatableCurve::new( rotation_property, curve, )) }, ) } gltf::animation::Interpolation::Step => { SteppedKeyframeCurve::new( keyframe_timestamps.into_iter().zip(rotations), ) .ok() .map( |curve| { VariableCurve::new(AnimatableCurve::new( rotation_property, curve, )) }, ) } gltf::animation::Interpolation::CubicSpline => { CubicRotationCurve::new( keyframe_timestamps, rotations.into_iter().map(Vec4::from), ) .ok() .map( |curve| { VariableCurve::new(AnimatableCurve::new( rotation_property, curve, )) }, ) } } } } ReadOutputs::Scales(scale) => { let scale_property = animated_field!(Transform::scale); let scales: Vec<Vec3> = scale.map(Vec3::from).collect(); if keyframe_timestamps.len() == 1 { Some(VariableCurve::new(AnimatableCurve::new( scale_property, ConstantCurve::new(Interval::EVERYWHERE, scales[0]), ))) } else { match interpolation { gltf::animation::Interpolation::Linear => { UnevenSampleAutoCurve::new( keyframe_timestamps.into_iter().zip(scales), ) .ok() .map( |curve| { VariableCurve::new(AnimatableCurve::new( scale_property, curve, )) }, ) } gltf::animation::Interpolation::Step => { SteppedKeyframeCurve::new( keyframe_timestamps.into_iter().zip(scales), ) .ok() .map( |curve| { VariableCurve::new(AnimatableCurve::new( scale_property, curve, )) }, ) } gltf::animation::Interpolation::CubicSpline => { CubicKeyframeCurve::new(keyframe_timestamps, scales) .ok() .map(|curve| { VariableCurve::new(AnimatableCurve::new( scale_property, curve, )) }) } } } } ReadOutputs::MorphTargetWeights(weights) => { let weights: Vec<f32> = weights.into_f32().collect(); if keyframe_timestamps.len() == 1 { #[expect( clippy::unnecessary_map_on_constructor, reason = "While the mapping is unnecessary, it is much more readable at this level of indentation. Additionally, mapping makes it more consistent with the other branches." )] Some(ConstantCurve::new(Interval::EVERYWHERE, weights)) .map(WeightsCurve) .map(VariableCurve::new) } else { match interpolation { gltf::animation::Interpolation::Linear => { WideLinearKeyframeCurve::new( keyframe_timestamps, weights, ) .ok() .map(WeightsCurve) .map(VariableCurve::new) } gltf::animation::Interpolation::Step => { WideSteppedKeyframeCurve::new( keyframe_timestamps, weights, ) .ok() .map(WeightsCurve) .map(VariableCurve::new) } gltf::animation::Interpolation::CubicSpline => { WideCubicKeyframeCurve::new( keyframe_timestamps, weights, ) .ok() .map(WeightsCurve) .map(VariableCurve::new) } } } } } } else { warn!("Animations without a sampler output are not supported"); return Err(GltfError::MissingAnimationSampler(animation.index())); }; let Some(curve) = maybe_curve else { warn!( "Invalid keyframe data for node {}; curve could not be constructed", node.index() ); continue; }; if let Some((root_index, path)) = paths.get(&node.index()) { animation_roots.insert(*root_index); animation_clip.add_variable_curve_to_target( AnimationTargetId::from_names(path.iter()), curve, ); } else { warn!( "Animation ignored for node {}: part of its hierarchy is missing a name", node.index() ); } } let handle = load_context.add_labeled_asset( GltfAssetLabel::Animation(animation.index()).to_string(), animation_clip, ); if let Some(name) = animation.name() { named_animations.insert(name.into(), handle.clone()); } // let extensions handle extension data placed on animations for extension in extensions.iter_mut() { extension.on_animation(&animation, handle.clone()); } animations.push(handle); } // let extensions process the collection of animation data // this only happens once for each GltfExtensionHandler because // it is a hook for Bevy's finalized representation of the animations for extension in extensions.iter_mut() { extension.on_animations_collected( load_context, &animations, &named_animations, &animation_roots, ); } (animations, named_animations, animation_roots) } else { Default::default() }; let default_sampler = match settings.default_sampler.as_ref() { Some(sampler) => sampler, None => &loader.default_sampler.lock().unwrap().clone(), }; // We collect handles to ensure loaded images from paths are not unloaded before they are used elsewhere // in the loader. This prevents "reloads", but it also prevents dropping the is_srgb context on reload. // // In theory we could store a mapping between texture.index() and handle to use // later in the loader when looking up handles for materials. However this would mean // that the material's load context would no longer track those images as dependencies. let mut texture_handles = Vec::new(); if gltf.textures().len() == 1 || cfg!(target_arch = "wasm32") { for texture in gltf.textures() { let image = load_image( texture.clone(), &buffer_data, &linear_textures, load_context.path(), loader.supported_compressed_formats, default_sampler, settings, ) .await?; image.process_loaded_texture(load_context, &mut texture_handles); // let extensions handle texture data for extension in extensions.iter_mut() { extension.on_texture(&texture, texture_handles.last().unwrap().clone()); } } } else { #[cfg(not(target_arch = "wasm32"))] IoTaskPool::get() .scope(|scope| { gltf.textures().for_each(|gltf_texture| { let asset_path = load_context.path().clone(); let linear_textures = &linear_textures; let buffer_data = &buffer_data; scope.spawn(async move { load_image( gltf_texture, buffer_data, linear_textures, &asset_path, loader.supported_compressed_formats, default_sampler, settings, ) .await }); }); }) .into_iter() // order is preserved if the futures are only spawned from the root scope .zip(gltf.textures()) .for_each(|(result, texture)| match result { Ok(image) => { image.process_loaded_texture(load_context, &mut texture_handles); // let extensions handle texture data for extension in extensions.iter_mut() { extension.on_texture(&texture, texture_handles.last().unwrap().clone()); } } Err(err) => { warn!("Error loading glTF texture: {}", err); } }); } let mut materials = vec![]; let mut named_materials = <HashMap<_, _>>::default(); // Only include materials in the output if they're set to be retained in the MAIN_WORLD and/or RENDER_WORLD by the load_materials flag if !settings.load_materials.is_empty() { // NOTE: materials must be loaded after textures because image load() calls will happen before load_with_settings, preventing is_srgb from being set properly for material in gltf.materials() { let handle = { let (label, material) = load_material( &material, &texture_handles, false, load_context.path().clone(), ); load_context.add_labeled_asset(label, material) }; if let Some(name) = material.name() { named_materials.insert(name.into(), handle.clone()); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gltf/src/loader/gltf_ext/texture.rs
crates/bevy_gltf/src/loader/gltf_ext/texture.rs
use bevy_image::{ImageAddressMode, ImageFilterMode, ImageSamplerDescriptor}; use bevy_math::Affine2; use gltf::texture::{MagFilter, MinFilter, Texture, TextureTransform, WrappingMode}; /// Extracts the texture sampler data from the glTF [`Texture`]. pub(crate) fn texture_sampler( texture: &Texture<'_>, default_sampler: &ImageSamplerDescriptor, ) -> ImageSamplerDescriptor { let gltf_sampler = texture.sampler(); let mut sampler = default_sampler.clone(); sampler.address_mode_u = address_mode(&gltf_sampler.wrap_s()); sampler.address_mode_v = address_mode(&gltf_sampler.wrap_t()); // Shouldn't parse filters when anisotropic filtering is on, because trilinear is then required by wgpu. // We also trust user to have provided a valid sampler. if sampler.anisotropy_clamp == 1 { if let Some(mag_filter) = gltf_sampler.mag_filter().map(|mf| match mf { MagFilter::Nearest => ImageFilterMode::Nearest, MagFilter::Linear => ImageFilterMode::Linear, }) { sampler.mag_filter = mag_filter; } if let Some(min_filter) = gltf_sampler.min_filter().map(|mf| match mf { MinFilter::Nearest | MinFilter::NearestMipmapNearest | MinFilter::NearestMipmapLinear => ImageFilterMode::Nearest, MinFilter::Linear | MinFilter::LinearMipmapNearest | MinFilter::LinearMipmapLinear => { ImageFilterMode::Linear } }) { sampler.min_filter = min_filter; } if let Some(mipmap_filter) = gltf_sampler.min_filter().map(|mf| match mf { MinFilter::Nearest | MinFilter::Linear | MinFilter::NearestMipmapNearest | MinFilter::LinearMipmapNearest => ImageFilterMode::Nearest, MinFilter::NearestMipmapLinear | MinFilter::LinearMipmapLinear => { ImageFilterMode::Linear } }) { sampler.mipmap_filter = mipmap_filter; } } sampler } pub(crate) fn address_mode(wrapping_mode: &WrappingMode) -> ImageAddressMode { match wrapping_mode { WrappingMode::ClampToEdge => ImageAddressMode::ClampToEdge, WrappingMode::Repeat => ImageAddressMode::Repeat, WrappingMode::MirroredRepeat => ImageAddressMode::MirrorRepeat, } } pub(crate) fn texture_transform_to_affine2(texture_transform: TextureTransform) -> Affine2 { Affine2::from_scale_angle_translation( texture_transform.scale().into(), -texture_transform.rotation(), texture_transform.offset().into(), ) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gltf/src/loader/gltf_ext/mesh.rs
crates/bevy_gltf/src/loader/gltf_ext/mesh.rs
use bevy_mesh::PrimitiveTopology; use gltf::{ mesh::{Mesh, Mode}, Material, }; use crate::GltfError; pub(crate) fn primitive_name(mesh: &Mesh<'_>, material: &Material) -> String { let mesh_name = mesh.name().unwrap_or("Mesh"); if let Some(material_name) = material.name() { format!("{mesh_name}.{material_name}") } else { mesh_name.to_string() } } /// Maps the `primitive_topology` from glTF to `wgpu`. #[cfg_attr( not(target_arch = "wasm32"), expect( clippy::result_large_err, reason = "`GltfError` is only barely past the threshold for large errors." ) )] pub(crate) fn primitive_topology(mode: Mode) -> Result<PrimitiveTopology, GltfError> { match mode { Mode::Points => Ok(PrimitiveTopology::PointList), Mode::Lines => Ok(PrimitiveTopology::LineList), Mode::LineStrip => Ok(PrimitiveTopology::LineStrip), Mode::Triangles => Ok(PrimitiveTopology::TriangleList), Mode::TriangleStrip => Ok(PrimitiveTopology::TriangleStrip), mode => Err(GltfError::UnsupportedPrimitive { mode }), } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gltf/src/loader/gltf_ext/scene.rs
crates/bevy_gltf/src/loader/gltf_ext/scene.rs
use bevy_ecs::name::Name; use bevy_math::{Mat4, Vec3}; use bevy_transform::components::Transform; use gltf::scene::Node; use fixedbitset::FixedBitSet; use itertools::Itertools; #[cfg(feature = "bevy_animation")] use bevy_platform::collections::{HashMap, HashSet}; use crate::GltfError; pub(crate) fn node_name(node: &Node) -> Name { let name = node .name() .map(ToString::to_string) .unwrap_or_else(|| format!("GltfNode{}", node.index())); Name::new(name) } /// Calculate the transform of gLTF [`Node`]. /// /// This should be used instead of calling [`gltf::scene::Transform::matrix()`] /// on [`Node::transform()`](gltf::Node::transform) directly because it uses optimized glam types and /// if `libm` feature of `bevy_math` crate is enabled also handles cross /// platform determinism properly. pub(crate) fn node_transform(node: &Node) -> Transform { match node.transform() { gltf::scene::Transform::Matrix { matrix } => { Transform::from_matrix(Mat4::from_cols_array_2d(&matrix)) } gltf::scene::Transform::Decomposed { translation, rotation, scale, } => Transform { translation: Vec3::from(translation), rotation: bevy_math::Quat::from_array(rotation), scale: Vec3::from(scale), }, } } #[cfg_attr( not(target_arch = "wasm32"), expect( clippy::result_large_err, reason = "need to be signature compatible with `load_gltf`" ) )] /// Check if [`Node`] is part of cycle pub(crate) fn check_is_part_of_cycle( node: &Node, visited: &mut FixedBitSet, ) -> Result<(), GltfError> { // Do we have a cycle? if visited.contains(node.index()) { return Err(GltfError::CircularChildren(format!( "glTF nodes form a cycle: {} -> {}", visited.ones().map(|bit| bit.to_string()).join(" -> "), node.index() ))); } // Recurse. visited.insert(node.index()); for kid in node.children() { check_is_part_of_cycle(&kid, visited)?; } visited.remove(node.index()); Ok(()) } #[cfg(feature = "bevy_animation")] pub(crate) fn collect_path( node: &Node, current_path: &[Name], paths: &mut HashMap<usize, (usize, Vec<Name>)>, root_index: usize, visited: &mut HashSet<usize>, ) { let mut path = current_path.to_owned(); path.push(node_name(node)); visited.insert(node.index()); for child in node.children() { if !visited.contains(&child.index()) { collect_path(&child, &path, paths, root_index, visited); } } paths.insert(node.index(), (root_index, path)); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gltf/src/loader/gltf_ext/material.rs
crates/bevy_gltf/src/loader/gltf_ext/material.rs
use bevy_math::Affine2; use bevy_pbr::UvChannel; use bevy_render::alpha::AlphaMode; use gltf::{json::texture::Info, Material}; use serde_json::value; use crate::GltfAssetLabel; use super::texture::texture_transform_to_affine2; #[cfg(any( feature = "pbr_anisotropy_texture", feature = "pbr_specular_textures", feature = "pbr_multi_layer_material_textures" ))] use { bevy_asset::{AssetPath, Handle}, bevy_image::Image, serde_json::{Map, Value}, }; /// Parses a texture that's part of a material extension block and returns its /// UV channel and image reference. #[cfg(any( feature = "pbr_anisotropy_texture", feature = "pbr_specular_textures", feature = "pbr_multi_layer_material_textures" ))] pub(crate) fn parse_material_extension_texture( material: &Material, extension: &Map<String, Value>, texture_name: &str, texture_kind: &str, textures: &[Handle<Image>], asset_path: AssetPath<'_>, ) -> (UvChannel, Option<Handle<Image>>) { match extension .get(texture_name) .and_then(|value| value::from_value::<Info>(value.clone()).ok()) { Some(json_info) => ( uv_channel(material, texture_kind, json_info.tex_coord), Some({ match textures.get(json_info.index.value()).cloned() { None => { tracing::warn!("Gltf at path \"{asset_path}\" contains invalid texture index <{}> for texture {texture_name}. Using default image.", json_info.index.value()); Handle::default() } Some(handle) => handle, } }), ), None => (UvChannel::default(), None), } } pub(crate) fn uv_channel(material: &Material, texture_kind: &str, tex_coord: u32) -> UvChannel { match tex_coord { 0 => UvChannel::Uv0, 1 => UvChannel::Uv1, _ => { let material_name = material .name() .map(|n| format!("the material \"{n}\"")) .unwrap_or_else(|| "an unnamed material".to_string()); let material_index = material .index() .map(|i| format!("index {i}")) .unwrap_or_else(|| "default".to_string()); tracing::warn!( "Only 2 UV Channels are supported, but {material_name} ({material_index}) \ has the TEXCOORD attribute {} on texture kind {texture_kind}, which will fallback to 0.", tex_coord, ); UvChannel::Uv0 } } } pub(crate) fn alpha_mode(material: &Material) -> AlphaMode { match material.alpha_mode() { gltf::material::AlphaMode::Opaque => AlphaMode::Opaque, gltf::material::AlphaMode::Mask => AlphaMode::Mask(material.alpha_cutoff().unwrap_or(0.5)), gltf::material::AlphaMode::Blend => AlphaMode::Blend, } } /// Returns the index (within the `textures` array) of the texture with the /// given field name in the data for the material extension with the given name, /// if there is one. pub(crate) fn extension_texture_index( material: &Material, extension_name: &str, texture_field_name: &str, ) -> Option<usize> { Some( value::from_value::<Info>( material .extensions()? .get(extension_name)? .as_object()? .get(texture_field_name)? .clone(), ) .ok()? .index .value(), ) } /// Returns true if the material needs mesh tangents in order to be successfully /// rendered. /// /// We generate them if this function returns true. pub(crate) fn needs_tangents(material: &Material) -> bool { [ material.normal_texture().is_some(), #[cfg(feature = "pbr_multi_layer_material_textures")] extension_texture_index( material, "KHR_materials_clearcoat", "clearcoatNormalTexture", ) .is_some(), ] .into_iter() .reduce(|a, b| a || b) .unwrap_or(false) } pub(crate) fn warn_on_differing_texture_transforms( material: &Material, info: &gltf::texture::Info, texture_transform: Affine2, texture_kind: &str, ) { let has_differing_texture_transform = info .texture_transform() .map(texture_transform_to_affine2) .is_some_and(|t| t != texture_transform); if has_differing_texture_transform { let material_name = material .name() .map(|n| format!("the material \"{n}\"")) .unwrap_or_else(|| "an unnamed material".to_string()); let texture_name = info .texture() .name() .map(|n| format!("its {texture_kind} texture \"{n}\"")) .unwrap_or_else(|| format!("its unnamed {texture_kind} texture")); let material_index = material .index() .map(|i| format!("index {i}")) .unwrap_or_else(|| "default".to_string()); tracing::warn!( "Only texture transforms on base color textures are supported, but {material_name} ({material_index}) \ has a texture transform on {texture_name} (index {}), which will be ignored.", info.texture().index() ); } } pub(crate) fn material_label(material: &Material, is_scale_inverted: bool) -> GltfAssetLabel { if let Some(index) = material.index() { GltfAssetLabel::Material { index, is_scale_inverted, } } else { GltfAssetLabel::DefaultMaterial } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gltf/src/loader/gltf_ext/mod.rs
crates/bevy_gltf/src/loader/gltf_ext/mod.rs
//! Methods to access information from [`gltf`] types pub mod material; pub mod mesh; pub mod scene; pub mod texture; use bevy_platform::collections::HashSet; use fixedbitset::FixedBitSet; use gltf::{Document, Gltf}; use super::GltfError; use self::{material::extension_texture_index, scene::check_is_part_of_cycle}; #[cfg_attr( not(target_arch = "wasm32"), expect( clippy::result_large_err, reason = "need to be signature compatible with `load_gltf`" ) )] /// Checks all glTF nodes for cycles, starting at the scene root. pub(crate) fn check_for_cycles(gltf: &Gltf) -> Result<(), GltfError> { // Initialize with the scene roots. let mut roots = FixedBitSet::with_capacity(gltf.nodes().len()); for root in gltf.scenes().flat_map(|scene| scene.nodes()) { roots.insert(root.index()); } // Check each one. let mut visited = FixedBitSet::with_capacity(gltf.nodes().len()); for root in roots.ones() { let Some(node) = gltf.nodes().nth(root) else { unreachable!("Index of a root node should always exist."); }; check_is_part_of_cycle(&node, &mut visited)?; } Ok(()) } pub(crate) fn get_linear_textures(document: &Document) -> HashSet<usize> { let mut linear_textures = HashSet::default(); for material in document.materials() { if let Some(texture) = material.normal_texture() { linear_textures.insert(texture.texture().index()); } if let Some(texture) = material.occlusion_texture() { linear_textures.insert(texture.texture().index()); } if let Some(texture) = material .pbr_metallic_roughness() .metallic_roughness_texture() { linear_textures.insert(texture.texture().index()); } if let Some(texture_index) = extension_texture_index(&material, "KHR_materials_anisotropy", "anisotropyTexture") { linear_textures.insert(texture_index); } // None of the clearcoat maps should be loaded as sRGB. #[cfg(feature = "pbr_multi_layer_material_textures")] for texture_field_name in [ "clearcoatTexture", "clearcoatRoughnessTexture", "clearcoatNormalTexture", ] { if let Some(texture_index) = extension_texture_index(&material, "KHR_materials_clearcoat", texture_field_name) { linear_textures.insert(texture_index); } } } linear_textures }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gltf/src/loader/extensions/khr_materials_clearcoat.rs
crates/bevy_gltf/src/loader/extensions/khr_materials_clearcoat.rs
use bevy_asset::{AssetPath, Handle}; use bevy_image::Image; use gltf::Material; use serde_json::Value; #[cfg(feature = "pbr_multi_layer_material_textures")] use {crate::loader::gltf_ext::material::parse_material_extension_texture, bevy_pbr::UvChannel}; /// Parsed data from the `KHR_materials_clearcoat` extension. /// /// See the specification: /// <https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_clearcoat/README.md> #[derive(Default)] pub(crate) struct ClearcoatExtension { pub(crate) clearcoat_factor: Option<f64>, #[cfg(feature = "pbr_multi_layer_material_textures")] pub(crate) clearcoat_channel: UvChannel, #[cfg(feature = "pbr_multi_layer_material_textures")] pub(crate) clearcoat_texture: Option<Handle<Image>>, pub(crate) clearcoat_roughness_factor: Option<f64>, #[cfg(feature = "pbr_multi_layer_material_textures")] pub(crate) clearcoat_roughness_channel: UvChannel, #[cfg(feature = "pbr_multi_layer_material_textures")] pub(crate) clearcoat_roughness_texture: Option<Handle<Image>>, #[cfg(feature = "pbr_multi_layer_material_textures")] pub(crate) clearcoat_normal_channel: UvChannel, #[cfg(feature = "pbr_multi_layer_material_textures")] pub(crate) clearcoat_normal_texture: Option<Handle<Image>>, } impl ClearcoatExtension { #[expect( clippy::allow_attributes, reason = "`unused_variables` is not always linted" )] #[allow( unused_variables, reason = "Depending on what features are used to compile this crate, certain parameters may end up unused." )] pub(crate) fn parse( material: &Material, textures: &[Handle<Image>], asset_path: AssetPath<'_>, ) -> Option<ClearcoatExtension> { let extension = material .extensions()? .get("KHR_materials_clearcoat")? .as_object()?; #[cfg(feature = "pbr_multi_layer_material_textures")] let (clearcoat_channel, clearcoat_texture) = parse_material_extension_texture( material, extension, "clearcoatTexture", "clearcoat", textures, asset_path.clone(), ); #[cfg(feature = "pbr_multi_layer_material_textures")] let (clearcoat_roughness_channel, clearcoat_roughness_texture) = parse_material_extension_texture( material, extension, "clearcoatRoughnessTexture", "clearcoat roughness", textures, asset_path.clone(), ); #[cfg(feature = "pbr_multi_layer_material_textures")] let (clearcoat_normal_channel, clearcoat_normal_texture) = parse_material_extension_texture( material, extension, "clearcoatNormalTexture", "clearcoat normal", textures, asset_path, ); Some(ClearcoatExtension { clearcoat_factor: extension.get("clearcoatFactor").and_then(Value::as_f64), clearcoat_roughness_factor: extension .get("clearcoatRoughnessFactor") .and_then(Value::as_f64), #[cfg(feature = "pbr_multi_layer_material_textures")] clearcoat_channel, #[cfg(feature = "pbr_multi_layer_material_textures")] clearcoat_texture, #[cfg(feature = "pbr_multi_layer_material_textures")] clearcoat_roughness_channel, #[cfg(feature = "pbr_multi_layer_material_textures")] clearcoat_roughness_texture, #[cfg(feature = "pbr_multi_layer_material_textures")] clearcoat_normal_channel, #[cfg(feature = "pbr_multi_layer_material_textures")] clearcoat_normal_texture, }) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gltf/src/loader/extensions/khr_materials_specular.rs
crates/bevy_gltf/src/loader/extensions/khr_materials_specular.rs
use bevy_asset::{AssetPath, Handle}; use bevy_image::Image; use gltf::Material; use serde_json::Value; #[cfg(feature = "pbr_specular_textures")] use {crate::loader::gltf_ext::material::parse_material_extension_texture, bevy_pbr::UvChannel}; /// Parsed data from the `KHR_materials_specular` extension. /// /// We currently don't parse `specularFactor` and `specularTexture`, since /// they're incompatible with Filament. /// /// Note that the map is a *specular map*, not a *reflectance map*. In Bevy and /// Filament terms, the reflectance values in the specular map range from [0.0, /// 0.5], rather than [0.0, 1.0]. This is an unfortunate /// `KHR_materials_specular` specification requirement that stems from the fact /// that glTF is specified in terms of a specular strength model, not the /// reflectance model that Filament and Bevy use. A workaround, which is noted /// in the [`StandardMaterial`](bevy_pbr::StandardMaterial) documentation, is to set the reflectance value /// to 2.0, which spreads the specular map range from [0.0, 1.0] as normal. /// /// See the specification: /// <https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_specular/README.md> #[derive(Default)] pub(crate) struct SpecularExtension { pub(crate) specular_factor: Option<f64>, #[cfg(feature = "pbr_specular_textures")] pub(crate) specular_channel: UvChannel, #[cfg(feature = "pbr_specular_textures")] pub(crate) specular_texture: Option<Handle<Image>>, pub(crate) specular_color_factor: Option<[f64; 3]>, #[cfg(feature = "pbr_specular_textures")] pub(crate) specular_color_channel: UvChannel, #[cfg(feature = "pbr_specular_textures")] pub(crate) specular_color_texture: Option<Handle<Image>>, } impl SpecularExtension { #[expect( clippy::allow_attributes, reason = "`unused_variables` is not always linted" )] #[allow( unused_variables, reason = "Depending on what features are used to compile this crate, certain parameters may end up unused." )] pub(crate) fn parse( material: &Material, textures: &[Handle<Image>], asset_path: AssetPath<'_>, ) -> Option<Self> { let extension = material .extensions()? .get("KHR_materials_specular")? .as_object()?; #[cfg(feature = "pbr_specular_textures")] let (_specular_channel, _specular_texture) = parse_material_extension_texture( material, extension, "specularTexture", "specular", textures, asset_path.clone(), ); #[cfg(feature = "pbr_specular_textures")] let (_specular_color_channel, _specular_color_texture) = parse_material_extension_texture( material, extension, "specularColorTexture", "specular color", textures, asset_path, ); Some(SpecularExtension { specular_factor: extension.get("specularFactor").and_then(Value::as_f64), #[cfg(feature = "pbr_specular_textures")] specular_channel: _specular_channel, #[cfg(feature = "pbr_specular_textures")] specular_texture: _specular_texture, specular_color_factor: extension .get("specularColorFactor") .and_then(Value::as_array) .and_then(|json_array| { if json_array.len() < 3 { None } else { Some([ json_array[0].as_f64()?, json_array[1].as_f64()?, json_array[2].as_f64()?, ]) } }), #[cfg(feature = "pbr_specular_textures")] specular_color_channel: _specular_color_channel, #[cfg(feature = "pbr_specular_textures")] specular_color_texture: _specular_color_texture, }) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gltf/src/loader/extensions/mod.rs
crates/bevy_gltf/src/loader/extensions/mod.rs
//! glTF extensions defined by the Khronos Group and other vendors mod khr_materials_anisotropy; mod khr_materials_clearcoat; mod khr_materials_specular; use alloc::sync::Arc; use async_lock::RwLock; use bevy_asset::{Handle, LoadContext}; use bevy_ecs::{ entity::Entity, resource::Resource, world::{EntityWorldMut, World}, }; use bevy_pbr::StandardMaterial; use gltf::Node; #[cfg(feature = "bevy_animation")] use { bevy_animation::AnimationClip, bevy_platform::collections::{HashMap, HashSet}, }; use crate::GltfMesh; pub(crate) use self::{ khr_materials_anisotropy::AnisotropyExtension, khr_materials_clearcoat::ClearcoatExtension, khr_materials_specular::SpecularExtension, }; /// Stores the `GltfExtensionHandler` implementations so that they /// can be added by users and also passed to the glTF loader #[derive(Resource, Default)] pub struct GltfExtensionHandlers(pub Arc<RwLock<Vec<Box<dyn GltfExtensionHandler>>>>); /// glTF Extensions can attach data to any objects in a glTF file. /// This is done by inserting data in the `extensions` sub-object, and /// data in the extensions sub-object is keyed by the id of the extension. /// For example: `KHR_materials_variants`, `EXT_meshopt_compression`, or `BEVY_my_tool` /// /// A list of publicly known extensions and their ids can be found /// in the [KhronosGroup/glTF](https://github.com/KhronosGroup/glTF/blob/main/extensions/README.md) /// git repo. Vendors reserve prefixes, such as the `BEVY` prefix, /// which is also listed in the [KhronosGroup repo](https://github.com/KhronosGroup/glTF/blob/main/extensions/Prefixes.md). /// /// The `GltfExtensionHandler` trait should be implemented to participate in /// processing glTF files as they load, and exposes glTF extension data via /// a series of hook callbacks. /// /// The type a `GltfExtensionHandler` is implemented for can define data /// which will be cloned for each new glTF load. This enables stateful /// handling of glTF extension data during a single load. /// /// When loading a glTF file, a glTF object that could contain extension /// data will cause the relevant hook to execute once per object. /// Each invocation will receive all extension data, which is required because /// many extensions require accessing data defined by other extensions. /// /// The hooks are always called once, even if there is no extension data /// This is useful for scenarios where additional extension data isn't /// required, but processing should still happen. pub trait GltfExtensionHandler: Send + Sync { /// Required for dyn cloning fn dyn_clone(&self) -> Box<dyn GltfExtensionHandler>; /// Called when the "global" data for an extension /// at the root of a glTF file is encountered. #[expect( unused, reason = "default trait implementations do not use the arguments because they are no-ops" )] fn on_root(&mut self, gltf: &gltf::Gltf) {} #[cfg(feature = "bevy_animation")] #[expect( unused, reason = "default trait implementations do not use the arguments because they are no-ops" )] /// Called when an individual animation is processed fn on_animation(&mut self, gltf_animation: &gltf::Animation, handle: Handle<AnimationClip>) {} #[cfg(feature = "bevy_animation")] #[expect( unused, reason = "default trait implementations do not use the arguments because they are no-ops" )] /// Called when all animations have been collected. /// `animations` is the glTF ordered list of `Handle<AnimationClip>`s /// `named_animations` is a `HashMap` from animation name to `Handle<AnimationClip>` /// `animation_roots` is the glTF index of the animation root object fn on_animations_collected( &mut self, load_context: &mut LoadContext<'_>, animations: &[Handle<AnimationClip>], named_animations: &HashMap<Box<str>, Handle<AnimationClip>>, animation_roots: &HashSet<usize>, ) { } /// Called when an individual texture is processed #[expect( unused, reason = "default trait implementations do not use the arguments because they are no-ops" )] fn on_texture(&mut self, gltf_texture: &gltf::Texture, texture: Handle<bevy_image::Image>) {} /// Called when an individual material is processed #[expect( unused, reason = "default trait implementations do not use the arguments because they are no-ops" )] fn on_material( &mut self, load_context: &mut LoadContext<'_>, gltf_material: &gltf::Material, material: Handle<StandardMaterial>, ) { } /// Called when an individual glTF Mesh is processed #[expect( unused, reason = "default trait implementations do not use the arguments because they are no-ops" )] fn on_gltf_mesh( &mut self, load_context: &mut LoadContext<'_>, gltf_mesh: &gltf::Mesh, mesh: Handle<GltfMesh>, ) { } /// mesh and material are spawned as a single Entity, /// which means an extension would have to decide for /// itself how to merge the extension data. #[expect( unused, reason = "default trait implementations do not use the arguments because they are no-ops" )] fn on_spawn_mesh_and_material( &mut self, load_context: &mut LoadContext<'_>, primitive: &gltf::Primitive, mesh: &gltf::Mesh, material: &gltf::Material, entity: &mut EntityWorldMut, ) { } /// Called when an individual Scene is done processing #[expect( unused, reason = "default trait implementations do not use the arguments because they are no-ops" )] fn on_scene_completed( &mut self, load_context: &mut LoadContext<'_>, scene: &gltf::Scene, world_root_id: Entity, scene_world: &mut World, ) { } /// Called when a node is processed #[expect( unused, reason = "default trait implementations do not use the arguments because they are no-ops" )] fn on_gltf_node( &mut self, load_context: &mut LoadContext<'_>, gltf_node: &Node, entity: &mut EntityWorldMut, ) { } /// Called with a `DirectionalLight` node is spawned /// which is typically created as a result of /// `KHR_lights_punctual` #[expect( unused, reason = "default trait implementations do not use the arguments because they are no-ops" )] fn on_spawn_light_directional( &mut self, load_context: &mut LoadContext<'_>, gltf_node: &Node, entity: &mut EntityWorldMut, ) { } /// Called with a `PointLight` node is spawned /// which is typically created as a result of /// `KHR_lights_punctual` #[expect( unused, reason = "default trait implementations do not use the arguments because they are no-ops" )] fn on_spawn_light_point( &mut self, load_context: &mut LoadContext<'_>, gltf_node: &Node, entity: &mut EntityWorldMut, ) { } /// Called with a `SpotLight` node is spawned /// which is typically created as a result of /// `KHR_lights_punctual` #[expect( unused, reason = "default trait implementations do not use the arguments because they are no-ops" )] fn on_spawn_light_spot( &mut self, load_context: &mut LoadContext<'_>, gltf_node: &Node, entity: &mut EntityWorldMut, ) { } } impl Clone for Box<dyn GltfExtensionHandler> { fn clone(&self) -> Self { self.dyn_clone() } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gltf/src/loader/extensions/khr_materials_anisotropy.rs
crates/bevy_gltf/src/loader/extensions/khr_materials_anisotropy.rs
use bevy_asset::{AssetPath, Handle}; use bevy_image::Image; use gltf::Material; use serde_json::Value; #[cfg(feature = "pbr_anisotropy_texture")] use {crate::loader::gltf_ext::material::parse_material_extension_texture, bevy_pbr::UvChannel}; /// Parsed data from the `KHR_materials_anisotropy` extension. /// /// See the specification: /// <https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_anisotropy/README.md> #[derive(Default)] pub(crate) struct AnisotropyExtension { pub(crate) anisotropy_strength: Option<f64>, pub(crate) anisotropy_rotation: Option<f64>, #[cfg(feature = "pbr_anisotropy_texture")] pub(crate) anisotropy_channel: UvChannel, #[cfg(feature = "pbr_anisotropy_texture")] pub(crate) anisotropy_texture: Option<Handle<Image>>, } impl AnisotropyExtension { #[expect( clippy::allow_attributes, reason = "`unused_variables` is not always linted" )] #[allow( unused_variables, reason = "Depending on what features are used to compile this crate, certain parameters may end up unused." )] pub(crate) fn parse( material: &Material, textures: &[Handle<Image>], asset_path: AssetPath<'_>, ) -> Option<AnisotropyExtension> { let extension = material .extensions()? .get("KHR_materials_anisotropy")? .as_object()?; #[cfg(feature = "pbr_anisotropy_texture")] let (anisotropy_channel, anisotropy_texture) = parse_material_extension_texture( material, extension, "anisotropyTexture", "anisotropy", textures, asset_path, ); Some(AnisotropyExtension { anisotropy_strength: extension.get("anisotropyStrength").and_then(Value::as_f64), anisotropy_rotation: extension.get("anisotropyRotation").and_then(Value::as_f64), #[cfg(feature = "pbr_anisotropy_texture")] anisotropy_channel, #[cfg(feature = "pbr_anisotropy_texture")] anisotropy_texture, }) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/src/lib.rs
crates/bevy_reflect/compile_fail/src/lib.rs
// Nothing here, check out the integration tests
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/func.rs
crates/bevy_reflect/compile_fail/tests/func.rs
fn main() -> compile_fail_utils::ui_test::Result<()> { compile_fail_utils::test("reflect_into_function", "tests/into_function") }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/remote.rs
crates/bevy_reflect/compile_fail/tests/remote.rs
fn main() -> compile_fail_utils::ui_test::Result<()> { compile_fail_utils::test("reflect_remote", "tests/reflect_remote") }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/derive.rs
crates/bevy_reflect/compile_fail/tests/derive.rs
fn main() -> compile_fail_utils::ui_test::Result<()> { compile_fail_utils::test("reflect_derive", "tests/reflect_derive") }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/into_function/arguments_fail.rs
crates/bevy_reflect/compile_fail/tests/into_function/arguments_fail.rs
#![allow(unused)] use bevy_reflect::func::IntoFunction; use bevy_reflect::Reflect; fn pass(_: i32) {} fn too_many_arguments( arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32, arg5: i32, arg6: i32, arg7: i32, arg8: i32, arg9: i32, arg10: i32, arg11: i32, arg12: i32, arg13: i32, arg14: i32, arg15: i32, ) { } struct Foo; fn argument_not_reflect(foo: Foo) {} fn main() { let _ = pass.into_function(); let _ = too_many_arguments.into_function(); //~^ E0599 let _ = argument_not_reflect.into_function(); //~^ E0599 }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/into_function/return_fail.rs
crates/bevy_reflect/compile_fail/tests/into_function/return_fail.rs
#![allow(unused)] use bevy_reflect::func::IntoFunction; use bevy_reflect::Reflect; fn pass() -> i32 { 123 } struct Foo; fn return_not_reflect() -> Foo { Foo } fn return_with_lifetime_pass<'a>(a: &'a String) -> &'a String { a } fn return_with_invalid_lifetime<'a, 'b>(a: &'a String, b: &'b String) -> &'b String { b } fn main() { let _ = pass.into_function(); let _ = return_not_reflect.into_function(); //~^ E0599 let _ = return_with_lifetime_pass.into_function(); let _ = return_with_invalid_lifetime.into_function(); //~^ E0599 }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/into_function/closure_fail.rs
crates/bevy_reflect/compile_fail/tests/into_function/closure_fail.rs
#![allow(unused)] use bevy_reflect::func::{DynamicFunction, IntoFunction}; use bevy_reflect::Reflect; fn main() { let value = String::from("Hello, World!"); let closure_capture_owned = move || println!("{}", value); // Pass: let _: DynamicFunction<'static> = closure_capture_owned.into_function(); let value = String::from("Hello, World!"); let closure_capture_reference = || println!("{}", value); //~^ ERROR: `value` does not live long enough let _: DynamicFunction<'static> = closure_capture_reference.into_function(); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_remote/incorrect_wrapper_pass.rs
crates/bevy_reflect/compile_fail/tests/reflect_remote/incorrect_wrapper_pass.rs
//@check-pass use bevy_reflect::{reflect_remote, Reflect}; mod external_crate { pub struct TheirFoo { pub value: u32, } } #[reflect_remote(external_crate::TheirFoo)] struct MyFoo { pub value: u32, } #[derive(Reflect)] struct MyStruct { #[reflect(remote = MyFoo)] foo: external_crate::TheirFoo, } fn main() {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_remote/incorrect_wrapper_fail.rs
crates/bevy_reflect/compile_fail/tests/reflect_remote/incorrect_wrapper_fail.rs
use bevy_reflect::Reflect; mod external_crate { pub struct TheirFoo { pub value: u32, } } #[repr(transparent)] #[derive(Reflect)] #[reflect(from_reflect = false)] struct MyFoo(#[reflect(ignore)] pub external_crate::TheirFoo); #[derive(Reflect)] //~^ ERROR: the trait bound `MyFoo: ReflectRemote` is not satisfied #[reflect(from_reflect = false)] struct MyStruct { // Reason: `MyFoo` does not implement `ReflectRemote` (from `#[reflect_remote]` attribute) #[reflect(remote = MyFoo)] //~^ ERROR: the trait bound `MyFoo: ReflectRemote` is not satisfied foo: external_crate::TheirFoo, } fn main() {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_remote/type_mismatch_fail.rs
crates/bevy_reflect/compile_fail/tests/reflect_remote/type_mismatch_fail.rs
//@no-rustfix mod structs { use bevy_reflect::{reflect_remote, Reflect}; mod external_crate { pub struct TheirFoo { pub value: u32, } pub struct TheirBar { pub value: i32, } } #[reflect_remote(external_crate::TheirFoo)] struct MyFoo { pub value: u32, } #[reflect_remote(external_crate::TheirBar)] struct MyBar { pub value: i32, } #[derive(Reflect)] //~^ ERROR: mismatched types //~| ERROR: mismatched types struct MyStruct { // Reason: Should use `MyFoo` #[reflect(remote = MyBar)] //~^ ERROR: mismatched types foo: external_crate::TheirFoo, } } mod tuple_structs { use bevy_reflect::{reflect_remote, Reflect}; mod external_crate { pub struct TheirFoo(pub u32); pub struct TheirBar(pub i32); } #[reflect_remote(external_crate::TheirFoo)] struct MyFoo(pub u32); #[reflect_remote(external_crate::TheirBar)] struct MyBar(pub i32); #[derive(Reflect)] //~^ ERROR: mismatched types //~| ERROR: mismatched types struct MyStruct( // Reason: Should use `MyFoo` #[reflect(remote = MyBar)] external_crate::TheirFoo, //~^ ERROR: mismatched types ); } mod enums { use bevy_reflect::{reflect_remote, Reflect}; mod external_crate { pub enum TheirFoo { Value(u32), } pub enum TheirBar { Value(i32), } } #[reflect_remote(external_crate::TheirFoo)] enum MyFoo { Value(u32), } #[reflect_remote(external_crate::TheirBar)] //~^ ERROR: `?` operator has incompatible types //~| ERROR: mismatched types enum MyBar { // Reason: Should use `i32` Value(u32), //~^ ERROR: mismatched types } #[derive(Reflect)] //~^ ERROR: mismatched types //~| ERROR: mismatched types //~| ERROR: mismatched types enum MyStruct { Value( // Reason: Should use `MyFoo` #[reflect(remote = MyBar)] external_crate::TheirFoo, //~^ ERROR: mismatched types ), } } fn main() {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_remote/invalid_definition_pass.rs
crates/bevy_reflect/compile_fail/tests/reflect_remote/invalid_definition_pass.rs
//@check-pass mod structs { use bevy_reflect::reflect_remote; mod external_crate { pub struct TheirStruct { pub value: u32, } } #[reflect_remote(external_crate::TheirStruct)] struct MyStruct { pub value: u32, } } mod tuple_structs { use bevy_reflect::reflect_remote; mod external_crate { pub struct TheirStruct(pub u32); } #[reflect_remote(external_crate::TheirStruct)] struct MyStruct(pub u32); } mod enums { use bevy_reflect::reflect_remote; mod external_crate { pub enum TheirStruct { Unit, Tuple(u32), Struct { value: usize }, } } #[reflect_remote(external_crate::TheirStruct)] enum MyStruct { Unit, Tuple(u32), Struct { value: usize }, } } fn main() {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_remote/macro_order_fail.rs
crates/bevy_reflect/compile_fail/tests/reflect_remote/macro_order_fail.rs
use bevy_reflect::{reflect_remote, std_traits::ReflectDefault}; mod external_crate { #[derive(Debug, Default)] pub struct TheirType { pub value: String, } } #[derive(Debug, Default)] #[reflect_remote(external_crate::TheirType)] #[reflect(Debug, Default)] struct MyType { pub value: String, //~^ ERROR: no field `value` on type `&MyType` //~| ERROR: struct `MyType` has no field named `value` } fn main() {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_remote/nested_fail.rs
crates/bevy_reflect/compile_fail/tests/reflect_remote/nested_fail.rs
mod external_crate { pub struct TheirOuter<T> { pub inner: TheirInner<T>, } pub struct TheirInner<T>(pub T); } mod missing_attribute { use bevy_reflect::{FromReflect, GetTypeRegistration, reflect_remote}; #[reflect_remote(super::external_crate::TheirOuter<T>)] struct MyOuter<T: FromReflect + GetTypeRegistration> { // Reason: Missing `#[reflect(remote = ...)]` attribute pub inner: super::external_crate::TheirInner<T>, } #[reflect_remote(super::external_crate::TheirInner<T>)] struct MyInner<T>(pub T); } mod incorrect_inner_type { use bevy_reflect::{FromReflect, GetTypeRegistration, reflect_remote}; #[reflect_remote(super::external_crate::TheirOuter<T>)] //~^ ERROR: `TheirInner<T>` does not implement `PartialReflect` so cannot be introspected //~| ERROR: `TheirInner<T>` does not implement `PartialReflect` so cannot be introspected //~| ERROR: `TheirInner<T>` does not implement `PartialReflect` so cannot be introspected //~| ERROR: `TheirInner<T>` does not implement `TypePath` so cannot provide dynamic type path information //~| ERROR: `?` operator has incompatible types //~| ERROR: mismatched types struct MyOuter<T: FromReflect + GetTypeRegistration> { // Reason: Should not use `MyInner<T>` directly pub inner: MyInner<T>, //~^ ERROR: mismatched types } #[reflect_remote(super::external_crate::TheirInner<T>)] struct MyInner<T>(pub T); } mod mismatched_remote_type { use bevy_reflect::{FromReflect, GetTypeRegistration, reflect_remote}; #[reflect_remote(super::external_crate::TheirOuter<T>)] //~^ ERROR: mismatched types //~| ERROR: mismatched types struct MyOuter<T: FromReflect + GetTypeRegistration> { // Reason: Should be `MyInner<T>` #[reflect(remote = MyOuter<T>)] //~^ ERROR: mismatched types pub inner: super::external_crate::TheirInner<T>, } #[reflect_remote(super::external_crate::TheirInner<T>)] struct MyInner<T>(pub T); } mod mismatched_remote_generic { use bevy_reflect::{FromReflect, GetTypeRegistration, reflect_remote}; #[reflect_remote(super::external_crate::TheirOuter<T>)] //~^ ERROR: `?` operator has incompatible types //~| ERROR: mismatched types //~| ERROR: mismatched types struct MyOuter<T: FromReflect + GetTypeRegistration> { // Reason: `TheirOuter::inner` is not defined as `TheirInner<bool>` #[reflect(remote = MyInner<bool>)] pub inner: super::external_crate::TheirInner<bool>, //~^ ERROR: mismatched types } #[reflect_remote(super::external_crate::TheirInner<T>)] struct MyInner<T>(pub T); } fn main() {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_remote/type_mismatch_pass.rs
crates/bevy_reflect/compile_fail/tests/reflect_remote/type_mismatch_pass.rs
//@check-pass mod structs { use bevy_reflect::{reflect_remote, Reflect}; mod external_crate { pub struct TheirFoo { pub value: u32, } pub struct TheirBar { pub value: i32, } } #[reflect_remote(external_crate::TheirFoo)] struct MyFoo { pub value: u32, } #[reflect_remote(external_crate::TheirBar)] struct MyBar { pub value: i32, } #[derive(Reflect)] struct MyStruct { #[reflect(remote = MyFoo)] foo: external_crate::TheirFoo, } } mod tuple_structs { use bevy_reflect::{reflect_remote, Reflect}; mod external_crate { pub struct TheirFoo(pub u32); pub struct TheirBar(pub i32); } #[reflect_remote(external_crate::TheirFoo)] struct MyFoo(pub u32); #[reflect_remote(external_crate::TheirBar)] struct MyBar(pub i32); #[derive(Reflect)] struct MyStruct(#[reflect(remote = MyFoo)] external_crate::TheirFoo); } mod enums { use bevy_reflect::{reflect_remote, Reflect}; mod external_crate { pub enum TheirFoo { Value(u32), } pub enum TheirBar { Value(i32), } } #[reflect_remote(external_crate::TheirFoo)] enum MyFoo { Value(u32), } #[reflect_remote(external_crate::TheirBar)] enum MyBar { Value(i32), } #[derive(Reflect)] enum MyStruct { Value(#[reflect(remote = MyFoo)] external_crate::TheirFoo), } } fn main() {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_remote/nested_pass.rs
crates/bevy_reflect/compile_fail/tests/reflect_remote/nested_pass.rs
//@check-pass use bevy_reflect::{FromReflect, GetTypeRegistration, reflect_remote, Reflect, Typed}; mod external_crate { pub struct TheirOuter<T> { pub inner: TheirInner<T>, } pub struct TheirInner<T>(pub T); } #[reflect_remote(external_crate::TheirOuter<T>)] struct MyOuter<T: FromReflect + Typed + GetTypeRegistration> { #[reflect(remote = MyInner<T>)] pub inner: external_crate::TheirInner<T>, } #[reflect_remote(external_crate::TheirInner<T>)] struct MyInner<T: Reflect>(pub T); fn main() {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_remote/macro_order_pass.rs
crates/bevy_reflect/compile_fail/tests/reflect_remote/macro_order_pass.rs
//@check-pass use bevy_reflect::{reflect_remote, std_traits::ReflectDefault}; mod external_crate { #[derive(Debug, Default)] pub struct TheirType { pub value: String, } } #[reflect_remote(external_crate::TheirType)] #[derive(Debug, Default)] #[reflect(Debug, Default)] struct MyType { pub value: String, } fn main() {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_remote/invalid_definition_fail.rs
crates/bevy_reflect/compile_fail/tests/reflect_remote/invalid_definition_fail.rs
mod structs { use bevy_reflect::reflect_remote; mod external_crate { pub struct TheirStruct { pub value: u32, } } #[reflect_remote(external_crate::TheirStruct)] //~^ ERROR: `?` operator has incompatible types //~| ERROR: mismatched types struct MyStruct { // Reason: Should be `u32` pub value: bool, //~^ ERROR: mismatched types } } mod tuple_structs { use bevy_reflect::reflect_remote; mod external_crate { pub struct TheirStruct(pub u32); } #[reflect_remote(external_crate::TheirStruct)] //~^ ERROR: `?` operator has incompatible types //~| ERROR: mismatched types struct MyStruct( // Reason: Should be `u32` pub bool, //~^ ERROR: mismatched types ); } mod enums { use bevy_reflect::reflect_remote; mod external_crate { pub enum TheirStruct { Unit, Tuple(u32), Struct { value: usize }, } } #[reflect_remote(external_crate::TheirStruct)] //~^ ERROR: variant `enums::external_crate::TheirStruct::Unit` does not have a field named `0` //~| ERROR: variant `enums::external_crate::TheirStruct::Unit` has no field named `0` //~| ERROR: `?` operator has incompatible types //~| ERROR: `?` operator has incompatible types //~| ERROR: mismatched types enum MyStruct { // Reason: Should be unit variant Unit(i32), // Reason: Should be `u32` Tuple(bool), //~^ ERROR: mismatched types // Reason: Should be `usize` Struct { value: String }, //~^ ERROR: mismatched types //~| ERROR: mismatched types } } fn main() {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_derive/generics_structs_pass.rs
crates/bevy_reflect/compile_fail/tests/reflect_derive/generics_structs_pass.rs
//@check-pass use bevy_reflect::{GetField, Reflect}; #[derive(Reflect)] #[reflect(from_reflect = false)] struct Foo<T, U, S> { a: T, #[reflect(ignore)] _b: U, // check that duplicate types don't cause any compile errors _c: T, // check that when a type is both an active and inactive type, both trait bounds are used _d: U, #[reflect(ignore)] _e: S, } // check that we use the proper bounds when auto-deriving `FromReflect` #[derive(Reflect)] struct Bar<T, U: Default, S: Default> { a: T, #[reflect(ignore)] _b: U, _c: T, _d: U, #[reflect(ignore)] _e: S, } fn main() { let foo = Foo::<u32, usize, f32> { a: 1, _b: 2, _c: 3, _d: 4, _e: 5.0, }; let _ = *foo.get_field::<u32>("a").unwrap(); let bar = Bar::<u32, usize, f32> { a: 1, _b: 2, _c: 3, _d: 4, _e: 5.0, }; let _ = *bar.get_field::<u32>("a").unwrap(); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_derive/generics_fail.rs
crates/bevy_reflect/compile_fail/tests/reflect_derive/generics_fail.rs
use bevy_reflect::{GetField, Reflect, Struct, TypePath}; #[derive(Reflect)] #[reflect(from_reflect = false)] struct Foo<T> { a: T, } // Type that doesn't implement Reflect #[derive(TypePath)] struct NoReflect(f32); fn main() { let mut foo: Box<dyn Struct> = Box::new(Foo::<NoReflect> { a: NoReflect(42.0) }); //~^ ERROR: `NoReflect` does not implement `GetTypeRegistration` so cannot provide type registration information //~| ERROR: `NoReflect` does not implement `Typed` so cannot provide static type information // foo doesn't implement Reflect because NoReflect doesn't implement Reflect foo.get_field::<NoReflect>("a").unwrap(); //~^ ERROR: `NoReflect` does not implement `Reflect` so cannot be fully reflected }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_derive/bounds_pass.rs
crates/bevy_reflect/compile_fail/tests/reflect_derive/bounds_pass.rs
//@check-pass use bevy_reflect::prelude::*; #[derive(Default)] struct NonReflect; struct NonReflectNonDefault; mod structs { use super::*; #[derive(Reflect)] struct ReflectGeneric<T> { foo: T, #[reflect(ignore)] _ignored: NonReflect, } #[derive(Reflect)] struct FromReflectGeneric<T> { foo: T, #[reflect(ignore)] _ignored: NonReflect, } #[derive(Reflect)] #[reflect(Default)] struct DefaultGeneric<T> { foo: Option<T>, #[reflect(ignore)] _ignored: NonReflectNonDefault, } impl<T> Default for DefaultGeneric<T> { fn default() -> Self { Self { foo: None, _ignored: NonReflectNonDefault, } } } #[derive(Reflect)] struct ReflectBoundGeneric<T: Clone> { foo: T, #[reflect(ignore)] _ignored: NonReflect, } #[derive(Reflect)] struct FromReflectBoundGeneric<T: Clone> { foo: T, #[reflect(ignore)] _ignored: NonReflect, } #[derive(Reflect)] #[reflect(Default)] struct DefaultBoundGeneric<T: Clone> { foo: Option<T>, #[reflect(ignore)] _ignored: NonReflectNonDefault, } impl<T: Clone> Default for DefaultBoundGeneric<T> { fn default() -> Self { Self { foo: None, _ignored: NonReflectNonDefault, } } } #[derive(Reflect)] struct ReflectGenericWithWhere<T> where T: Clone, { foo: T, #[reflect(ignore)] _ignored: NonReflect, } #[derive(Reflect)] struct FromReflectGenericWithWhere<T> where T: Clone, { foo: T, #[reflect(ignore)] _ignored: NonReflect, } #[derive(Reflect)] #[reflect(Default)] struct DefaultGenericWithWhere<T> where T: Clone, { foo: Option<T>, #[reflect(ignore)] _ignored: NonReflectNonDefault, } impl<T> Default for DefaultGenericWithWhere<T> where T: Clone, { fn default() -> Self { Self { foo: None, _ignored: NonReflectNonDefault, } } } #[derive(Reflect)] #[rustfmt::skip] struct ReflectGenericWithWhereNoTrailingComma<T> where T: Clone { foo: T, #[reflect(ignore)] _ignored: NonReflect, } #[derive(Reflect)] #[rustfmt::skip] struct FromReflectGenericWithWhereNoTrailingComma<T> where T: Clone { foo: T, #[reflect(ignore)] _ignored: NonReflect, } #[derive(Reflect)] #[reflect(Default)] #[rustfmt::skip] struct DefaultGenericWithWhereNoTrailingComma<T> where T: Clone { foo: Option<T>, #[reflect(ignore)] _ignored: NonReflectNonDefault, } impl<T> Default for DefaultGenericWithWhereNoTrailingComma<T> where T: Clone, { fn default() -> Self { Self { foo: None, _ignored: NonReflectNonDefault, } } } } mod tuple_structs { use super::*; #[derive(Reflect)] struct ReflectGeneric<T>(T, #[reflect(ignore)] NonReflect); #[derive(Reflect)] struct FromReflectGeneric<T>(T, #[reflect(ignore)] NonReflect); #[derive(Reflect)] #[reflect(Default)] struct DefaultGeneric<T>(Option<T>, #[reflect(ignore)] NonReflectNonDefault); impl<T> Default for DefaultGeneric<T> { fn default() -> Self { Self(None, NonReflectNonDefault) } } #[derive(Reflect)] struct ReflectBoundGeneric<T: Clone>(T, #[reflect(ignore)] NonReflect); #[derive(Reflect)] struct FromReflectBoundGeneric<T: Clone>(T, #[reflect(ignore)] NonReflect); #[derive(Reflect)] #[reflect(Default)] struct DefaultBoundGeneric<T: Clone>(Option<T>, #[reflect(ignore)] NonReflectNonDefault); impl<T: Clone> Default for DefaultBoundGeneric<T> { fn default() -> Self { Self(None, NonReflectNonDefault) } } #[derive(Reflect)] struct ReflectGenericWithWhere<T>(T, #[reflect(ignore)] NonReflect) where T: Clone; #[derive(Reflect)] struct FromReflectGenericWithWhere<T>(T, #[reflect(ignore)] NonReflect) where T: Clone; #[derive(Reflect)] #[reflect(Default)] struct DefaultGenericWithWhere<T>(Option<T>, #[reflect(ignore)] NonReflectNonDefault) where T: Clone; impl<T> Default for DefaultGenericWithWhere<T> where T: Clone, { fn default() -> Self { Self(None, NonReflectNonDefault) } } } mod enums { use super::*; #[derive(Reflect)] enum ReflectGeneric<T> { Foo(T, #[reflect(ignore)] NonReflect), } #[derive(Reflect)] enum FromReflectGeneric<T> { Foo(T, #[reflect(ignore)] NonReflect), } #[derive(Reflect)] enum ReflectBoundGeneric<T: Clone> { Foo(T, #[reflect(ignore)] NonReflect), } #[derive(Reflect)] enum FromReflectBoundGeneric<T: Clone> { Foo(T, #[reflect(ignore)] NonReflect), } #[derive(Reflect)] enum ReflectGenericWithWhere<T> where T: Clone, { Foo(T, #[reflect(ignore)] NonReflect), } #[derive(Reflect)] enum FromReflectGenericWithWhere<T> where T: Clone, { Foo(T, #[reflect(ignore)] NonReflect), } #[derive(Reflect)] #[rustfmt::skip] enum ReflectGenericWithWhereNoTrailingComma<T> where T: Clone { Foo(T, #[reflect(ignore)] NonReflect), } #[derive(Reflect)] #[rustfmt::skip] enum FromReflectGenericWithWhereNoTrailingComma<T> where T: Clone { Foo(T, #[reflect(ignore)] NonReflect), } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_derive/from_reflect_pass.rs
crates/bevy_reflect/compile_fail/tests/reflect_derive/from_reflect_pass.rs
//@check-pass use bevy_reflect::{FromReflect, Reflect}; #[derive(Reflect)] #[reflect(from_reflect = false)] #[reflect(from_reflect = false)] struct Foo { value: String, } #[derive(Reflect)] #[reflect(from_reflect = true)] #[reflect(from_reflect = true)] struct Bar { value: String, } #[derive(Reflect, FromReflect)] #[reflect(from_reflect = false)] struct Baz { value: String, }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_derive/custom_where_fail.rs
crates/bevy_reflect/compile_fail/tests/reflect_derive/custom_where_fail.rs
use bevy_reflect::{FromType, Reflect}; use core::marker::PhantomData; #[derive(Clone)] struct ReflectMyTrait; impl<T> FromType<T> for ReflectMyTrait { fn from_type() -> Self { Self } } // Reason: populated `where` clause must be last with #[reflect(MyTrait)] #[derive(Reflect)] #[reflect(where T: core::fmt::Debug, MyTrait)] //~^ ERROR: /expected.+:/ // TODO: Investigate a way to improve the error message. pub struct Foo<T> { value: String, #[reflect(ignore)] _marker: PhantomData<T>, }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_derive/lifetimes_pass.rs
crates/bevy_reflect/compile_fail/tests/reflect_derive/lifetimes_pass.rs
//@check-pass use bevy_reflect::Reflect; // Reason: Reflection relies on `Any` which requires `'static` #[derive(Reflect)] struct Foo<'a: 'static> { #[reflect(ignore)] value: &'a str, }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_derive/from_reflect_fail.rs
crates/bevy_reflect/compile_fail/tests/reflect_derive/from_reflect_fail.rs
use bevy_reflect::{FromReflect, Reflect}; // Reason: Cannot have conflicting `from_reflect` attributes #[derive(Reflect)] #[reflect(from_reflect = false)] #[reflect(from_reflect = true)] //~^ ERROR: already set to false struct Foo { value: String, } // Reason: Cannot have conflicting `from_reflect` attributes #[derive(Reflect)] #[reflect(from_reflect = true)] #[reflect(from_reflect = false)] //~^ ERROR: already set to true struct Bar { value: String, } // Reason: Conflicting `FromReflect` implementations #[derive(Reflect, FromReflect)] //~^ ERROR: conflicting implementation struct Baz { value: String, }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_derive/nested_pass.rs
crates/bevy_reflect/compile_fail/tests/reflect_derive/nested_pass.rs
//@check-pass use bevy_reflect::Reflect; mod nested_generics { use super::*; #[derive(Reflect)] struct Foo<T>(T); #[derive(Reflect)] struct Bar<T>(Foo<T>); #[derive(Reflect)] struct Baz<T>(Bar<Foo<T>>); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/compile_fail/tests/reflect_derive/custom_where_pass.rs
crates/bevy_reflect/compile_fail/tests/reflect_derive/custom_where_pass.rs
//@check-pass use bevy_reflect::{FromType, Reflect}; use core::marker::PhantomData; #[derive(Clone)] struct ReflectMyTrait; impl<T> FromType<T> for ReflectMyTrait { fn from_type() -> Self { Self } } #[derive(Reflect)] #[reflect(MyTrait, where T: core::fmt::Debug)] pub struct Foo<T> { value: String, #[reflect(ignore)] _marker: PhantomData<T>, } #[derive(Reflect)] #[reflect(where, MyTrait)] pub struct Bar<T> { value: String, #[reflect(ignore)] _marker: PhantomData<T>, } #[derive(Reflect)] #[reflect(MyTrait)] #[reflect(where T: core::fmt::Debug)] pub struct Baz<T> { value: String, #[reflect(ignore)] _marker: PhantomData<T>, }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/array.rs
crates/bevy_reflect/src/array.rs
use crate::generics::impl_generic_info_methods; use crate::{ type_info::impl_type_methods, utility::reflect_hasher, ApplyError, Generics, MaybeTyped, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type, TypeInfo, TypePath, }; use alloc::{boxed::Box, vec::Vec}; use bevy_reflect_derive::impl_type_path; use core::{ any::Any, fmt::{Debug, Formatter}, hash::{Hash, Hasher}, }; /// A trait used to power [array-like] operations via [reflection]. /// /// This corresponds to true Rust arrays like `[T; N]`, /// but also to any fixed-size linear sequence types. /// It is expected that implementors of this trait uphold this contract /// and maintain a fixed size as returned by the [`Array::len`] method. /// /// Due to the [type-erasing] nature of the reflection API as a whole, /// this trait does not make any guarantees that the implementor's elements /// are homogeneous (i.e. all the same type). /// /// This trait has a blanket implementation over Rust arrays of up to 32 items. /// This implementation can technically contain more than 32, /// but the blanket [`GetTypeRegistration`] is only implemented up to the 32 /// item limit due to a [limitation] on [`Deserialize`]. /// /// # Example /// /// ``` /// use bevy_reflect::{PartialReflect, Array}; /// /// let foo: &dyn Array = &[123_u32, 456_u32, 789_u32]; /// assert_eq!(foo.len(), 3); /// /// let field: &dyn PartialReflect = foo.get(0).unwrap(); /// assert_eq!(field.try_downcast_ref::<u32>(), Some(&123)); /// ``` /// /// [array-like]: https://doc.rust-lang.org/book/ch03-02-data-types.html#the-array-type /// [reflection]: crate /// [`List`]: crate::List /// [type-erasing]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html /// [`GetTypeRegistration`]: crate::GetTypeRegistration /// [limitation]: https://github.com/serde-rs/serde/issues/1937 /// [`Deserialize`]: ::serde::Deserialize pub trait Array: PartialReflect { /// Returns a reference to the element at `index`, or `None` if out of bounds. fn get(&self, index: usize) -> Option<&dyn PartialReflect>; /// Returns a mutable reference to the element at `index`, or `None` if out of bounds. fn get_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>; /// Returns the number of elements in the array. fn len(&self) -> usize; /// Returns `true` if the collection contains no elements. fn is_empty(&self) -> bool { self.len() == 0 } /// Returns an iterator over the array. fn iter(&self) -> ArrayIter<'_>; /// Drain the elements of this array to get a vector of owned values. fn drain(self: Box<Self>) -> Vec<Box<dyn PartialReflect>>; /// Creates a new [`DynamicArray`] from this array. fn to_dynamic_array(&self) -> DynamicArray { DynamicArray { represented_type: self.get_represented_type_info(), values: self.iter().map(PartialReflect::to_dynamic).collect(), } } /// Will return `None` if [`TypeInfo`] is not available. fn get_represented_array_info(&self) -> Option<&'static ArrayInfo> { self.get_represented_type_info()?.as_array().ok() } } /// A container for compile-time array info. #[derive(Clone, Debug)] pub struct ArrayInfo { ty: Type, generics: Generics, item_info: fn() -> Option<&'static TypeInfo>, item_ty: Type, capacity: usize, #[cfg(feature = "reflect_documentation")] docs: Option<&'static str>, } impl ArrayInfo { /// Create a new [`ArrayInfo`]. /// /// # Arguments /// /// * `capacity`: The maximum capacity of the underlying array. pub fn new<TArray: Array + TypePath, TItem: Reflect + MaybeTyped + TypePath>( capacity: usize, ) -> Self { Self { ty: Type::of::<TArray>(), generics: Generics::new(), item_info: TItem::maybe_type_info, item_ty: Type::of::<TItem>(), capacity, #[cfg(feature = "reflect_documentation")] docs: None, } } /// Sets the docstring for this array. #[cfg(feature = "reflect_documentation")] pub fn with_docs(self, docs: Option<&'static str>) -> Self { Self { docs, ..self } } /// The compile-time capacity of the array. pub fn capacity(&self) -> usize { self.capacity } impl_type_methods!(ty); /// The [`TypeInfo`] of the array item. /// /// Returns `None` if the array item does not contain static type information, /// such as for dynamic types. pub fn item_info(&self) -> Option<&'static TypeInfo> { (self.item_info)() } /// The [type] of the array item. /// /// [type]: Type pub fn item_ty(&self) -> Type { self.item_ty } /// The docstring of this array, if any. #[cfg(feature = "reflect_documentation")] pub fn docs(&self) -> Option<&'static str> { self.docs } impl_generic_info_methods!(generics); } /// A fixed-size list of reflected values. /// /// This differs from [`DynamicList`] in that the size of the [`DynamicArray`] /// is constant, whereas a [`DynamicList`] can have items added and removed. /// /// This isn't to say that a [`DynamicArray`] is immutable— its items /// can be mutated— just that the _number_ of items cannot change. /// /// [`DynamicList`]: crate::DynamicList #[derive(Debug)] pub struct DynamicArray { pub(crate) represented_type: Option<&'static TypeInfo>, pub(crate) values: Box<[Box<dyn PartialReflect>]>, } impl DynamicArray { /// Creates a new [`DynamicArray`]. #[inline] pub fn new(values: Box<[Box<dyn PartialReflect>]>) -> Self { Self { represented_type: None, values, } } /// Sets the [type] to be represented by this `DynamicArray`. /// /// # Panics /// /// Panics if the given [type] is not a [`TypeInfo::Array`]. /// /// [type]: TypeInfo pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) { if let Some(represented_type) = represented_type { assert!( matches!(represented_type, TypeInfo::Array(_)), "expected TypeInfo::Array but received: {represented_type:?}" ); } self.represented_type = represented_type; } } impl PartialReflect for DynamicArray { #[inline] fn get_represented_type_info(&self) -> Option<&'static TypeInfo> { self.represented_type } #[inline] fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> { self } #[inline] fn as_partial_reflect(&self) -> &dyn PartialReflect { self } #[inline] fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect { self } fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> { Err(self) } fn try_as_reflect(&self) -> Option<&dyn Reflect> { None } fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { None } fn apply(&mut self, value: &dyn PartialReflect) { array_apply(self, value); } fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { array_try_apply(self, value) } #[inline] fn reflect_kind(&self) -> ReflectKind { ReflectKind::Array } #[inline] fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Array(self) } #[inline] fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Array(self) } #[inline] fn reflect_owned(self: Box<Self>) -> ReflectOwned { ReflectOwned::Array(self) } #[inline] fn reflect_hash(&self) -> Option<u64> { array_hash(self) } fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> { array_partial_eq(self, value) } fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicArray(")?; array_debug(self, f)?; write!(f, ")") } #[inline] fn is_dynamic(&self) -> bool { true } } impl Array for DynamicArray { #[inline] fn get(&self, index: usize) -> Option<&dyn PartialReflect> { self.values.get(index).map(|value| &**value) } #[inline] fn get_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> { self.values.get_mut(index).map(|value| &mut **value) } #[inline] fn len(&self) -> usize { self.values.len() } #[inline] fn iter(&self) -> ArrayIter<'_> { ArrayIter::new(self) } #[inline] fn drain(self: Box<Self>) -> Vec<Box<dyn PartialReflect>> { self.values.into_vec() } } impl FromIterator<Box<dyn PartialReflect>> for DynamicArray { fn from_iter<I: IntoIterator<Item = Box<dyn PartialReflect>>>(values: I) -> Self { Self { represented_type: None, values: values.into_iter().collect::<Vec<_>>().into_boxed_slice(), } } } impl<T: PartialReflect> FromIterator<T> for DynamicArray { fn from_iter<I: IntoIterator<Item = T>>(values: I) -> Self { values .into_iter() .map(|value| Box::new(value).into_partial_reflect()) .collect() } } impl IntoIterator for DynamicArray { type Item = Box<dyn PartialReflect>; type IntoIter = alloc::vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.values.into_vec().into_iter() } } impl<'a> IntoIterator for &'a DynamicArray { type Item = &'a dyn PartialReflect; type IntoIter = ArrayIter<'a>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl_type_path!((in bevy_reflect) DynamicArray); /// An iterator over an [`Array`]. pub struct ArrayIter<'a> { array: &'a dyn Array, index: usize, } impl ArrayIter<'_> { /// Creates a new [`ArrayIter`]. #[inline] pub const fn new(array: &dyn Array) -> ArrayIter<'_> { ArrayIter { array, index: 0 } } } impl<'a> Iterator for ArrayIter<'a> { type Item = &'a dyn PartialReflect; #[inline] fn next(&mut self) -> Option<Self::Item> { let value = self.array.get(self.index); self.index += value.is_some() as usize; value } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let size = self.array.len(); (size, Some(size)) } } impl<'a> ExactSizeIterator for ArrayIter<'a> {} /// Returns the `u64` hash of the given [array](Array). #[inline] pub fn array_hash<A: Array + ?Sized>(array: &A) -> Option<u64> { let mut hasher = reflect_hasher(); Any::type_id(array).hash(&mut hasher); array.len().hash(&mut hasher); for value in array.iter() { hasher.write_u64(value.reflect_hash()?); } Some(hasher.finish()) } /// Applies the reflected [array](Array) data to the given [array](Array). /// /// # Panics /// /// * Panics if the two arrays have differing lengths. /// * Panics if the reflected value is not a [valid array](ReflectRef::Array). #[inline] pub fn array_apply<A: Array + ?Sized>(array: &mut A, reflect: &dyn PartialReflect) { if let ReflectRef::Array(reflect_array) = reflect.reflect_ref() { if array.len() != reflect_array.len() { panic!("Attempted to apply different sized `Array` types."); } for (i, value) in reflect_array.iter().enumerate() { let v = array.get_mut(i).unwrap(); v.apply(value); } } else { panic!("Attempted to apply a non-`Array` type to an `Array` type."); } } /// Tries to apply the reflected [array](Array) data to the given [array](Array) and /// returns a Result. /// /// # Errors /// /// * Returns an [`ApplyError::DifferentSize`] if the two arrays have differing lengths. /// * Returns an [`ApplyError::MismatchedKinds`] if the reflected value is not a /// [valid array](ReflectRef::Array). /// * Returns any error that is generated while applying elements to each other. #[inline] pub fn array_try_apply<A: Array>( array: &mut A, reflect: &dyn PartialReflect, ) -> Result<(), ApplyError> { let reflect_array = reflect.reflect_ref().as_array()?; if array.len() != reflect_array.len() { return Err(ApplyError::DifferentSize { from_size: reflect_array.len(), to_size: array.len(), }); } for (i, value) in reflect_array.iter().enumerate() { let v = array.get_mut(i).unwrap(); v.try_apply(value)?; } Ok(()) } /// Compares two [arrays](Array) (one concrete and one reflected) to see if they /// are equal. /// /// Returns [`None`] if the comparison couldn't even be performed. #[inline] pub fn array_partial_eq<A: Array + ?Sized>( array: &A, reflect: &dyn PartialReflect, ) -> Option<bool> { match reflect.reflect_ref() { ReflectRef::Array(reflect_array) if reflect_array.len() == array.len() => { for (a, b) in array.iter().zip(reflect_array.iter()) { let eq_result = a.reflect_partial_eq(b); if let failed @ (Some(false) | None) = eq_result { return failed; } } } _ => return Some(false), } Some(true) } /// The default debug formatter for [`Array`] types. /// /// # Example /// ``` /// use bevy_reflect::Reflect; /// /// let my_array: &dyn Reflect = &[1, 2, 3]; /// println!("{:#?}", my_array); /// /// // Output: /// /// // [ /// // 1, /// // 2, /// // 3, /// // ] /// ``` #[inline] pub fn array_debug(dyn_array: &dyn Array, f: &mut Formatter<'_>) -> core::fmt::Result { let mut debug = f.debug_list(); for item in dyn_array.iter() { debug.entry(&item as &dyn Debug); } debug.finish() } #[cfg(test)] mod tests { use crate::Reflect; use alloc::boxed::Box; #[test] fn next_index_increment() { const SIZE: usize = if cfg!(debug_assertions) { 4 } else { // If compiled in release mode, verify we dont overflow usize::MAX }; let b = Box::new([(); SIZE]).into_reflect(); let array = b.reflect_ref().as_array().unwrap(); let mut iter = array.iter(); iter.index = SIZE - 1; assert!(iter.next().is_some()); // When None we should no longer increase index assert!(iter.next().is_none()); assert!(iter.index == SIZE); assert!(iter.next().is_none()); assert!(iter.index == SIZE); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/std_traits.rs
crates/bevy_reflect/src/std_traits.rs
//! Module containing the [`ReflectDefault`] type. use crate::{FromType, Reflect}; use alloc::boxed::Box; /// A struct used to provide the default value of a type. /// /// A [`ReflectDefault`] for type `T` can be obtained via [`FromType::from_type`]. #[derive(Clone)] pub struct ReflectDefault { default: fn() -> Box<dyn Reflect>, } impl ReflectDefault { /// Returns the default value for a type. pub fn default(&self) -> Box<dyn Reflect> { (self.default)() } } impl<T: Reflect + Default> FromType<T> for ReflectDefault { fn from_type() -> Self { ReflectDefault { default: || Box::<T>::default(), } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/type_path.rs
crates/bevy_reflect/src/type_path.rs
use core::fmt; /// A static accessor to type paths and names. /// /// The engine uses this trait over [`core::any::type_name`] for stability and flexibility. /// /// This trait is automatically implemented by the `#[derive(Reflect)]` macro /// and allows type path information to be processed without an instance of that type. /// /// Implementors may have difficulty in generating references with static /// lifetimes. Luckily, this crate comes with some [utility] structs, to make generating these /// statics much simpler. /// /// # Stability /// /// Certain parts of the engine, e.g. [(de)serialization], rely on type paths as identifiers /// for matching dynamic values to concrete types. /// /// Using [`core::any::type_name`], a scene containing `my_crate::foo::MyComponent` would break, /// failing to deserialize if the component was moved from the `foo` module to the `bar` module, /// becoming `my_crate::bar::MyComponent`. /// This trait, through attributes when deriving itself or [`Reflect`], can ensure breaking changes are avoidable. /// /// The only external factor we rely on for stability when deriving is the [`module_path!`] macro, /// only if the derive does not provide a `#[type_path = "..."]` attribute. /// /// # Anonymity /// /// Some methods on this trait return `Option<&'static str>` over `&'static str` /// because not all types define all parts of a type path, for example the array type `[T; N]`. /// /// Such types are 'anonymous' in that they have only a defined [`type_path`] and [`short_type_path`] /// and the methods [`crate_name`], [`module_path`] and [`type_ident`] all return `None`. /// /// Primitives are treated like anonymous types, except they also have a defined [`type_ident`]. /// /// # Example /// /// ``` /// use bevy_reflect::TypePath; /// /// // This type path will not change with compiler versions or recompiles, /// // although it will not be the same if the definition is moved. /// #[derive(TypePath)] /// struct NonStableTypePath; /// /// // This type path will never change, even if the definition is moved. /// #[derive(TypePath)] /// #[type_path = "my_crate::foo"] /// struct StableTypePath; /// /// // Type paths can have any number of path segments. /// #[derive(TypePath)] /// #[type_path = "my_crate::foo::bar::baz"] /// struct DeeplyNestedStableTypePath; /// /// // Including just a crate name! /// #[derive(TypePath)] /// #[type_path = "my_crate"] /// struct ShallowStableTypePath; /// /// // We can also rename the identifier/name of types. /// #[derive(TypePath)] /// #[type_path = "my_crate::foo"] /// #[type_name = "RenamedStableTypePath"] /// struct NamedStableTypePath; /// /// // Generics are also supported. /// #[derive(TypePath)] /// #[type_path = "my_crate::foo"] /// struct StableGenericTypePath<T, const N: usize>([T; N]); /// ``` /// /// [utility]: crate::utility /// [(de)serialization]: crate::serde::ReflectDeserializer /// [`Reflect`]: crate::Reflect /// [`type_path`]: TypePath::type_path /// [`short_type_path`]: TypePath::short_type_path /// [`crate_name`]: TypePath::crate_name /// [`module_path`]: TypePath::module_path /// [`type_ident`]: TypePath::type_ident #[diagnostic::on_unimplemented( message = "`{Self}` does not implement `TypePath` so cannot provide static type path information", note = "consider annotating `{Self}` with `#[derive(Reflect)]` or `#[derive(TypePath)]`" )] pub trait TypePath: 'static { /// Returns the fully qualified path of the underlying type. /// /// Generic parameter types are also fully expanded. /// /// For `Option<Vec<usize>>`, this is `"std::option::Option<std::vec::Vec<usize>>"`. fn type_path() -> &'static str; /// Returns a short, pretty-print enabled path to the type. /// /// Generic parameter types are also shortened. /// /// For `Option<Vec<usize>>`, this is `"Option<Vec<usize>>"`. fn short_type_path() -> &'static str; /// Returns the name of the type, or [`None`] if it is [anonymous]. /// /// Primitive types will return [`Some`]. /// /// For `Option<Vec<usize>>`, this is `"Option"`. /// /// [anonymous]: TypePath#anonymity fn type_ident() -> Option<&'static str> { None } /// Returns the name of the crate the type is in, or [`None`] if it is [anonymous]. /// /// For `Option<Vec<usize>>`, this is `"core"`. /// /// [anonymous]: TypePath#anonymity fn crate_name() -> Option<&'static str> { None } /// Returns the path to the module the type is in, or [`None`] if it is [anonymous]. /// /// For `Option<Vec<usize>>`, this is `"std::option"`. /// /// [anonymous]: TypePath#anonymity fn module_path() -> Option<&'static str> { None } } /// Dynamic dispatch for [`TypePath`]. /// /// Since this is a supertrait of [`Reflect`] its methods can be called on a `dyn Reflect`. /// /// [`Reflect`]: crate::Reflect #[diagnostic::on_unimplemented( message = "`{Self}` does not implement `TypePath` so cannot provide dynamic type path information", note = "consider annotating `{Self}` with `#[derive(Reflect)]` or `#[derive(TypePath)]`" )] pub trait DynamicTypePath { /// See [`TypePath::type_path`]. fn reflect_type_path(&self) -> &str; /// See [`TypePath::short_type_path`]. fn reflect_short_type_path(&self) -> &str; /// See [`TypePath::type_ident`]. fn reflect_type_ident(&self) -> Option<&str>; /// See [`TypePath::crate_name`]. fn reflect_crate_name(&self) -> Option<&str>; /// See [`TypePath::module_path`]. fn reflect_module_path(&self) -> Option<&str>; } impl<T: TypePath> DynamicTypePath for T { #[inline] fn reflect_type_path(&self) -> &str { Self::type_path() } #[inline] fn reflect_short_type_path(&self) -> &str { Self::short_type_path() } #[inline] fn reflect_type_ident(&self) -> Option<&str> { Self::type_ident() } #[inline] fn reflect_crate_name(&self) -> Option<&str> { Self::crate_name() } #[inline] fn reflect_module_path(&self) -> Option<&str> { Self::module_path() } } /// Provides dynamic access to all methods on [`TypePath`]. #[derive(Clone, Copy)] pub struct TypePathTable { // Cache the type path as it is likely the only one that will be used. type_path: &'static str, short_type_path: fn() -> &'static str, type_ident: fn() -> Option<&'static str>, crate_name: fn() -> Option<&'static str>, module_path: fn() -> Option<&'static str>, } impl fmt::Debug for TypePathTable { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TypePathVtable") .field("type_path", &self.type_path) .field("short_type_path", &(self.short_type_path)()) .field("type_ident", &(self.type_ident)()) .field("crate_name", &(self.crate_name)()) .field("module_path", &(self.module_path)()) .finish() } } impl TypePathTable { /// Creates a new table from a type. pub fn of<T: TypePath + ?Sized>() -> Self { Self { type_path: T::type_path(), short_type_path: T::short_type_path, type_ident: T::type_ident, crate_name: T::crate_name, module_path: T::module_path, } } /// See [`TypePath::type_path`]. pub fn path(&self) -> &'static str { self.type_path } /// See [`TypePath::short_type_path`]. pub fn short_path(&self) -> &'static str { (self.short_type_path)() } /// See [`TypePath::type_ident`]. pub fn ident(&self) -> Option<&'static str> { (self.type_ident)() } /// See [`TypePath::crate_name`]. pub fn crate_name(&self) -> Option<&'static str> { (self.crate_name)() } /// See [`TypePath::module_path`]. pub fn module_path(&self) -> Option<&'static str> { (self.module_path)() } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/lib.rs
crates/bevy_reflect/src/lib.rs
#![cfg_attr( any(docsrs, docsrs_dep), expect( internal_features, reason = "rustdoc_internals is needed for fake_variadic" ) )] #![cfg_attr(any(docsrs, docsrs_dep), feature(doc_cfg, rustdoc_internals))] #![doc( html_logo_url = "https://bevy.org/assets/icon.png", html_favicon_url = "https://bevy.org/assets/icon.png" )] //! Reflection in Rust. //! //! [Reflection] is a powerful tool provided within many programming languages //! that allows for meta-programming: using information _about_ the program to //! _affect_ the program. //! In other words, reflection allows us to inspect the program itself, its //! syntax, and its type information at runtime. //! //! This crate adds this missing reflection functionality to Rust. //! Though it was made with the [Bevy] game engine in mind, //! it's a general-purpose solution that can be used in any Rust project. //! //! At a very high level, this crate allows you to: //! * Dynamically interact with Rust values //! * Access type metadata at runtime //! * Serialize and deserialize (i.e. save and load) data //! //! It's important to note that because of missing features in Rust, //! there are some [limitations] with this crate. //! //! # The `Reflect` and `PartialReflect` traits //! //! At the root of [`bevy_reflect`] is the [`PartialReflect`] trait. //! //! Its purpose is to allow dynamic [introspection] of values, //! following Rust's type system through a system of [subtraits]. //! //! Its primary purpose is to allow all implementors to be passed around //! as a `dyn PartialReflect` trait object in one of the following forms: //! * `&dyn PartialReflect` //! * `&mut dyn PartialReflect` //! * `Box<dyn PartialReflect>` //! //! This allows values of types implementing `PartialReflect` //! to be operated upon completely dynamically (at a small [runtime cost]). //! //! Building on `PartialReflect` is the [`Reflect`] trait. //! //! `PartialReflect` is a supertrait of `Reflect` //! so any type implementing `Reflect` implements `PartialReflect` by definition. //! `dyn Reflect` trait objects can be used similarly to `dyn PartialReflect`, //! but `Reflect` is also often used in trait bounds (like `T: Reflect`). //! //! The distinction between `PartialReflect` and `Reflect` is summarized in the following: //! * `PartialReflect` is a trait for interacting with values under `bevy_reflect`'s data model. //! This means values implementing `PartialReflect` can be dynamically constructed and introspected. //! * The `Reflect` trait, however, ensures that the interface exposed by `PartialReflect` //! on types which additionally implement `Reflect` mirrors the structure of a single Rust type. //! * This means `dyn Reflect` trait objects can be directly downcast to concrete types, //! where `dyn PartialReflect` trait object cannot. //! * `Reflect`, since it provides a stronger type-correctness guarantee, //! is the trait used to interact with [the type registry]. //! //! ## Converting between `PartialReflect` and `Reflect` //! //! Since `T: Reflect` implies `T: PartialReflect`, conversion from a `dyn Reflect` to a `dyn PartialReflect` //! trait object (upcasting) is infallible and can be performed with one of the following methods. //! Note that these are temporary while [the language feature for dyn upcasting coercion] is experimental: //! * [`PartialReflect::as_partial_reflect`] for `&dyn PartialReflect` //! * [`PartialReflect::as_partial_reflect_mut`] for `&mut dyn PartialReflect` //! * [`PartialReflect::into_partial_reflect`] for `Box<dyn PartialReflect>` //! //! For conversion in the other direction — downcasting `dyn PartialReflect` to `dyn Reflect` — //! there are fallible methods: //! * [`PartialReflect::try_as_reflect`] for `&dyn Reflect` //! * [`PartialReflect::try_as_reflect_mut`] for `&mut dyn Reflect` //! * [`PartialReflect::try_into_reflect`] for `Box<dyn Reflect>` //! //! Additionally, [`FromReflect::from_reflect`] can be used to convert a `dyn PartialReflect` to a concrete type //! which implements `Reflect`. //! //! # Implementing `Reflect` //! //! Implementing `Reflect` (and `PartialReflect`) is easily done using the provided [derive macro]: //! //! ``` //! # use bevy_reflect::Reflect; //! #[derive(Reflect)] //! struct MyStruct { //! foo: i32 //! } //! ``` //! //! This will automatically generate the implementation of `Reflect` for any struct or enum. //! //! It will also generate other very important trait implementations used for reflection: //! * [`GetTypeRegistration`] //! * [`Typed`] //! * [`Struct`], [`TupleStruct`], or [`Enum`] depending on the type //! //! ## Requirements //! //! We can implement `Reflect` on any type that satisfies _both_ of the following conditions: //! * The type implements `Any`, `Send`, and `Sync`. //! For the `Any` requirement to be satisfied, the type itself must have a [`'static` lifetime]. //! * All fields and sub-elements themselves implement `Reflect` //! (see the [derive macro documentation] for details on how to ignore certain fields when deriving). //! //! Additionally, using the derive macro on enums requires a third condition to be met: //! * All fields and sub-elements must implement [`FromReflect`]— //! another important reflection trait discussed in a later section. //! //! # The Reflection Subtraits //! //! Since [`PartialReflect`] is meant to cover any and every type, this crate also comes with a few //! more traits to accompany `PartialReflect` and provide more specific interactions. //! We refer to these traits as the _reflection subtraits_ since they all have `PartialReflect` as a supertrait. //! The current list of reflection subtraits include: //! * [`Tuple`] //! * [`Array`] //! * [`List`] //! * [`Set`] //! * [`Map`] //! * [`Struct`] //! * [`TupleStruct`] //! * [`Enum`] //! * [`Function`] (requires the `functions` feature) //! //! As mentioned previously, the last three are automatically implemented by the [derive macro]. //! //! Each of these traits come with their own methods specific to their respective category. //! For example, we can access our struct's fields by name using the [`Struct::field`] method. //! //! ``` //! # use bevy_reflect::{PartialReflect, Reflect, Struct}; //! # #[derive(Reflect)] //! # struct MyStruct { //! # foo: i32 //! # } //! let my_struct: Box<dyn Struct> = Box::new(MyStruct { //! foo: 123 //! }); //! let foo: &dyn PartialReflect = my_struct.field("foo").unwrap(); //! assert_eq!(Some(&123), foo.try_downcast_ref::<i32>()); //! ``` //! //! Since most data is passed around as `dyn PartialReflect` or `dyn Reflect` trait objects, //! the `PartialReflect` trait has methods for going to and from these subtraits. //! //! [`PartialReflect::reflect_kind`], [`PartialReflect::reflect_ref`], //! [`PartialReflect::reflect_mut`], and [`PartialReflect::reflect_owned`] all return //! an enum that respectively contains zero-sized, immutable, mutable, and owned access to the type as a subtrait object. //! //! For example, we can get out a `dyn Tuple` from our reflected tuple type using one of these methods. //! //! ``` //! # use bevy_reflect::{PartialReflect, ReflectRef}; //! let my_tuple: Box<dyn PartialReflect> = Box::new((1, 2, 3)); //! let my_tuple = my_tuple.reflect_ref().as_tuple().unwrap(); //! assert_eq!(3, my_tuple.field_len()); //! ``` //! //! And to go back to a general-purpose `dyn PartialReflect`, //! we can just use the matching [`PartialReflect::as_partial_reflect`], [`PartialReflect::as_partial_reflect_mut`], //! or [`PartialReflect::into_partial_reflect`] methods. //! //! ## Opaque Types //! //! Some types don't fall under a particular subtrait. //! //! These types hide their internal structure to reflection, //! either because it is not possible, difficult, or not useful to reflect its internals. //! Such types are known as _opaque_ types. //! //! This includes truly opaque types like `String` or `Instant`, //! but also includes all the primitive types (e.g. `bool`, `usize`, etc.) //! since they can't be broken down any further. //! //! # Dynamic Types //! //! Each subtrait comes with a corresponding _dynamic_ type. //! //! The available dynamic types are: //! * [`DynamicTuple`] //! * [`DynamicArray`] //! * [`DynamicList`] //! * [`DynamicMap`] //! * [`DynamicStruct`] //! * [`DynamicTupleStruct`] //! * [`DynamicEnum`] //! //! These dynamic types may contain any arbitrary reflected data. //! //! ``` //! # use bevy_reflect::{DynamicStruct, Struct}; //! let mut data = DynamicStruct::default(); //! data.insert("foo", 123_i32); //! assert_eq!(Some(&123), data.field("foo").unwrap().try_downcast_ref::<i32>()) //! ``` //! //! They are most commonly used as "proxies" for other types, //! where they contain the same data as— and therefore, represent— a concrete type. //! The [`PartialReflect::to_dynamic`] method will return a dynamic type for all non-opaque types, //! allowing all types to essentially be "cloned" into a dynamic type. //! And since dynamic types themselves implement [`PartialReflect`], //! we may pass them around just like most other reflected types. //! //! ``` //! # use bevy_reflect::{DynamicStruct, PartialReflect, Reflect}; //! # #[derive(Reflect)] //! # struct MyStruct { //! # foo: i32 //! # } //! let original: Box<dyn Reflect> = Box::new(MyStruct { //! foo: 123 //! }); //! //! // `dynamic` will be a `DynamicStruct` representing a `MyStruct` //! let dynamic: Box<dyn PartialReflect> = original.to_dynamic(); //! assert!(dynamic.represents::<MyStruct>()); //! ``` //! //! ## Patching //! //! These dynamic types come in handy when needing to apply multiple changes to another type. //! This is known as "patching" and is done using the [`PartialReflect::apply`] and [`PartialReflect::try_apply`] methods. //! //! ``` //! # use bevy_reflect::{DynamicEnum, PartialReflect}; //! let mut value = Some(123_i32); //! let patch = DynamicEnum::new("None", ()); //! value.apply(&patch); //! assert_eq!(None, value); //! ``` //! //! ## `FromReflect` //! //! It's important to remember that dynamic types are _not_ the concrete type they may be representing. //! A common mistake is to treat them like such when trying to cast back to the original type //! or when trying to make use of a reflected trait which expects the actual type. //! //! ```should_panic //! # use bevy_reflect::{DynamicStruct, PartialReflect, Reflect}; //! # #[derive(Reflect)] //! # struct MyStruct { //! # foo: i32 //! # } //! let original: Box<dyn Reflect> = Box::new(MyStruct { //! foo: 123 //! }); //! //! let dynamic: Box<dyn PartialReflect> = original.to_dynamic(); //! let value = dynamic.try_take::<MyStruct>().unwrap(); // PANIC! //! ``` //! //! To resolve this issue, we'll need to convert the dynamic type to the concrete one. //! This is where [`FromReflect`] comes in. //! //! `FromReflect` is a trait that allows an instance of a type to be generated from a //! dynamic representation— even partial ones. //! And since the [`FromReflect::from_reflect`] method takes the data by reference, //! this can be used to effectively clone data (to an extent). //! //! It is automatically implemented when [deriving `Reflect`] on a type unless opted out of //! using `#[reflect(from_reflect = false)]` on the item. //! //! ``` //! # use bevy_reflect::{FromReflect, PartialReflect, Reflect}; //! #[derive(Reflect)] //! struct MyStruct { //! foo: i32 //! } //! let original: Box<dyn Reflect> = Box::new(MyStruct { //! foo: 123 //! }); //! //! let dynamic: Box<dyn PartialReflect> = original.to_dynamic(); //! let value = <MyStruct as FromReflect>::from_reflect(&*dynamic).unwrap(); // OK! //! ``` //! //! When deriving, all active fields and sub-elements must also implement `FromReflect`. //! //! Fields can be given default values for when a field is missing in the passed value or even ignored. //! Ignored fields must either implement [`Default`] or have a default function specified //! using `#[reflect(default = "path::to::function")]`. //! //! See the [derive macro documentation](derive@crate::FromReflect) for details. //! //! All primitives and simple types implement `FromReflect` by relying on their [`Default`] implementation. //! //! # Path navigation //! //! The [`GetPath`] trait allows accessing arbitrary nested fields of an [`PartialReflect`] type. //! //! Using `GetPath`, it is possible to use a path string to access a specific field //! of a reflected type. //! //! ``` //! # use bevy_reflect::{Reflect, GetPath}; //! #[derive(Reflect)] //! struct MyStruct { //! value: Vec<Option<u32>> //! } //! //! let my_struct = MyStruct { //! value: vec![None, None, Some(123)], //! }; //! assert_eq!( //! my_struct.path::<u32>(".value[2].0").unwrap(), //! &123, //! ); //! ``` //! //! # Type Registration //! //! This crate also comes with a [`TypeRegistry`] that can be used to store and retrieve additional type metadata at runtime, //! such as helper types and trait implementations. //! //! The [derive macro] for [`Reflect`] also generates an implementation of the [`GetTypeRegistration`] trait, //! which is used by the registry to generate a [`TypeRegistration`] struct for that type. //! We can then register additional [type data] we want associated with that type. //! //! For example, we can register [`ReflectDefault`] on our type so that its `Default` implementation //! may be used dynamically. //! //! ``` //! # use bevy_reflect::{Reflect, TypeRegistry, prelude::ReflectDefault}; //! #[derive(Reflect, Default)] //! struct MyStruct { //! foo: i32 //! } //! let mut registry = TypeRegistry::empty(); //! registry.register::<MyStruct>(); //! registry.register_type_data::<MyStruct, ReflectDefault>(); //! //! let registration = registry.get(core::any::TypeId::of::<MyStruct>()).unwrap(); //! let reflect_default = registration.data::<ReflectDefault>().unwrap(); //! //! let new_value: Box<dyn Reflect> = reflect_default.default(); //! assert!(new_value.is::<MyStruct>()); //! ``` //! //! Because this operation is so common, the derive macro actually has a shorthand for it. //! By using the `#[reflect(Trait)]` attribute, the derive macro will automatically register a matching, //! in-scope `ReflectTrait` type within the `GetTypeRegistration` implementation. //! //! ``` //! use bevy_reflect::prelude::{Reflect, ReflectDefault}; //! //! #[derive(Reflect, Default)] //! #[reflect(Default)] //! struct MyStruct { //! foo: i32 //! } //! ``` //! //! ## Reflecting Traits //! //! Type data doesn't have to be tied to a trait, but it's often extremely useful to create trait type data. //! These allow traits to be used directly on a `dyn Reflect` (and not a `dyn PartialReflect`) //! while utilizing the underlying type's implementation. //! //! For any [object-safe] trait, we can easily generate a corresponding `ReflectTrait` type for our trait //! using the [`#[reflect_trait]`](reflect_trait) macro. //! //! ``` //! # use bevy_reflect::{Reflect, reflect_trait, TypeRegistry}; //! #[reflect_trait] // Generates a `ReflectMyTrait` type //! pub trait MyTrait {} //! impl<T: Reflect> MyTrait for T {} //! //! let mut registry = TypeRegistry::new(); //! registry.register_type_data::<i32, ReflectMyTrait>(); //! ``` //! //! The generated type data can be used to convert a valid `dyn Reflect` into a `dyn MyTrait`. //! See the [dynamic types example](https://github.com/bevyengine/bevy/blob/latest/examples/reflection/dynamic_types.rs) //! for more information and usage details. //! //! # Serialization //! //! By using reflection, we are also able to get serialization capabilities for free. //! In fact, using [`bevy_reflect`] can result in faster compile times and reduced code generation over //! directly deriving the [`serde`] traits. //! //! The way it works is by moving the serialization logic into common serializers and deserializers: //! * [`ReflectSerializer`] //! * [`TypedReflectSerializer`] //! * [`ReflectDeserializer`] //! * [`TypedReflectDeserializer`] //! //! All of these structs require a reference to the [registry] so that [type information] can be retrieved, //! as well as registered type data, such as [`ReflectSerialize`] and [`ReflectDeserialize`]. //! //! The general entry point are the "untyped" versions of these structs. //! These will automatically extract the type information and pass them into their respective "typed" version. //! //! The output of the `ReflectSerializer` will be a map, where the key is the [type path] //! and the value is the serialized data. //! The `TypedReflectSerializer` will simply output the serialized data. //! //! The `ReflectDeserializer` can be used to deserialize this map and return a `Box<dyn Reflect>`, //! where the underlying type will be a dynamic type representing some concrete type (except for opaque types). //! //! Again, it's important to remember that dynamic types may need to be converted to their concrete counterparts //! in order to be used in certain cases. //! This can be achieved using [`FromReflect`]. //! //! ``` //! # use serde::de::DeserializeSeed; //! # use bevy_reflect::{ //! # serde::{ReflectSerializer, ReflectDeserializer}, //! # Reflect, PartialReflect, FromReflect, TypeRegistry //! # }; //! #[derive(Reflect, PartialEq, Debug)] //! struct MyStruct { //! foo: i32 //! } //! //! let original_value = MyStruct { //! foo: 123 //! }; //! //! // Register //! let mut registry = TypeRegistry::new(); //! registry.register::<MyStruct>(); //! //! // Serialize //! let reflect_serializer = ReflectSerializer::new(original_value.as_partial_reflect(), &registry); //! let serialized_value: String = ron::to_string(&reflect_serializer).unwrap(); //! //! // Deserialize //! let reflect_deserializer = ReflectDeserializer::new(&registry); //! let deserialized_value: Box<dyn PartialReflect> = reflect_deserializer.deserialize( //! &mut ron::Deserializer::from_str(&serialized_value).unwrap() //! ).unwrap(); //! //! // Convert //! let converted_value = <MyStruct as FromReflect>::from_reflect(&*deserialized_value).unwrap(); //! //! assert_eq!(original_value, converted_value); //! ``` //! //! # Limitations //! //! While this crate offers a lot in terms of adding reflection to Rust, //! it does come with some limitations that don't make it as featureful as reflection //! in other programming languages. //! //! ## Non-Static Lifetimes //! //! One of the most obvious limitations is the `'static` requirement. //! Rust requires fields to define a lifetime for referenced data, //! but [`Reflect`] requires all types to have a `'static` lifetime. //! This makes it impossible to reflect any type with non-static borrowed data. //! //! ## Generic Function Reflection //! //! Another limitation is the inability to reflect over generic functions directly. It can be done, but will //! typically require manual monomorphization (i.e. manually specifying the types the generic method can //! take). //! //! # Features //! //! ## `bevy` //! //! | Default | Dependencies | //! | :-----: | :-------------------------------------------------: | //! | ❌ | [`bevy_math`], [`glam`], [`indexmap`], [`smallvec`] | //! //! This feature makes it so that the appropriate reflection traits are implemented on all the types //! necessary for the [Bevy] game engine. //! enables the optional dependencies: [`bevy_math`], [`glam`], [`indexmap`], and [`smallvec`]. //! These dependencies are used by the [Bevy] game engine and must define their reflection implementations //! within this crate due to Rust's [orphan rule]. //! //! ## `functions` //! //! | Default | Dependencies | //! | :-----: | :-------------------------------: | //! | ❌ | [`bevy_reflect_derive/functions`] | //! //! This feature allows creating a [`DynamicFunction`] or [`DynamicFunctionMut`] from Rust functions. Dynamic //! functions can then be called with valid [`ArgList`]s. //! //! For more information, read the [`func`] module docs. //! //! ## `documentation` //! //! | Default | Dependencies | //! | :-----: | :-------------------------------------------: | //! | ❌ | [`bevy_reflect_derive/documentation`] | //! //! This feature enables capturing doc comments as strings for items that [derive `Reflect`]. //! Documentation information can then be accessed at runtime on the [`TypeInfo`] of that item. //! //! This can be useful for generating documentation for scripting language interop or //! for displaying tooltips in an editor. //! //! ## `debug` //! //! | Default | Dependencies | //! | :-----: | :-------------------------------------------: | //! | ✅ | `debug_stack` | //! //! This feature enables useful debug features for reflection. //! //! This includes the `debug_stack` feature, //! which enables capturing the type stack when serializing or deserializing a type //! and displaying it in error messages. //! //! ## `auto_register_inventory`/`auto_register_static` //! //! | Default | Dependencies | //! | :-----: | :-------------------------------: | //! | ✅ | `bevy_reflect_derive/auto_register_inventory` | //! | ❌ | `bevy_reflect_derive/auto_register_static` | //! //! These features enable automatic registration of types that derive [`Reflect`]. //! //! - `auto_register_inventory` uses `inventory` to collect types on supported platforms (Linux, macOS, iOS, FreeBSD, Android, Windows, WebAssembly). //! - `auto_register_static` uses platform-independent way to collect types, but requires additional setup and might //! slow down compilation, so it should only be used on platforms not supported by `inventory`. //! See documentation for [`load_type_registrations`] macro for more info //! //! When this feature is enabled `bevy_reflect` will automatically collects all types that derive [`Reflect`] on app startup, //! and [`TypeRegistry::register_derived_types`] can be used to register these types at any point in the program. //! However, this does not apply to types with generics: their desired monomorphized representations must be registered manually. //! //! [Reflection]: https://en.wikipedia.org/wiki/Reflective_programming //! [Bevy]: https://bevy.org/ //! [limitations]: #limitations //! [`bevy_reflect`]: crate //! [introspection]: https://en.wikipedia.org/wiki/Type_introspection //! [subtraits]: #the-reflection-subtraits //! [the type registry]: #type-registration //! [runtime cost]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html#trait-objects-perform-dynamic-dispatch //! [the language feature for dyn upcasting coercion]: https://github.com/rust-lang/rust/issues/65991 //! [derive macro]: derive@crate::Reflect //! [`'static` lifetime]: https://doc.rust-lang.org/rust-by-example/scope/lifetime/static_lifetime.html#trait-bound //! [`Function`]: crate::func::Function //! [derive macro documentation]: derive@crate::Reflect //! [deriving `Reflect`]: derive@crate::Reflect //! [type data]: TypeData //! [`ReflectDefault`]: std_traits::ReflectDefault //! [object-safe]: https://doc.rust-lang.org/reference/items/traits.html#object-safety //! [`serde`]: ::serde //! [`ReflectSerializer`]: serde::ReflectSerializer //! [`TypedReflectSerializer`]: serde::TypedReflectSerializer //! [`ReflectDeserializer`]: serde::ReflectDeserializer //! [`TypedReflectDeserializer`]: serde::TypedReflectDeserializer //! [registry]: TypeRegistry //! [type information]: TypeInfo //! [type path]: TypePath //! [type registry]: TypeRegistry //! [`bevy_math`]: https://docs.rs/bevy_math/latest/bevy_math/ //! [`glam`]: https://docs.rs/glam/latest/glam/ //! [`smallvec`]: https://docs.rs/smallvec/latest/smallvec/ //! [`indexmap`]: https://docs.rs/indexmap/latest/indexmap/ //! [orphan rule]: https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type:~:text=But%20we%20can%E2%80%99t,implementation%20to%20use. //! [`bevy_reflect_derive/documentation`]: bevy_reflect_derive //! [`bevy_reflect_derive/functions`]: bevy_reflect_derive //! [`DynamicFunction`]: crate::func::DynamicFunction //! [`DynamicFunctionMut`]: crate::func::DynamicFunctionMut //! [`ArgList`]: crate::func::ArgList //! [derive `Reflect`]: derive@crate::Reflect #![no_std] #[cfg(feature = "std")] extern crate std; extern crate alloc; // Required to make proc macros work in bevy itself. extern crate self as bevy_reflect; mod array; mod error; mod fields; mod from_reflect; #[cfg(feature = "functions")] pub mod func; mod is; mod kind; mod list; mod map; mod path; mod reflect; mod reflectable; mod remote; mod set; mod struct_trait; mod tuple; mod tuple_struct; mod type_info; mod type_path; mod type_registry; mod impls { mod alloc; mod bevy_platform; mod core; mod foldhash; #[cfg(feature = "hashbrown")] mod hashbrown; mod macros; #[cfg(feature = "std")] mod std; #[cfg(feature = "glam")] mod glam; #[cfg(feature = "indexmap")] mod indexmap; #[cfg(feature = "petgraph")] mod petgraph; #[cfg(feature = "smallvec")] mod smallvec; #[cfg(feature = "smol_str")] mod smol_str; #[cfg(feature = "uuid")] mod uuid; #[cfg(feature = "wgpu-types")] mod wgpu_types; } pub mod attributes; mod enums; mod generics; pub mod serde; pub mod std_traits; #[cfg(feature = "debug_stack")] mod type_info_stack; pub mod utility; /// The reflect prelude. /// /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { pub use crate::std_traits::*; #[doc(hidden)] pub use crate::{ reflect_trait, FromReflect, GetField, GetPath, GetTupleStructField, PartialReflect, Reflect, ReflectDeserialize, ReflectFromReflect, ReflectPath, ReflectSerialize, Struct, TupleStruct, TypePath, }; #[cfg(feature = "functions")] pub use crate::func::{Function, IntoFunction, IntoFunctionMut}; } pub use array::*; pub use enums::*; pub use error::*; pub use fields::*; pub use from_reflect::*; pub use generics::*; pub use is::*; pub use kind::*; pub use list::*; pub use map::*; pub use path::*; pub use reflect::*; pub use reflectable::*; pub use remote::*; pub use set::*; pub use struct_trait::*; pub use tuple::*; pub use tuple_struct::*; pub use type_info::*; pub use type_path::*; pub use type_registry::*; pub use bevy_reflect_derive::*; pub use erased_serde; /// Exports used by the reflection macros. /// /// These are not meant to be used directly and are subject to breaking changes. #[doc(hidden)] pub mod __macro_exports { use crate::{ DynamicArray, DynamicEnum, DynamicList, DynamicMap, DynamicStruct, DynamicTuple, DynamicTupleStruct, GetTypeRegistration, TypeRegistry, }; /// Re-exports of items from the [`alloc`] crate. /// /// This is required because in `std` environments (e.g., the `std` feature is enabled) /// the `alloc` crate may not have been included, making its namespace unreliable. pub mod alloc_utils { pub use ::alloc::{ borrow::{Cow, ToOwned}, boxed::Box, string::ToString, }; } /// A wrapper trait around [`GetTypeRegistration`]. /// /// This trait is used by the derive macro to recursively register all type dependencies. /// It's used instead of `GetTypeRegistration` directly to avoid making dynamic types also /// implement `GetTypeRegistration` in order to be used as active fields. /// /// This trait has a blanket implementation for all types that implement `GetTypeRegistration` /// and manual implementations for all dynamic types (which simply do nothing). #[diagnostic::on_unimplemented( message = "`{Self}` does not implement `GetTypeRegistration` so cannot be registered for reflection", note = "consider annotating `{Self}` with `#[derive(Reflect)]`" )] pub trait RegisterForReflection { #[expect( unused_variables, reason = "The parameters here are intentionally unused by the default implementation; however, putting underscores here will result in the underscores being copied by rust-analyzer's tab completion." )] fn __register(registry: &mut TypeRegistry) {} } impl<T: GetTypeRegistration> RegisterForReflection for T { fn __register(registry: &mut TypeRegistry) { registry.register::<T>(); } } impl RegisterForReflection for DynamicEnum {} impl RegisterForReflection for DynamicTupleStruct {} impl RegisterForReflection for DynamicStruct {} impl RegisterForReflection for DynamicMap {} impl RegisterForReflection for DynamicList {} impl RegisterForReflection for DynamicArray {} impl RegisterForReflection for DynamicTuple {} /// Automatic reflect registration implementation #[cfg(feature = "auto_register")] pub mod auto_register { pub use super::*; #[cfg(all( not(feature = "auto_register_inventory"), not(feature = "auto_register_static") ))] compile_error!( "Choosing a backend is required for automatic reflect registration. Please enable either the \"auto_register_inventory\" or the \"auto_register_static\" feature." ); /// inventory impl #[cfg(all( not(feature = "auto_register_static"), feature = "auto_register_inventory" ))] mod __automatic_type_registration_impl { use super::*; pub use inventory; /// Stores type registration functions pub struct AutomaticReflectRegistrations(pub fn(&mut TypeRegistry)); /// Registers all collected types. pub fn register_types(registry: &mut TypeRegistry) { #[cfg(target_family = "wasm")] wasm_support::init(); for registration_fn in inventory::iter::<AutomaticReflectRegistrations> { registration_fn.0(registry); } } inventory::collect!(AutomaticReflectRegistrations); #[cfg(target_family = "wasm")] mod wasm_support { use bevy_platform::sync::atomic::{AtomicBool, Ordering}; static INIT_DONE: AtomicBool = AtomicBool::new(false); #[expect(unsafe_code, reason = "This function is generated by linker.")] unsafe extern "C" { fn __wasm_call_ctors(); } /// This function must be called before using [`inventory::iter`] on [`AutomaticReflectRegistrations`] to run constructors on all platforms. pub fn init() { if INIT_DONE.swap(true, Ordering::Relaxed) { return; }; #[expect( unsafe_code, reason = "This function must be called to use inventory on wasm." )] // SAFETY: // This will call constructors on wasm platforms at most once (as long as `init` is the only function that calls `__wasm_call_ctors`). // // For more information see: https://docs.rs/inventory/latest/inventory/#webassembly-and-constructors unsafe { __wasm_call_ctors(); } } } } /// static impl #[cfg(feature = "auto_register_static")] mod __automatic_type_registration_impl { use super::*; use alloc::vec::Vec; use bevy_platform::sync::Mutex; static REGISTRATION_FNS: Mutex<Vec<fn(&mut TypeRegistry)>> = Mutex::new(Vec::new()); /// Adds a new registration function for [`TypeRegistry`] pub fn push_registration_fn(registration_fn: fn(&mut TypeRegistry)) { REGISTRATION_FNS.lock().unwrap().push(registration_fn); } /// Registers all collected types. pub fn register_types(registry: &mut TypeRegistry) { for func in REGISTRATION_FNS.lock().unwrap().iter() { (func)(registry); } } } #[cfg(any(feature = "auto_register_static", feature = "auto_register_inventory"))] pub use __automatic_type_registration_impl::*; } } #[cfg(test)] #[expect( clippy::approx_constant, reason = "We don't need the exact value of Pi here." )] mod tests { use ::serde::{de::DeserializeSeed, Deserialize, Serialize}; use alloc::{ borrow::Cow, boxed::Box, format,
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/reflect.rs
crates/bevy_reflect/src/reflect.rs
use crate::{ array_debug, enum_debug, list_debug, map_debug, set_debug, struct_debug, tuple_debug, tuple_struct_debug, DynamicTypePath, DynamicTyped, OpaqueInfo, ReflectCloneError, ReflectKind, ReflectKindMismatchError, ReflectMut, ReflectOwned, ReflectRef, TypeInfo, TypePath, Typed, }; use alloc::borrow::Cow; use alloc::boxed::Box; use alloc::string::ToString; use core::{ any::{Any, TypeId}, fmt::Debug, }; use thiserror::Error; use crate::utility::NonGenericTypeInfoCell; /// A enumeration of all error outcomes that might happen when running [`try_apply`](PartialReflect::try_apply). #[derive(Error, Debug)] pub enum ApplyError { #[error("attempted to apply `{from_kind}` to `{to_kind}`")] /// Attempted to apply the wrong [kind](ReflectKind) to a type, e.g. a struct to an enum. MismatchedKinds { /// Kind of the value we attempted to apply. from_kind: ReflectKind, /// Kind of the type we attempted to apply the value to. to_kind: ReflectKind, }, #[error("enum variant `{variant_name}` doesn't have a field named `{field_name}`")] /// Enum variant that we tried to apply to was missing a field. MissingEnumField { /// Name of the enum variant. variant_name: Box<str>, /// Name of the missing field. field_name: Box<str>, }, #[error("`{from_type}` is not `{to_type}`")] /// Tried to apply incompatible types. MismatchedTypes { /// Type of the value we attempted to apply. from_type: Box<str>, /// Type we attempted to apply the value to. to_type: Box<str>, }, #[error("attempted to apply type with {from_size} size to a type with {to_size} size")] /// Attempted to apply an [array-like] type to another of different size, e.g. a [u8; 4] to [u8; 3]. /// /// [array-like]: crate::Array DifferentSize { /// Size of the value we attempted to apply, in elements. from_size: usize, /// Size of the type we attempted to apply the value to, in elements. to_size: usize, }, #[error("variant with name `{variant_name}` does not exist on enum `{enum_name}`")] /// The enum we tried to apply to didn't contain a variant with the give name. UnknownVariant { /// Name of the enum. enum_name: Box<str>, /// Name of the missing variant. variant_name: Box<str>, }, } impl From<ReflectKindMismatchError> for ApplyError { fn from(value: ReflectKindMismatchError) -> Self { Self::MismatchedKinds { from_kind: value.received, to_kind: value.expected, } } } /// The foundational trait of [`bevy_reflect`], used for accessing and modifying data dynamically. /// /// This is a supertrait of [`Reflect`], /// meaning any type which implements `Reflect` implements `PartialReflect` by definition. /// /// It's recommended to use [the derive macro for `Reflect`] rather than manually implementing this trait. /// Doing so will automatically implement this trait as well as many other useful traits for reflection, /// including one of the appropriate subtraits: [`Struct`], [`TupleStruct`] or [`Enum`]. /// /// See the [crate-level documentation] to see how this trait and its subtraits can be used. /// /// [`bevy_reflect`]: crate /// [the derive macro for `Reflect`]: bevy_reflect_derive::Reflect /// [`Struct`]: crate::Struct /// [`TupleStruct`]: crate::TupleStruct /// [`Enum`]: crate::Enum /// [crate-level documentation]: crate #[diagnostic::on_unimplemented( message = "`{Self}` does not implement `PartialReflect` so cannot be introspected", note = "consider annotating `{Self}` with `#[derive(Reflect)]`" )] pub trait PartialReflect: DynamicTypePath + Send + Sync where // NB: we don't use `Self: Any` since for downcasting, `Reflect` should be used. Self: 'static, { /// Returns the [`TypeInfo`] of the type _represented_ by this value. /// /// For most types, this will simply return their own `TypeInfo`. /// However, for dynamic types, such as [`DynamicStruct`] or [`DynamicList`], /// this will return the type they represent /// (or `None` if they don't represent any particular type). /// /// This method is great if you have an instance of a type or a `dyn Reflect`, /// and want to access its [`TypeInfo`]. However, if this method is to be called /// frequently, consider using [`TypeRegistry::get_type_info`] as it can be more /// performant for such use cases. /// /// [`DynamicStruct`]: crate::DynamicStruct /// [`DynamicList`]: crate::DynamicList /// [`TypeRegistry::get_type_info`]: crate::TypeRegistry::get_type_info fn get_represented_type_info(&self) -> Option<&'static TypeInfo>; /// Casts this type to a boxed, reflected value. /// /// This is useful for coercing trait objects. fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect>; /// Casts this type to a reflected value. /// /// This is useful for coercing trait objects. fn as_partial_reflect(&self) -> &dyn PartialReflect; /// Casts this type to a mutable, reflected value. /// /// This is useful for coercing trait objects. fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect; /// Attempts to cast this type to a boxed, [fully-reflected] value. /// /// [fully-reflected]: Reflect fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>; /// Attempts to cast this type to a [fully-reflected] value. /// /// [fully-reflected]: Reflect fn try_as_reflect(&self) -> Option<&dyn Reflect>; /// Attempts to cast this type to a mutable, [fully-reflected] value. /// /// [fully-reflected]: Reflect fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect>; /// Applies a reflected value to this value. /// /// If `Self` implements a [reflection subtrait], then the semantics of this /// method are as follows: /// - If `Self` is a [`Struct`], then the value of each named field of `value` is /// applied to the corresponding named field of `self`. Fields which are /// not present in both structs are ignored. /// - If `Self` is a [`TupleStruct`] or [`Tuple`], then the value of each /// numbered field is applied to the corresponding numbered field of /// `self.` Fields which are not present in both values are ignored. /// - If `Self` is an [`Enum`], then the variant of `self` is `updated` to match /// the variant of `value`. The corresponding fields of that variant are /// applied from `value` onto `self`. Fields which are not present in both /// values are ignored. /// - If `Self` is a [`List`] or [`Array`], then each element of `value` is applied /// to the corresponding element of `self`. Up to `self.len()` items are applied, /// and excess elements in `value` are appended to `self`. /// - If `Self` is a [`Map`], then for each key in `value`, the associated /// value is applied to the value associated with the same key in `self`. /// Keys which are not present in `self` are inserted, and keys from `self` which are not present in `value` are removed. /// - If `Self` is a [`Set`], then each element of `value` is applied to the corresponding /// element of `Self`. If an element of `value` does not exist in `Self` then it is /// cloned and inserted. If an element from `self` is not present in `value` then it is removed. /// - If `Self` is none of these, then `value` is downcast to `Self`, cloned, and /// assigned to `self`. /// /// Note that `Reflect` must be implemented manually for [`List`]s, /// [`Map`]s, and [`Set`]s in order to achieve the correct semantics, as derived /// implementations will have the semantics for [`Struct`], [`TupleStruct`], [`Enum`] /// or none of the above depending on the kind of type. For lists, maps, and sets, use the /// [`list_apply`], [`map_apply`], and [`set_apply`] helper functions when implementing this method. /// /// [reflection subtrait]: crate#the-reflection-subtraits /// [`Struct`]: crate::Struct /// [`TupleStruct`]: crate::TupleStruct /// [`Tuple`]: crate::Tuple /// [`Enum`]: crate::Enum /// [`List`]: crate::List /// [`Array`]: crate::Array /// [`Map`]: crate::Map /// [`Set`]: crate::Set /// [`list_apply`]: crate::list_apply /// [`map_apply`]: crate::map_apply /// [`set_apply`]: crate::set_apply /// /// # Panics /// /// Derived implementations of this method will panic: /// - If the type of `value` is not of the same kind as `Self` (e.g. if `Self` is /// a `List`, while `value` is a `Struct`). /// - If `Self` is any complex type and the corresponding fields or elements of /// `self` and `value` are not of the same type. /// - If `Self` is an opaque type and `value` cannot be downcast to `Self` fn apply(&mut self, value: &dyn PartialReflect) { PartialReflect::try_apply(self, value).unwrap(); } /// Tries to [`apply`](PartialReflect::apply) a reflected value to this value. /// /// Functions the same as the [`apply`](PartialReflect::apply) function but returns an error instead of /// panicking. /// /// # Handling Errors /// /// This function may leave `self` in a partially mutated state if a error was encountered on the way. /// consider maintaining a cloned instance of this data you can switch to if a error is encountered. fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError>; /// Returns a zero-sized enumeration of "kinds" of type. /// /// See [`ReflectKind`]. fn reflect_kind(&self) -> ReflectKind { self.reflect_ref().kind() } /// Returns an immutable enumeration of "kinds" of type. /// /// See [`ReflectRef`]. fn reflect_ref(&self) -> ReflectRef<'_>; /// Returns a mutable enumeration of "kinds" of type. /// /// See [`ReflectMut`]. fn reflect_mut(&mut self) -> ReflectMut<'_>; /// Returns an owned enumeration of "kinds" of type. /// /// See [`ReflectOwned`]. fn reflect_owned(self: Box<Self>) -> ReflectOwned; /// Converts this reflected value into its dynamic representation based on its [kind]. /// /// For example, a [`List`] type will internally invoke [`List::to_dynamic_list`], returning [`DynamicList`]. /// A [`Struct`] type will invoke [`Struct::to_dynamic_struct`], returning [`DynamicStruct`]. /// And so on. /// /// If the [kind] is [opaque], then the value will attempt to be cloned directly via [`reflect_clone`], /// since opaque types do not have any standard dynamic representation. /// /// To attempt to clone the value directly such that it returns a concrete instance of this type, /// use [`reflect_clone`]. /// /// # Panics /// /// This method will panic if the [kind] is [opaque] and the call to [`reflect_clone`] fails. /// /// # Example /// /// ``` /// # use bevy_reflect::{PartialReflect}; /// let value = (1, true, 3.14); /// let dynamic_value = value.to_dynamic(); /// assert!(dynamic_value.is_dynamic()) /// ``` /// /// [kind]: PartialReflect::reflect_kind /// [`List`]: crate::List /// [`List::to_dynamic_list`]: crate::List::to_dynamic_list /// [`DynamicList`]: crate::DynamicList /// [`Struct`]: crate::Struct /// [`Struct::to_dynamic_struct`]: crate::Struct::to_dynamic_struct /// [`DynamicStruct`]: crate::DynamicStruct /// [opaque]: crate::ReflectKind::Opaque /// [`reflect_clone`]: PartialReflect::reflect_clone fn to_dynamic(&self) -> Box<dyn PartialReflect> { match self.reflect_ref() { ReflectRef::Struct(dyn_struct) => Box::new(dyn_struct.to_dynamic_struct()), ReflectRef::TupleStruct(dyn_tuple_struct) => { Box::new(dyn_tuple_struct.to_dynamic_tuple_struct()) } ReflectRef::Tuple(dyn_tuple) => Box::new(dyn_tuple.to_dynamic_tuple()), ReflectRef::List(dyn_list) => Box::new(dyn_list.to_dynamic_list()), ReflectRef::Array(dyn_array) => Box::new(dyn_array.to_dynamic_array()), ReflectRef::Map(dyn_map) => Box::new(dyn_map.to_dynamic_map()), ReflectRef::Set(dyn_set) => Box::new(dyn_set.to_dynamic_set()), ReflectRef::Enum(dyn_enum) => Box::new(dyn_enum.to_dynamic_enum()), #[cfg(feature = "functions")] ReflectRef::Function(dyn_function) => Box::new(dyn_function.to_dynamic_function()), ReflectRef::Opaque(value) => value.reflect_clone().unwrap().into_partial_reflect(), } } /// Attempts to clone `Self` using reflection. /// /// Unlike [`to_dynamic`], which generally returns a dynamic representation of `Self`, /// this method attempts create a clone of `Self` directly, if possible. /// /// If the clone cannot be performed, an appropriate [`ReflectCloneError`] is returned. /// /// # Example /// /// ``` /// # use bevy_reflect::PartialReflect; /// let value = (1, true, 3.14); /// let cloned = value.reflect_clone().unwrap(); /// assert!(cloned.is::<(i32, bool, f64)>()) /// ``` /// /// [`to_dynamic`]: PartialReflect::to_dynamic fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> { Err(ReflectCloneError::NotImplemented { type_path: Cow::Owned(self.reflect_type_path().to_string()), }) } /// For a type implementing [`PartialReflect`], combines `reflect_clone` and /// `take` in a useful fashion, automatically constructing an appropriate /// [`ReflectCloneError`] if the downcast fails. /// /// This is an associated function, rather than a method, because methods /// with generic types prevent dyn-compatibility. fn reflect_clone_and_take<T: 'static>(&self) -> Result<T, ReflectCloneError> where Self: TypePath + Sized, { self.reflect_clone()? .take() .map_err(|_| ReflectCloneError::FailedDowncast { expected: Cow::Borrowed(<Self as TypePath>::type_path()), received: Cow::Owned(self.reflect_type_path().to_string()), }) } /// Returns a hash of the value (which includes the type). /// /// If the underlying type does not support hashing, returns `None`. fn reflect_hash(&self) -> Option<u64> { None } /// Returns a "partial equality" comparison result. /// /// If the underlying type does not support equality testing, returns `None`. fn reflect_partial_eq(&self, _value: &dyn PartialReflect) -> Option<bool> { None } /// Debug formatter for the value. /// /// Any value that is not an implementor of other `Reflect` subtraits /// (e.g. [`List`], [`Map`]), will default to the format: `"Reflect(type_path)"`, /// where `type_path` is the [type path] of the underlying type. /// /// [`List`]: crate::List /// [`Map`]: crate::Map /// [type path]: TypePath::type_path fn debug(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self.reflect_ref() { ReflectRef::Struct(dyn_struct) => struct_debug(dyn_struct, f), ReflectRef::TupleStruct(dyn_tuple_struct) => tuple_struct_debug(dyn_tuple_struct, f), ReflectRef::Tuple(dyn_tuple) => tuple_debug(dyn_tuple, f), ReflectRef::List(dyn_list) => list_debug(dyn_list, f), ReflectRef::Array(dyn_array) => array_debug(dyn_array, f), ReflectRef::Map(dyn_map) => map_debug(dyn_map, f), ReflectRef::Set(dyn_set) => set_debug(dyn_set, f), ReflectRef::Enum(dyn_enum) => enum_debug(dyn_enum, f), #[cfg(feature = "functions")] ReflectRef::Function(dyn_function) => dyn_function.fmt(f), ReflectRef::Opaque(_) => write!(f, "Reflect({})", self.reflect_type_path()), } } /// Indicates whether or not this type is a _dynamic_ type. /// /// Dynamic types include the ones built-in to this [crate], /// such as [`DynamicStruct`], [`DynamicList`], and [`DynamicTuple`]. /// However, they may be custom types used as proxies for other types /// or to facilitate scripting capabilities. /// /// By default, this method will return `false`. /// /// [`DynamicStruct`]: crate::DynamicStruct /// [`DynamicList`]: crate::DynamicList /// [`DynamicTuple`]: crate::DynamicTuple fn is_dynamic(&self) -> bool { false } } /// A core trait of [`bevy_reflect`], used for downcasting to concrete types. /// /// This is a subtrait of [`PartialReflect`], /// meaning any type which implements `Reflect` implements `PartialReflect` by definition. /// /// It's recommended to use [the derive macro] rather than manually implementing this trait. /// Doing so will automatically implement this trait, [`PartialReflect`], and many other useful traits for reflection, /// including one of the appropriate subtraits: [`Struct`], [`TupleStruct`] or [`Enum`]. /// /// If you need to use this trait as a generic bound along with other reflection traits, /// for your convenience, consider using [`Reflectable`] instead. /// /// See the [crate-level documentation] to see how this trait can be used. /// /// [`bevy_reflect`]: crate /// [the derive macro]: bevy_reflect_derive::Reflect /// [`Struct`]: crate::Struct /// [`TupleStruct`]: crate::TupleStruct /// [`Enum`]: crate::Enum /// [`Reflectable`]: crate::Reflectable /// [crate-level documentation]: crate #[diagnostic::on_unimplemented( message = "`{Self}` does not implement `Reflect` so cannot be fully reflected", note = "consider annotating `{Self}` with `#[derive(Reflect)]`" )] pub trait Reflect: PartialReflect + DynamicTyped + Any { /// Returns the value as a [`Box<dyn Any>`][core::any::Any]. /// /// For remote wrapper types, this will return the remote type instead. fn into_any(self: Box<Self>) -> Box<dyn Any>; /// Returns the value as a [`&dyn Any`][core::any::Any]. /// /// For remote wrapper types, this will return the remote type instead. fn as_any(&self) -> &dyn Any; /// Returns the value as a [`&mut dyn Any`][core::any::Any]. /// /// For remote wrapper types, this will return the remote type instead. fn as_any_mut(&mut self) -> &mut dyn Any; /// Casts this type to a boxed, fully-reflected value. fn into_reflect(self: Box<Self>) -> Box<dyn Reflect>; /// Casts this type to a fully-reflected value. fn as_reflect(&self) -> &dyn Reflect; /// Casts this type to a mutable, fully-reflected value. fn as_reflect_mut(&mut self) -> &mut dyn Reflect; /// Performs a type-checked assignment of a reflected value to this value. /// /// If `value` does not contain a value of type `T`, returns an `Err` /// containing the trait object. fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>>; } impl dyn PartialReflect { /// Returns `true` if the underlying value represents a value of type `T`, or `false` /// otherwise. /// /// Read `is` for more information on underlying values and represented types. #[inline] pub fn represents<T: Reflect + TypePath>(&self) -> bool { self.get_represented_type_info() .is_some_and(|t| t.type_path() == T::type_path()) } /// Downcasts the value to type `T`, consuming the trait object. /// /// If the underlying value does not implement [`Reflect`] /// or is not of type `T`, returns `Err(self)`. /// /// For remote types, `T` should be the type itself rather than the wrapper type. pub fn try_downcast<T: Any>( self: Box<dyn PartialReflect>, ) -> Result<Box<T>, Box<dyn PartialReflect>> { self.try_into_reflect()? .downcast() .map_err(PartialReflect::into_partial_reflect) } /// Downcasts the value to type `T`, unboxing and consuming the trait object. /// /// If the underlying value does not implement [`Reflect`] /// or is not of type `T`, returns `Err(self)`. /// /// For remote types, `T` should be the type itself rather than the wrapper type. pub fn try_take<T: Any>(self: Box<dyn PartialReflect>) -> Result<T, Box<dyn PartialReflect>> { self.try_downcast().map(|value| *value) } /// Downcasts the value to type `T` by reference. /// /// If the underlying value does not implement [`Reflect`] /// or is not of type `T`, returns [`None`]. /// /// For remote types, `T` should be the type itself rather than the wrapper type. pub fn try_downcast_ref<T: Any>(&self) -> Option<&T> { self.try_as_reflect()?.downcast_ref() } /// Downcasts the value to type `T` by mutable reference. /// /// If the underlying value does not implement [`Reflect`] /// or is not of type `T`, returns [`None`]. /// /// For remote types, `T` should be the type itself rather than the wrapper type. pub fn try_downcast_mut<T: Any>(&mut self) -> Option<&mut T> { self.try_as_reflect_mut()?.downcast_mut() } } impl Debug for dyn PartialReflect { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.debug(f) } } // The following implementation never actually shadows the concrete TypePath implementation. // See the comment on `dyn Reflect`'s `TypePath` implementation. impl TypePath for dyn PartialReflect { fn type_path() -> &'static str { "dyn bevy_reflect::PartialReflect" } fn short_type_path() -> &'static str { "dyn PartialReflect" } } #[deny(rustdoc::broken_intra_doc_links)] impl dyn Reflect { /// Downcasts the value to type `T`, consuming the trait object. /// /// If the underlying value is not of type `T`, returns `Err(self)`. /// /// For remote types, `T` should be the type itself rather than the wrapper type. pub fn downcast<T: Any>(self: Box<dyn Reflect>) -> Result<Box<T>, Box<dyn Reflect>> { if self.is::<T>() { Ok(self.into_any().downcast().unwrap()) } else { Err(self) } } /// Downcasts the value to type `T`, unboxing and consuming the trait object. /// /// If the underlying value is not of type `T`, returns `Err(self)`. /// /// For remote types, `T` should be the type itself rather than the wrapper type. pub fn take<T: Any>(self: Box<dyn Reflect>) -> Result<T, Box<dyn Reflect>> { self.downcast::<T>().map(|value| *value) } /// Returns `true` if the underlying value is of type `T`, or `false` /// otherwise. /// /// The underlying value is the concrete type that is stored in this `dyn` object; /// it can be downcast to. In the case that this underlying value "represents" /// a different type, like the Dynamic\*\*\* types do, you can call `represents` /// to determine what type they represent. Represented types cannot be downcast /// to, but you can use [`FromReflect`] to create a value of the represented type from them. /// /// For remote types, `T` should be the type itself rather than the wrapper type. /// /// [`FromReflect`]: crate::FromReflect #[inline] pub fn is<T: Any>(&self) -> bool { self.as_any().type_id() == TypeId::of::<T>() } /// Downcasts the value to type `T` by reference. /// /// If the underlying value is not of type `T`, returns `None`. /// /// For remote types, `T` should be the type itself rather than the wrapper type. #[inline] pub fn downcast_ref<T: Any>(&self) -> Option<&T> { self.as_any().downcast_ref::<T>() } /// Downcasts the value to type `T` by mutable reference. /// /// If the underlying value is not of type `T`, returns `None`. /// /// For remote types, `T` should be the type itself rather than the wrapper type. #[inline] pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> { self.as_any_mut().downcast_mut::<T>() } } impl Debug for dyn Reflect { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.debug(f) } } impl Typed for dyn Reflect { fn type_info() -> &'static TypeInfo { static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new(); CELL.get_or_set(|| TypeInfo::Opaque(OpaqueInfo::new::<Self>())) } } // The following implementation never actually shadows the concrete `TypePath` implementation. // See this playground (https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=589064053f27bc100d90da89c6a860aa). impl TypePath for dyn Reflect { fn type_path() -> &'static str { "dyn bevy_reflect::Reflect" } fn short_type_path() -> &'static str { "dyn Reflect" } } macro_rules! impl_full_reflect { ($(<$($id:ident),* $(,)?>)? for $ty:ty $(where $($tt:tt)*)?) => { impl $(<$($id),*>)? $crate::Reflect for $ty $(where $($tt)*)? { fn into_any(self: bevy_platform::prelude::Box<Self>) -> bevy_platform::prelude::Box<dyn ::core::any::Any> { self } fn as_any(&self) -> &dyn ::core::any::Any { self } fn as_any_mut(&mut self) -> &mut dyn ::core::any::Any { self } fn into_reflect(self: bevy_platform::prelude::Box<Self>) -> bevy_platform::prelude::Box<dyn $crate::Reflect> { self } fn as_reflect(&self) -> &dyn $crate::Reflect { self } fn as_reflect_mut(&mut self) -> &mut dyn $crate::Reflect { self } fn set( &mut self, value: bevy_platform::prelude::Box<dyn $crate::Reflect>, ) -> Result<(), bevy_platform::prelude::Box<dyn $crate::Reflect>> { *self = <dyn $crate::Reflect>::take(value)?; Ok(()) } } }; } pub(crate) use impl_full_reflect;
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/type_info_stack.rs
crates/bevy_reflect/src/type_info_stack.rs
use crate::TypeInfo; use alloc::vec::Vec; use core::{ fmt::{Debug, Formatter}, slice::Iter, }; /// Helper struct for managing a stack of [`TypeInfo`] instances. /// /// This is useful for tracking the type hierarchy when serializing and deserializing types. #[derive(Default, Clone)] pub(crate) struct TypeInfoStack { stack: Vec<&'static TypeInfo>, } impl TypeInfoStack { /// Create a new empty [`TypeInfoStack`]. pub const fn new() -> Self { Self { stack: Vec::new() } } /// Push a new [`TypeInfo`] onto the stack. pub fn push(&mut self, type_info: &'static TypeInfo) { self.stack.push(type_info); } /// Pop the last [`TypeInfo`] off the stack. pub fn pop(&mut self) { self.stack.pop(); } /// Get an iterator over the stack in the order they were pushed. pub fn iter(&self) -> Iter<'_, &'static TypeInfo> { self.stack.iter() } } impl Debug for TypeInfoStack { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { let mut iter = self.iter(); if let Some(first) = iter.next() { write!(f, "`{}`", first.type_path())?; } for info in iter { write!(f, " -> `{}`", info.type_path())?; } Ok(()) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/list.rs
crates/bevy_reflect/src/list.rs
use alloc::{boxed::Box, vec::Vec}; use core::{ any::Any, fmt::{Debug, Formatter}, hash::{Hash, Hasher}, }; use bevy_reflect_derive::impl_type_path; use crate::generics::impl_generic_info_methods; use crate::{ type_info::impl_type_methods, utility::reflect_hasher, ApplyError, FromReflect, Generics, MaybeTyped, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type, TypeInfo, TypePath, }; /// A trait used to power [list-like] operations via [reflection]. /// /// This corresponds to types, like [`Vec`], which contain an ordered sequence /// of elements that implement [`Reflect`]. /// /// Unlike the [`Array`](crate::Array) trait, implementors of this trait are not expected to /// maintain a constant length. /// Methods like [insertion](List::insert) and [removal](List::remove) explicitly allow for their /// internal size to change. /// /// [`push`](List::push) and [`pop`](List::pop) have default implementations, /// however it will generally be more performant to implement them manually /// as the default implementation uses a very naive approach to find the correct position. /// /// This trait expects its elements to be ordered linearly from front to back. /// The _front_ element starts at index 0 with the _back_ element ending at the largest index. /// This contract above should be upheld by any manual implementors. /// /// Due to the [type-erasing] nature of the reflection API as a whole, /// this trait does not make any guarantees that the implementor's elements /// are homogeneous (i.e. all the same type). /// /// # Example /// /// ``` /// use bevy_reflect::{PartialReflect, Reflect, List}; /// /// let foo: &mut dyn List = &mut vec![123_u32, 456_u32, 789_u32]; /// assert_eq!(foo.len(), 3); /// /// let last_field: Box<dyn PartialReflect> = foo.pop().unwrap(); /// assert_eq!(last_field.try_downcast_ref::<u32>(), Some(&789)); /// ``` /// /// [list-like]: https://doc.rust-lang.org/book/ch08-01-vectors.html /// [reflection]: crate /// [type-erasing]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html pub trait List: PartialReflect { /// Returns a reference to the element at `index`, or `None` if out of bounds. fn get(&self, index: usize) -> Option<&dyn PartialReflect>; /// Returns a mutable reference to the element at `index`, or `None` if out of bounds. fn get_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>; /// Inserts an element at position `index` within the list, /// shifting all elements after it towards the back of the list. /// /// # Panics /// Panics if `index > len`. fn insert(&mut self, index: usize, element: Box<dyn PartialReflect>); /// Removes and returns the element at position `index` within the list, /// shifting all elements before it towards the front of the list. /// /// # Panics /// Panics if `index` is out of bounds. fn remove(&mut self, index: usize) -> Box<dyn PartialReflect>; /// Appends an element to the _back_ of the list. fn push(&mut self, value: Box<dyn PartialReflect>) { self.insert(self.len(), value); } /// Removes the _back_ element from the list and returns it, or [`None`] if it is empty. fn pop(&mut self) -> Option<Box<dyn PartialReflect>> { if self.is_empty() { None } else { Some(self.remove(self.len() - 1)) } } /// Returns the number of elements in the list. fn len(&self) -> usize; /// Returns `true` if the collection contains no elements. fn is_empty(&self) -> bool { self.len() == 0 } /// Returns an iterator over the list. fn iter(&self) -> ListIter<'_>; /// Drain the elements of this list to get a vector of owned values. /// /// After calling this function, `self` will be empty. The order of items in the returned /// [`Vec`] will match the order of items in `self`. fn drain(&mut self) -> Vec<Box<dyn PartialReflect>>; /// Creates a new [`DynamicList`] from this list. fn to_dynamic_list(&self) -> DynamicList { DynamicList { represented_type: self.get_represented_type_info(), values: self.iter().map(PartialReflect::to_dynamic).collect(), } } /// Will return `None` if [`TypeInfo`] is not available. fn get_represented_list_info(&self) -> Option<&'static ListInfo> { self.get_represented_type_info()?.as_list().ok() } } /// A container for compile-time list info. #[derive(Clone, Debug)] pub struct ListInfo { ty: Type, generics: Generics, item_info: fn() -> Option<&'static TypeInfo>, item_ty: Type, #[cfg(feature = "reflect_documentation")] docs: Option<&'static str>, } impl ListInfo { /// Create a new [`ListInfo`]. pub fn new<TList: List + TypePath, TItem: FromReflect + MaybeTyped + TypePath>() -> Self { Self { ty: Type::of::<TList>(), generics: Generics::new(), item_info: TItem::maybe_type_info, item_ty: Type::of::<TItem>(), #[cfg(feature = "reflect_documentation")] docs: None, } } /// Sets the docstring for this list. #[cfg(feature = "reflect_documentation")] pub fn with_docs(self, docs: Option<&'static str>) -> Self { Self { docs, ..self } } impl_type_methods!(ty); /// The [`TypeInfo`] of the list item. /// /// Returns `None` if the list item does not contain static type information, /// such as for dynamic types. pub fn item_info(&self) -> Option<&'static TypeInfo> { (self.item_info)() } /// The [type] of the list item. /// /// [type]: Type pub fn item_ty(&self) -> Type { self.item_ty } /// The docstring of this list, if any. #[cfg(feature = "reflect_documentation")] pub fn docs(&self) -> Option<&'static str> { self.docs } impl_generic_info_methods!(generics); } /// A list of reflected values. #[derive(Default)] pub struct DynamicList { represented_type: Option<&'static TypeInfo>, values: Vec<Box<dyn PartialReflect>>, } impl DynamicList { /// Sets the [type] to be represented by this `DynamicList`. /// # Panics /// /// Panics if the given [type] is not a [`TypeInfo::List`]. /// /// [type]: TypeInfo pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) { if let Some(represented_type) = represented_type { assert!( matches!(represented_type, TypeInfo::List(_)), "expected TypeInfo::List but received: {represented_type:?}" ); } self.represented_type = represented_type; } /// Appends a typed value to the list. pub fn push<T: PartialReflect>(&mut self, value: T) { self.values.push(Box::new(value)); } /// Appends a [`Reflect`] trait object to the list. pub fn push_box(&mut self, value: Box<dyn PartialReflect>) { self.values.push(value); } } impl List for DynamicList { fn get(&self, index: usize) -> Option<&dyn PartialReflect> { self.values.get(index).map(|value| &**value) } fn get_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> { self.values.get_mut(index).map(|value| &mut **value) } fn insert(&mut self, index: usize, element: Box<dyn PartialReflect>) { self.values.insert(index, element); } fn remove(&mut self, index: usize) -> Box<dyn PartialReflect> { self.values.remove(index) } fn push(&mut self, value: Box<dyn PartialReflect>) { DynamicList::push_box(self, value); } fn pop(&mut self) -> Option<Box<dyn PartialReflect>> { self.values.pop() } fn len(&self) -> usize { self.values.len() } fn iter(&self) -> ListIter<'_> { ListIter::new(self) } fn drain(&mut self) -> Vec<Box<dyn PartialReflect>> { self.values.drain(..).collect() } } impl PartialReflect for DynamicList { #[inline] fn get_represented_type_info(&self) -> Option<&'static TypeInfo> { self.represented_type } #[inline] fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> { self } #[inline] fn as_partial_reflect(&self) -> &dyn PartialReflect { self } #[inline] fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect { self } fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> { Err(self) } fn try_as_reflect(&self) -> Option<&dyn Reflect> { None } fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { None } fn apply(&mut self, value: &dyn PartialReflect) { list_apply(self, value); } fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { list_try_apply(self, value) } #[inline] fn reflect_kind(&self) -> ReflectKind { ReflectKind::List } #[inline] fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::List(self) } #[inline] fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::List(self) } #[inline] fn reflect_owned(self: Box<Self>) -> ReflectOwned { ReflectOwned::List(self) } #[inline] fn reflect_hash(&self) -> Option<u64> { list_hash(self) } fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> { list_partial_eq(self, value) } fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicList(")?; list_debug(self, f)?; write!(f, ")") } #[inline] fn is_dynamic(&self) -> bool { true } } impl_type_path!((in bevy_reflect) DynamicList); impl Debug for DynamicList { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.debug(f) } } impl FromIterator<Box<dyn PartialReflect>> for DynamicList { fn from_iter<I: IntoIterator<Item = Box<dyn PartialReflect>>>(values: I) -> Self { Self { represented_type: None, values: values.into_iter().collect(), } } } impl<T: PartialReflect> FromIterator<T> for DynamicList { fn from_iter<I: IntoIterator<Item = T>>(values: I) -> Self { values .into_iter() .map(|field| Box::new(field).into_partial_reflect()) .collect() } } impl IntoIterator for DynamicList { type Item = Box<dyn PartialReflect>; type IntoIter = alloc::vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.values.into_iter() } } impl<'a> IntoIterator for &'a DynamicList { type Item = &'a dyn PartialReflect; type IntoIter = ListIter<'a>; fn into_iter(self) -> Self::IntoIter { self.iter() } } /// An iterator over an [`List`]. pub struct ListIter<'a> { list: &'a dyn List, index: usize, } impl ListIter<'_> { /// Creates a new [`ListIter`]. #[inline] pub const fn new(list: &dyn List) -> ListIter<'_> { ListIter { list, index: 0 } } } impl<'a> Iterator for ListIter<'a> { type Item = &'a dyn PartialReflect; #[inline] fn next(&mut self) -> Option<Self::Item> { let value = self.list.get(self.index); self.index += value.is_some() as usize; value } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let size = self.list.len(); (size, Some(size)) } } impl ExactSizeIterator for ListIter<'_> {} /// Returns the `u64` hash of the given [list](List). #[inline] pub fn list_hash<L: List>(list: &L) -> Option<u64> { let mut hasher = reflect_hasher(); Any::type_id(list).hash(&mut hasher); list.len().hash(&mut hasher); for value in list.iter() { hasher.write_u64(value.reflect_hash()?); } Some(hasher.finish()) } /// Applies the elements of `b` to the corresponding elements of `a`. /// /// If the length of `b` is greater than that of `a`, the excess elements of `b` /// are cloned and appended to `a`. /// /// # Panics /// /// This function panics if `b` is not a list. #[inline] pub fn list_apply<L: List>(a: &mut L, b: &dyn PartialReflect) { if let Err(err) = list_try_apply(a, b) { panic!("{err}"); } } /// Tries to apply the elements of `b` to the corresponding elements of `a` and /// returns a Result. /// /// If the length of `b` is greater than that of `a`, the excess elements of `b` /// are cloned and appended to `a`. /// /// # Errors /// /// This function returns an [`ApplyError::MismatchedKinds`] if `b` is not a list or if /// applying elements to each other fails. #[inline] pub fn list_try_apply<L: List>(a: &mut L, b: &dyn PartialReflect) -> Result<(), ApplyError> { let list_value = b.reflect_ref().as_list()?; for (i, value) in list_value.iter().enumerate() { if i < a.len() { if let Some(v) = a.get_mut(i) { v.try_apply(value)?; } } else { List::push(a, value.to_dynamic()); } } Ok(()) } /// Compares a [`List`] with a [`Reflect`] value. /// /// Returns true if and only if all of the following are true: /// - `b` is a list; /// - `b` is the same length as `a`; /// - [`PartialReflect::reflect_partial_eq`] returns `Some(true)` for pairwise elements of `a` and `b`. /// /// Returns [`None`] if the comparison couldn't even be performed. #[inline] pub fn list_partial_eq<L: List + ?Sized>(a: &L, b: &dyn PartialReflect) -> Option<bool> { let ReflectRef::List(list) = b.reflect_ref() else { return Some(false); }; if a.len() != list.len() { return Some(false); } for (a_value, b_value) in a.iter().zip(list.iter()) { let eq_result = a_value.reflect_partial_eq(b_value); if let failed @ (Some(false) | None) = eq_result { return failed; } } Some(true) } /// The default debug formatter for [`List`] types. /// /// # Example /// ``` /// use bevy_reflect::Reflect; /// /// let my_list: &dyn Reflect = &vec![1, 2, 3]; /// println!("{:#?}", my_list); /// /// // Output: /// /// // [ /// // 1, /// // 2, /// // 3, /// // ] /// ``` #[inline] pub fn list_debug(dyn_list: &dyn List, f: &mut Formatter<'_>) -> core::fmt::Result { let mut debug = f.debug_list(); for item in dyn_list.iter() { debug.entry(&item as &dyn Debug); } debug.finish() } #[cfg(test)] mod tests { use super::DynamicList; use crate::Reflect; use alloc::{boxed::Box, vec}; use core::assert_eq; #[test] fn test_into_iter() { let mut list = DynamicList::default(); list.push(0usize); list.push(1usize); list.push(2usize); let items = list.into_iter(); for (index, item) in items.into_iter().enumerate() { let value = item .try_take::<usize>() .expect("couldn't downcast to usize"); assert_eq!(index, value); } } #[test] fn next_index_increment() { const SIZE: usize = if cfg!(debug_assertions) { 4 } else { // If compiled in release mode, verify we dont overflow usize::MAX }; let b = Box::new(vec![(); SIZE]).into_reflect(); let list = b.reflect_ref().as_list().unwrap(); let mut iter = list.iter(); iter.index = SIZE - 1; assert!(iter.next().is_some()); // When None we should no longer increase index assert!(iter.next().is_none()); assert!(iter.index == SIZE); assert!(iter.next().is_none()); assert!(iter.index == SIZE); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/remote.rs
crates/bevy_reflect/src/remote.rs
use crate::Reflect; /// Marks a type as a [reflectable] wrapper for a remote type. /// /// This allows types from external libraries (remote types) to be included in reflection. /// /// # Safety /// /// It is highly recommended to avoid implementing this trait manually and instead use the /// [`#[reflect_remote]`](crate::reflect_remote) attribute macro. /// This is because the trait tends to rely on [`transmute`], which is [very unsafe]. /// /// The macro will ensure that the following safety requirements are met: /// - `Self` is a single-field tuple struct (i.e. a newtype) containing the remote type. /// - `Self` is `#[repr(transparent)]` over the remote type. /// /// Additionally, the macro will automatically generate [`Reflect`] and [`FromReflect`] implementations, /// along with compile-time assertions to validate that the safety requirements have been met. /// /// # Example /// /// ``` /// use bevy_reflect_derive::{reflect_remote, Reflect}; /// /// mod some_lib { /// pub struct TheirType { /// pub value: u32 /// } /// } /// /// #[reflect_remote(some_lib::TheirType)] /// struct MyType { /// pub value: u32 /// } /// /// #[derive(Reflect)] /// struct MyStruct { /// #[reflect(remote = MyType)] /// data: some_lib::TheirType, /// } /// ``` /// /// [reflectable]: Reflect /// [`transmute`]: core::mem::transmute /// [very unsafe]: https://doc.rust-lang.org/1.71.0/nomicon/transmutes.html /// [`FromReflect`]: crate::FromReflect pub trait ReflectRemote: Reflect { /// The remote type this type represents via reflection. type Remote; /// Converts a reference of this wrapper to a reference of its remote type. fn as_remote(&self) -> &Self::Remote; /// Converts a mutable reference of this wrapper to a mutable reference of its remote type. fn as_remote_mut(&mut self) -> &mut Self::Remote; /// Converts this wrapper into its remote type. fn into_remote(self) -> Self::Remote; /// Converts a reference of the remote type to a reference of this wrapper. fn as_wrapper(remote: &Self::Remote) -> &Self; /// Converts a mutable reference of the remote type to a mutable reference of this wrapper. fn as_wrapper_mut(remote: &mut Self::Remote) -> &mut Self; /// Converts the remote type into this wrapper. fn into_wrapper(remote: Self::Remote) -> Self; }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/reflectable.rs
crates/bevy_reflect/src/reflectable.rs
use crate::{GetTypeRegistration, Reflect, TypePath, Typed}; /// A catch-all trait that is bound by the core reflection traits, /// useful to simplify reflection-based generic type bounds. /// /// You do _not_ need to implement this trait manually. /// It is automatically implemented for all types that implement its supertraits. /// And these supertraits are all automatically derived with the [`Reflect` derive macro]. /// /// This should namely be used to bound generic arguments to the necessary traits for reflection. /// Doing this has the added benefit of reducing migration costs, as a change to the required traits /// is automatically handled by this trait. /// /// For now, the supertraits of this trait includes: /// * [`Reflect`] /// * [`GetTypeRegistration`] /// * [`Typed`] /// * [`TypePath`] /// /// ## Example /// /// ``` /// # use bevy_reflect::{Reflect, Reflectable}; /// #[derive(Reflect)] /// struct MyStruct<T: Reflectable> { /// value: T /// } /// ``` /// /// [`Reflect` derive macro]: bevy_reflect_derive::Reflect pub trait Reflectable: Reflect + GetTypeRegistration + Typed + TypePath {} impl<T: Reflect + GetTypeRegistration + Typed + TypePath> Reflectable for T {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/type_registry.rs
crates/bevy_reflect/src/type_registry.rs
use crate::{serde::Serializable, FromReflect, Reflect, TypeInfo, TypePath, Typed}; use alloc::{boxed::Box, string::String}; use bevy_platform::{ collections::{HashMap, HashSet}, sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard}, }; use bevy_ptr::{Ptr, PtrMut}; use bevy_utils::TypeIdMap; use core::{ any::TypeId, fmt::Debug, ops::{Deref, DerefMut}, }; use downcast_rs::{impl_downcast, Downcast}; use serde::{Deserialize, Serialize}; /// A registry of [reflected] types. /// /// This struct is used as the central store for type information. /// [Registering] a type will generate a new [`TypeRegistration`] entry in this store /// using a type's [`GetTypeRegistration`] implementation /// (which is automatically implemented when using [`#[derive(Reflect)]`](derive@crate::Reflect)). /// /// See the [crate-level documentation] for more information. /// /// [reflected]: crate /// [Registering]: TypeRegistry::register /// [crate-level documentation]: crate pub struct TypeRegistry { registrations: TypeIdMap<TypeRegistration>, short_path_to_id: HashMap<&'static str, TypeId>, type_path_to_id: HashMap<&'static str, TypeId>, ambiguous_names: HashSet<&'static str>, } // TODO: remove this wrapper once we migrate to Atelier Assets and the Scene AssetLoader doesn't // need a TypeRegistry ref /// A synchronized wrapper around a [`TypeRegistry`]. #[derive(Clone, Default)] pub struct TypeRegistryArc { /// The wrapped [`TypeRegistry`]. pub internal: Arc<RwLock<TypeRegistry>>, } impl Debug for TypeRegistryArc { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.internal .read() .unwrap_or_else(PoisonError::into_inner) .type_path_to_id .keys() .fmt(f) } } /// A trait which allows a type to generate its [`TypeRegistration`] /// for registration into the [`TypeRegistry`]. /// /// This trait is automatically implemented for items using [`#[derive(Reflect)]`](derive@crate::Reflect). /// The macro also allows [`TypeData`] to be more easily registered. /// /// If you need to use this trait as a generic bound along with other reflection traits, /// for your convenience, consider using [`Reflectable`] instead. /// /// See the [crate-level documentation] for more information on type registration. /// /// [`Reflectable`]: crate::Reflectable /// [crate-level documentation]: crate #[diagnostic::on_unimplemented( message = "`{Self}` does not implement `GetTypeRegistration` so cannot provide type registration information", note = "consider annotating `{Self}` with `#[derive(Reflect)]`" )] pub trait GetTypeRegistration: 'static { /// Returns the default [`TypeRegistration`] for this type. fn get_type_registration() -> TypeRegistration; /// Registers other types needed by this type. /// /// This method is called by [`TypeRegistry::register`] to register any other required types. /// Often, this is done for fields of structs and enum variants to ensure all types are properly registered. fn register_type_dependencies(_registry: &mut TypeRegistry) {} } impl Default for TypeRegistry { fn default() -> Self { Self::new() } } impl TypeRegistry { /// Create a type registry with *no* registered types. pub fn empty() -> Self { Self { registrations: Default::default(), short_path_to_id: Default::default(), type_path_to_id: Default::default(), ambiguous_names: Default::default(), } } /// Create a type registry with default registrations for primitive types. pub fn new() -> Self { let mut registry = Self::empty(); registry.register::<()>(); registry.register::<bool>(); registry.register::<char>(); registry.register::<u8>(); registry.register::<u16>(); registry.register::<u32>(); registry.register::<u64>(); registry.register::<u128>(); registry.register::<usize>(); registry.register::<i8>(); registry.register::<i16>(); registry.register::<i32>(); registry.register::<i64>(); registry.register::<i128>(); registry.register::<isize>(); registry.register::<f32>(); registry.register::<f64>(); registry.register::<String>(); registry } /// Register all non-generic types annotated with `#[derive(Reflect)]`. /// /// Calling this method is equivalent to calling [`register`](Self::register) on all types without generic parameters /// that derived [`Reflect`] trait. /// /// This method is supported on Linux, macOS, Windows, iOS, Android, and Web via the `inventory` crate. /// It does nothing on platforms not supported by either of those crates. /// /// # Example /// /// ``` /// # use std::any::TypeId; /// # use bevy_reflect::{Reflect, TypeRegistry, std_traits::ReflectDefault}; /// #[derive(Reflect, Default)] /// #[reflect(Default)] /// struct Foo { /// name: Option<String>, /// value: i32 /// } /// /// let mut type_registry = TypeRegistry::empty(); /// type_registry.register_derived_types(); /// /// // The main type /// assert!(type_registry.contains(TypeId::of::<Foo>())); /// /// // Its type dependencies /// assert!(type_registry.contains(TypeId::of::<Option<String>>())); /// assert!(type_registry.contains(TypeId::of::<i32>())); /// /// // Its type data /// assert!(type_registry.get_type_data::<ReflectDefault>(TypeId::of::<Foo>()).is_some()); /// ``` #[cfg(feature = "auto_register")] pub fn register_derived_types(&mut self) { crate::__macro_exports::auto_register::register_types(self); } /// Attempts to register the type `T` if it has not yet been registered already. /// /// This will also recursively register any type dependencies as specified by [`GetTypeRegistration::register_type_dependencies`]. /// When deriving `Reflect`, this will generally be all the fields of the struct or enum variant. /// As with any type registration, these type dependencies will not be registered more than once. /// /// If the registration for type `T` already exists, it will not be registered again and neither will its type dependencies. /// To register the type, overwriting any existing registration, use [register](Self::overwrite_registration) instead. /// /// Additionally, this will add any reflect [type data](TypeData) as specified in the [`Reflect`] derive. /// /// # Example /// /// ``` /// # use core::any::TypeId; /// # use bevy_reflect::{Reflect, TypeRegistry, std_traits::ReflectDefault}; /// #[derive(Reflect, Default)] /// #[reflect(Default)] /// struct Foo { /// name: Option<String>, /// value: i32 /// } /// /// let mut type_registry = TypeRegistry::default(); /// /// type_registry.register::<Foo>(); /// /// // The main type /// assert!(type_registry.contains(TypeId::of::<Foo>())); /// /// // Its type dependencies /// assert!(type_registry.contains(TypeId::of::<Option<String>>())); /// assert!(type_registry.contains(TypeId::of::<i32>())); /// /// // Its type data /// assert!(type_registry.get_type_data::<ReflectDefault>(TypeId::of::<Foo>()).is_some()); /// ``` pub fn register<T>(&mut self) where T: GetTypeRegistration, { if self.register_internal(TypeId::of::<T>(), T::get_type_registration) { T::register_type_dependencies(self); } } /// Attempts to register the referenced type `T` if it has not yet been registered. /// /// See [`register`] for more details. /// /// # Example /// /// ``` /// # use bevy_reflect::{Reflect, TypeRegistry}; /// # use core::any::TypeId; /// # /// # let mut type_registry = TypeRegistry::default(); /// # /// #[derive(Reflect)] /// struct Foo { /// bar: Bar, /// } /// /// #[derive(Reflect)] /// struct Bar; /// /// let foo = Foo { bar: Bar }; /// /// // Equivalent to `type_registry.register::<Foo>()` /// type_registry.register_by_val(&foo); /// /// assert!(type_registry.contains(TypeId::of::<Foo>())); /// assert!(type_registry.contains(TypeId::of::<Bar>())); /// ``` /// /// [`register`]: Self::register pub fn register_by_val<T>(&mut self, _: &T) where T: GetTypeRegistration, { self.register::<T>(); } /// Attempts to register the type described by `registration`. /// /// If the registration for the type already exists, it will not be registered again. /// /// To forcibly register the type, overwriting any existing registration, use the /// [`overwrite_registration`](Self::overwrite_registration) method instead. /// /// This method will _not_ register type dependencies. /// Use [`register`](Self::register) to register a type with its dependencies. /// /// Returns `true` if the registration was added and `false` if it already exists. pub fn add_registration(&mut self, registration: TypeRegistration) -> bool { let type_id = registration.type_id(); self.register_internal(type_id, || registration) } /// Registers the type described by `registration`. /// /// If the registration for the type already exists, it will be overwritten. /// /// To avoid overwriting existing registrations, it's recommended to use the /// [`register`](Self::register) or [`add_registration`](Self::add_registration) methods instead. /// /// This method will _not_ register type dependencies. /// Use [`register`](Self::register) to register a type with its dependencies. pub fn overwrite_registration(&mut self, registration: TypeRegistration) { Self::update_registration_indices( &registration, &mut self.short_path_to_id, &mut self.type_path_to_id, &mut self.ambiguous_names, ); self.registrations .insert(registration.type_id(), registration); } /// Internal method to register a type with a given [`TypeId`] and [`TypeRegistration`]. /// /// By using this method, we are able to reduce the number of `TypeId` hashes and lookups needed /// to register a type. /// /// This method is internal to prevent users from accidentally registering a type with a `TypeId` /// that does not match the type in the `TypeRegistration`. fn register_internal( &mut self, type_id: TypeId, get_registration: impl FnOnce() -> TypeRegistration, ) -> bool { use bevy_platform::collections::hash_map::Entry; match self.registrations.entry(type_id) { Entry::Occupied(_) => false, Entry::Vacant(entry) => { let registration = get_registration(); Self::update_registration_indices( &registration, &mut self.short_path_to_id, &mut self.type_path_to_id, &mut self.ambiguous_names, ); entry.insert(registration); true } } } /// Internal method to register additional lookups for a given [`TypeRegistration`]. fn update_registration_indices( registration: &TypeRegistration, short_path_to_id: &mut HashMap<&'static str, TypeId>, type_path_to_id: &mut HashMap<&'static str, TypeId>, ambiguous_names: &mut HashSet<&'static str>, ) { let short_name = registration.type_info().type_path_table().short_path(); if short_path_to_id.contains_key(short_name) || ambiguous_names.contains(short_name) { // name is ambiguous. fall back to long names for all ambiguous types short_path_to_id.remove(short_name); ambiguous_names.insert(short_name); } else { short_path_to_id.insert(short_name, registration.type_id()); } type_path_to_id.insert(registration.type_info().type_path(), registration.type_id()); } /// Registers the type data `D` for type `T`. /// /// Most of the time [`TypeRegistry::register`] can be used instead to register a type you derived [`Reflect`] for. /// However, in cases where you want to add a piece of type data that was not included in the list of `#[reflect(...)]` type data in the derive, /// or where the type is generic and cannot register e.g. [`ReflectSerialize`] unconditionally without knowing the specific type parameters, /// this method can be used to insert additional type data. /// /// # Example /// ``` /// use bevy_reflect::{TypeRegistry, ReflectSerialize, ReflectDeserialize}; /// /// let mut type_registry = TypeRegistry::default(); /// type_registry.register::<Option<String>>(); /// type_registry.register_type_data::<Option<String>, ReflectSerialize>(); /// type_registry.register_type_data::<Option<String>, ReflectDeserialize>(); /// ``` pub fn register_type_data<T: Reflect + TypePath, D: TypeData + FromType<T>>(&mut self) { let data = self.get_mut(TypeId::of::<T>()).unwrap_or_else(|| { panic!( "attempted to call `TypeRegistry::register_type_data` for type `{T}` with data `{D}` without registering `{T}` first", T = T::type_path(), D = core::any::type_name::<D>(), ) }); data.insert(D::from_type()); } /// Whether the type with given [`TypeId`] has been registered in this registry. pub fn contains(&self, type_id: TypeId) -> bool { self.registrations.contains_key(&type_id) } /// Returns a reference to the [`TypeRegistration`] of the type with the /// given [`TypeId`]. /// /// If the specified type has not been registered, returns `None`. #[inline] pub fn get(&self, type_id: TypeId) -> Option<&TypeRegistration> { self.registrations.get(&type_id) } /// Returns a mutable reference to the [`TypeRegistration`] of the type with /// the given [`TypeId`]. /// /// If the specified type has not been registered, returns `None`. pub fn get_mut(&mut self, type_id: TypeId) -> Option<&mut TypeRegistration> { self.registrations.get_mut(&type_id) } /// Returns a reference to the [`TypeRegistration`] of the type with the /// given [type path]. /// /// If no type with the given path has been registered, returns `None`. /// /// [type path]: TypePath::type_path pub fn get_with_type_path(&self, type_path: &str) -> Option<&TypeRegistration> { self.type_path_to_id .get(type_path) .and_then(|id| self.get(*id)) } /// Returns a mutable reference to the [`TypeRegistration`] of the type with /// the given [type path]. /// /// If no type with the given type path has been registered, returns `None`. /// /// [type path]: TypePath::type_path pub fn get_with_type_path_mut(&mut self, type_path: &str) -> Option<&mut TypeRegistration> { self.type_path_to_id .get(type_path) .cloned() .and_then(move |id| self.get_mut(id)) } /// Returns a reference to the [`TypeRegistration`] of the type with /// the given [short type path]. /// /// If the short type path is ambiguous, or if no type with the given path /// has been registered, returns `None`. /// /// [short type path]: TypePath::short_type_path pub fn get_with_short_type_path(&self, short_type_path: &str) -> Option<&TypeRegistration> { self.short_path_to_id .get(short_type_path) .and_then(|id| self.registrations.get(id)) } /// Returns a mutable reference to the [`TypeRegistration`] of the type with /// the given [short type path]. /// /// If the short type path is ambiguous, or if no type with the given path /// has been registered, returns `None`. /// /// [short type path]: TypePath::short_type_path pub fn get_with_short_type_path_mut( &mut self, short_type_path: &str, ) -> Option<&mut TypeRegistration> { self.short_path_to_id .get(short_type_path) .and_then(|id| self.registrations.get_mut(id)) } /// Returns `true` if the given [short type path] is ambiguous, that is, it matches multiple registered types. /// /// # Example /// ``` /// # use bevy_reflect::TypeRegistry; /// # mod foo { /// # use bevy_reflect::Reflect; /// # #[derive(Reflect)] /// # pub struct MyType; /// # } /// # mod bar { /// # use bevy_reflect::Reflect; /// # #[derive(Reflect)] /// # pub struct MyType; /// # } /// let mut type_registry = TypeRegistry::default(); /// type_registry.register::<foo::MyType>(); /// type_registry.register::<bar::MyType>(); /// assert_eq!(type_registry.is_ambiguous("MyType"), true); /// ``` /// /// [short type path]: TypePath::short_type_path pub fn is_ambiguous(&self, short_type_path: &str) -> bool { self.ambiguous_names.contains(short_type_path) } /// Returns a reference to the [`TypeData`] of type `T` associated with the given [`TypeId`]. /// /// The returned value may be used to downcast [`Reflect`] trait objects to /// trait objects of the trait used to generate `T`, provided that the /// underlying reflected type has the proper `#[reflect(DoThing)]` /// attribute. /// /// If the specified type has not been registered, or if `T` is not present /// in its type registration, returns `None`. pub fn get_type_data<T: TypeData>(&self, type_id: TypeId) -> Option<&T> { self.get(type_id) .and_then(|registration| registration.data::<T>()) } /// Returns a mutable reference to the [`TypeData`] of type `T` associated with the given [`TypeId`]. /// /// If the specified type has not been registered, or if `T` is not present /// in its type registration, returns `None`. pub fn get_type_data_mut<T: TypeData>(&mut self, type_id: TypeId) -> Option<&mut T> { self.get_mut(type_id) .and_then(|registration| registration.data_mut::<T>()) } /// Returns the [`TypeInfo`] associated with the given [`TypeId`]. /// /// If the specified type has not been registered, returns `None`. pub fn get_type_info(&self, type_id: TypeId) -> Option<&'static TypeInfo> { self.get(type_id).map(TypeRegistration::type_info) } /// Returns an iterator over the [`TypeRegistration`]s of the registered /// types. pub fn iter(&self) -> impl Iterator<Item = &TypeRegistration> { self.registrations.values() } /// Returns a mutable iterator over the [`TypeRegistration`]s of the registered /// types. pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut TypeRegistration> { self.registrations.values_mut() } /// Checks to see if the [`TypeData`] of type `T` is associated with each registered type, /// returning a ([`TypeRegistration`], [`TypeData`]) iterator for all entries where data of that type was found. pub fn iter_with_data<T: TypeData>(&self) -> impl Iterator<Item = (&TypeRegistration, &T)> { self.registrations.values().filter_map(|item| { let type_data = item.data::<T>(); type_data.map(|data| (item, data)) }) } } impl TypeRegistryArc { /// Takes a read lock on the underlying [`TypeRegistry`]. pub fn read(&self) -> RwLockReadGuard<'_, TypeRegistry> { self.internal.read().unwrap_or_else(PoisonError::into_inner) } /// Takes a write lock on the underlying [`TypeRegistry`]. pub fn write(&self) -> RwLockWriteGuard<'_, TypeRegistry> { self.internal .write() .unwrap_or_else(PoisonError::into_inner) } } /// Runtime storage for type metadata, registered into the [`TypeRegistry`]. /// /// An instance of `TypeRegistration` can be created using the [`TypeRegistration::of`] method, /// but is more often automatically generated using [`#[derive(Reflect)]`](derive@crate::Reflect) which itself generates /// an implementation of the [`GetTypeRegistration`] trait. /// /// Along with the type's [`TypeInfo`], /// this struct also contains a type's registered [`TypeData`]. /// /// See the [crate-level documentation] for more information on type registration. /// /// # Example /// /// ``` /// # use bevy_reflect::{TypeRegistration, std_traits::ReflectDefault, FromType}; /// let mut registration = TypeRegistration::of::<Option<String>>(); /// /// assert_eq!("core::option::Option<alloc::string::String>", registration.type_info().type_path()); /// assert_eq!("Option<String>", registration.type_info().type_path_table().short_path()); /// /// registration.insert::<ReflectDefault>(FromType::<Option<String>>::from_type()); /// assert!(registration.data::<ReflectDefault>().is_some()) /// ``` /// /// [crate-level documentation]: crate pub struct TypeRegistration { data: TypeIdMap<Box<dyn TypeData>>, type_info: &'static TypeInfo, } impl Debug for TypeRegistration { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("TypeRegistration") .field("type_info", &self.type_info) .finish() } } impl TypeRegistration { /// Creates type registration information for `T`. pub fn of<T: Reflect + Typed + TypePath>() -> Self { Self { data: Default::default(), type_info: T::type_info(), } } /// Returns the [`TypeId`] of the type. #[inline] pub fn type_id(&self) -> TypeId { self.type_info.type_id() } /// Returns a reference to the registration's [`TypeInfo`] pub fn type_info(&self) -> &'static TypeInfo { self.type_info } /// Inserts an instance of `T` into this registration's [type data]. /// /// If another instance of `T` was previously inserted, it is replaced. /// /// [type data]: TypeData pub fn insert<T: TypeData>(&mut self, data: T) { self.data.insert(TypeId::of::<T>(), Box::new(data)); } /// Inserts the [`TypeData`] instance of `T` created for `V`, and inserts any /// [`TypeData`] dependencies for that combination of `T` and `V`. #[inline] pub fn register_type_data<T: TypeData + FromType<V>, V>(&mut self) { self.insert(T::from_type()); T::insert_dependencies(self); } /// Returns a reference to the value of type `T` in this registration's /// [type data]. /// /// Returns `None` if no such value exists. /// /// For a dynamic version of this method, see [`data_by_id`]. /// /// [type data]: TypeData /// [`data_by_id`]: Self::data_by_id pub fn data<T: TypeData>(&self) -> Option<&T> { self.data .get(&TypeId::of::<T>()) .and_then(|value| value.downcast_ref()) } /// Returns a reference to the value with the given [`TypeId`] in this registration's /// [type data]. /// /// Returns `None` if no such value exists. /// /// For a static version of this method, see [`data`]. /// /// [type data]: TypeData /// [`data`]: Self::data pub fn data_by_id(&self, type_id: TypeId) -> Option<&dyn TypeData> { self.data.get(&type_id).map(Deref::deref) } /// Returns a mutable reference to the value of type `T` in this registration's /// [type data]. /// /// Returns `None` if no such value exists. /// /// For a dynamic version of this method, see [`data_mut_by_id`]. /// /// [type data]: TypeData /// [`data_mut_by_id`]: Self::data_mut_by_id pub fn data_mut<T: TypeData>(&mut self) -> Option<&mut T> { self.data .get_mut(&TypeId::of::<T>()) .and_then(|value| value.downcast_mut()) } /// Returns a mutable reference to the value with the given [`TypeId`] in this registration's /// [type data]. /// /// Returns `None` if no such value exists. /// /// For a static version of this method, see [`data_mut`]. /// /// [type data]: TypeData /// [`data_mut`]: Self::data_mut pub fn data_mut_by_id(&mut self, type_id: TypeId) -> Option<&mut dyn TypeData> { self.data.get_mut(&type_id).map(DerefMut::deref_mut) } /// Returns true if this registration contains the given [type data]. /// /// For a dynamic version of this method, see [`contains_by_id`]. /// /// [type data]: TypeData /// [`contains_by_id`]: Self::contains_by_id pub fn contains<T: TypeData>(&self) -> bool { self.data.contains_key(&TypeId::of::<T>()) } /// Returns true if this registration contains the given [type data] with [`TypeId`]. /// /// For a static version of this method, see [`contains`]. /// /// [type data]: TypeData /// [`contains`]: Self::contains pub fn contains_by_id(&self, type_id: TypeId) -> bool { self.data.contains_key(&type_id) } /// The total count of [type data] in this registration. /// /// [type data]: TypeData pub fn len(&self) -> usize { self.data.len() } /// Returns true if this registration has no [type data]. /// /// [type data]: TypeData pub fn is_empty(&self) -> bool { self.data.is_empty() } /// Returns an iterator over all [type data] in this registration. /// /// The iterator yields a tuple of the [`TypeId`] and its corresponding type data. /// /// [type data]: TypeData pub fn iter(&self) -> impl ExactSizeIterator<Item = (TypeId, &dyn TypeData)> { self.data.iter().map(|(id, data)| (*id, data.deref())) } /// Returns a mutable iterator over all [type data] in this registration. /// /// The iterator yields a tuple of the [`TypeId`] and its corresponding type data. /// /// [type data]: TypeData pub fn iter_mut(&mut self) -> impl ExactSizeIterator<Item = (TypeId, &mut dyn TypeData)> { self.data .iter_mut() .map(|(id, data)| (*id, data.deref_mut())) } } impl Clone for TypeRegistration { fn clone(&self) -> Self { let mut data = TypeIdMap::default(); for (id, type_data) in &self.data { data.insert(*id, (*type_data).clone_type_data()); } TypeRegistration { data, type_info: self.type_info, } } } /// A trait used to type-erase type metadata. /// /// Type data can be registered to the [`TypeRegistry`] and stored on a type's [`TypeRegistration`]. /// /// While type data is often generated using the [`#[reflect_trait]`](crate::reflect_trait) macro, /// almost any type that implements [`Clone`] can be considered "type data". /// This is because it has a blanket implementation over all `T` where `T: Clone + Send + Sync + 'static`. /// /// See the [crate-level documentation] for more information on type data and type registration. /// /// [crate-level documentation]: crate pub trait TypeData: Downcast + Send + Sync { /// Creates a type-erased clone of this value. fn clone_type_data(&self) -> Box<dyn TypeData>; } impl_downcast!(TypeData); impl<T: 'static + Send + Sync> TypeData for T where T: Clone, { fn clone_type_data(&self) -> Box<dyn TypeData> { Box::new(self.clone()) } } /// Trait used to generate [`TypeData`] for trait reflection. /// /// This is used by the `#[derive(Reflect)]` macro to generate an implementation /// of [`TypeData`] to pass to [`TypeRegistration::insert`]. pub trait FromType<T> { /// Creates an instance of `Self` for type `T`. fn from_type() -> Self; /// Inserts [`TypeData`] dependencies of this [`TypeData`]. /// This is especially useful for trait [`TypeData`] that has a supertrait (ex: `A: B`). /// When the [`TypeData`] for `A` is inserted, the `B` [`TypeData`] will also be inserted. fn insert_dependencies(_type_registration: &mut TypeRegistration) {} } /// A struct used to serialize reflected instances of a type. /// /// A `ReflectSerialize` for type `T` can be obtained via /// [`FromType::from_type`]. #[derive(Clone)] pub struct ReflectSerialize { get_serializable: fn(value: &dyn Reflect) -> Serializable, } impl<T: TypePath + FromReflect + erased_serde::Serialize> FromType<T> for ReflectSerialize { fn from_type() -> Self { ReflectSerialize { get_serializable: |value| { value .downcast_ref::<T>() .map(|value| Serializable::Borrowed(value)) .or_else(|| T::from_reflect(value.as_partial_reflect()).map(|value| Serializable::Owned(Box::new(value)))) .unwrap_or_else(|| { panic!( "FromReflect::from_reflect failed when called on type `{}` with this value: {value:?}", T::type_path(), ); }) }, } } } impl ReflectSerialize { /// Turn the value into a serializable representation pub fn get_serializable<'a>(&self, value: &'a dyn Reflect) -> Serializable<'a> { (self.get_serializable)(value) } /// Serializes a reflected value. pub fn serialize<S>(&self, value: &dyn Reflect, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { (self.get_serializable)(value).serialize(serializer) } } /// A struct used to deserialize reflected instances of a type. /// /// A `ReflectDeserialize` for type `T` can be obtained via /// [`FromType::from_type`]. #[derive(Clone)] pub struct ReflectDeserialize { /// Function used by [`ReflectDeserialize::deserialize`] to /// perform deserialization. pub func: fn( deserializer: &mut dyn erased_serde::Deserializer, ) -> Result<Box<dyn Reflect>, erased_serde::Error>, } impl ReflectDeserialize { /// Deserializes a reflected value. /// /// The underlying type of the reflected value, and thus the expected /// structure of the serialized data, is determined by the type used to /// construct this `ReflectDeserialize` value. pub fn deserialize<'de, D>(&self, deserializer: D) -> Result<Box<dyn Reflect>, D::Error> where D: serde::Deserializer<'de>, { let mut erased = <dyn erased_serde::Deserializer>::erase(deserializer); (self.func)(&mut erased) .map_err(<<D as serde::Deserializer<'de>>::Error as serde::de::Error>::custom) } } impl<T: for<'a> Deserialize<'a> + Reflect> FromType<T> for ReflectDeserialize { fn from_type() -> Self { ReflectDeserialize { func: |deserializer| Ok(Box::new(T::deserialize(deserializer)?)), } } } /// [`Reflect`] values are commonly used in situations where the actual types of values /// are not known at runtime. In such situations you might have access to a `*const ()` pointer /// that you know implements [`Reflect`], but have no way of turning it into a `&dyn Reflect`. /// /// This is where [`ReflectFromPtr`] comes in, when creating a [`ReflectFromPtr`] for a given type `T: Reflect`. /// Internally, this saves a concrete function `*const T -> const dyn Reflect` which lets you create a trait object of [`Reflect`] /// from a pointer. /// /// # Example /// ``` /// use bevy_reflect::{TypeRegistry, Reflect, ReflectFromPtr}; /// use bevy_ptr::Ptr; /// use core::ptr::NonNull; /// /// #[derive(Reflect)] /// struct Reflected(String); /// /// let mut type_registry = TypeRegistry::default(); /// type_registry.register::<Reflected>(); /// /// let mut value = Reflected("Hello world!".to_string()); /// let value = Ptr::from(&value); /// /// let reflect_data = type_registry.get(core::any::TypeId::of::<Reflected>()).unwrap(); /// let reflect_from_ptr = reflect_data.data::<ReflectFromPtr>().unwrap(); /// // SAFE: `value` is of type `Reflected`, which the `ReflectFromPtr` was created for /// let value = unsafe { reflect_from_ptr.as_reflect(value) }; /// /// assert_eq!(value.downcast_ref::<Reflected>().unwrap().0, "Hello world!"); /// ``` #[derive(Clone)] pub struct ReflectFromPtr { type_id: TypeId, from_ptr: unsafe fn(Ptr) -> &dyn Reflect,
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/fields.rs
crates/bevy_reflect/src/fields.rs
use crate::{ attributes::{impl_custom_attribute_methods, CustomAttributes}, type_info::impl_type_methods, MaybeTyped, PartialReflect, Type, TypeInfo, TypePath, }; use alloc::borrow::Cow; use bevy_platform::sync::Arc; use core::fmt::{Display, Formatter}; /// The named field of a reflected struct. #[derive(Clone, Debug)] pub struct NamedField { name: &'static str, type_info: fn() -> Option<&'static TypeInfo>, ty: Type, custom_attributes: Arc<CustomAttributes>, #[cfg(feature = "reflect_documentation")] docs: Option<&'static str>, } impl NamedField { /// Create a new [`NamedField`]. pub fn new<T: PartialReflect + MaybeTyped + TypePath>(name: &'static str) -> Self { Self { name, type_info: T::maybe_type_info, ty: Type::of::<T>(), custom_attributes: Arc::new(CustomAttributes::default()), #[cfg(feature = "reflect_documentation")] docs: None, } } /// Sets the docstring for this field. #[cfg(feature = "reflect_documentation")] pub fn with_docs(self, docs: Option<&'static str>) -> Self { Self { docs, ..self } } /// Sets the custom attributes for this field. pub fn with_custom_attributes(self, custom_attributes: CustomAttributes) -> Self { Self { custom_attributes: Arc::new(custom_attributes), ..self } } /// The name of the field. pub fn name(&self) -> &'static str { self.name } /// The [`TypeInfo`] of the field. /// /// /// Returns `None` if the field does not contain static type information, /// such as for dynamic types. pub fn type_info(&self) -> Option<&'static TypeInfo> { (self.type_info)() } impl_type_methods!(ty); /// The docstring of this field, if any. #[cfg(feature = "reflect_documentation")] pub fn docs(&self) -> Option<&'static str> { self.docs } impl_custom_attribute_methods!(self.custom_attributes, "field"); } /// The unnamed field of a reflected tuple or tuple struct. #[derive(Clone, Debug)] pub struct UnnamedField { index: usize, type_info: fn() -> Option<&'static TypeInfo>, ty: Type, custom_attributes: Arc<CustomAttributes>, #[cfg(feature = "reflect_documentation")] docs: Option<&'static str>, } impl UnnamedField { /// Create a new [`UnnamedField`]. pub fn new<T: PartialReflect + MaybeTyped + TypePath>(index: usize) -> Self { Self { index, type_info: T::maybe_type_info, ty: Type::of::<T>(), custom_attributes: Arc::new(CustomAttributes::default()), #[cfg(feature = "reflect_documentation")] docs: None, } } /// Sets the docstring for this field. #[cfg(feature = "reflect_documentation")] pub fn with_docs(self, docs: Option<&'static str>) -> Self { Self { docs, ..self } } /// Sets the custom attributes for this field. pub fn with_custom_attributes(self, custom_attributes: CustomAttributes) -> Self { Self { custom_attributes: Arc::new(custom_attributes), ..self } } /// Returns the index of the field. pub fn index(&self) -> usize { self.index } /// The [`TypeInfo`] of the field. /// /// /// Returns `None` if the field does not contain static type information, /// such as for dynamic types. pub fn type_info(&self) -> Option<&'static TypeInfo> { (self.type_info)() } impl_type_methods!(ty); /// The docstring of this field, if any. #[cfg(feature = "reflect_documentation")] pub fn docs(&self) -> Option<&'static str> { self.docs } impl_custom_attribute_methods!(self.custom_attributes, "field"); } /// A representation of a field's accessor. #[derive(Clone, Debug, PartialEq, Eq)] pub enum FieldId { /// Access a field by name. Named(Cow<'static, str>), /// Access a field by index. Unnamed(usize), } impl Display for FieldId { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { match self { Self::Named(name) => Display::fmt(name, f), Self::Unnamed(index) => Display::fmt(index, f), } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/kind.rs
crates/bevy_reflect/src/kind.rs
use alloc::boxed::Box; use thiserror::Error; #[cfg(feature = "functions")] use crate::func::Function; use crate::{Array, Enum, List, Map, PartialReflect, Set, Struct, Tuple, TupleStruct}; /// An enumeration of the "kinds" of a reflected type. /// /// Each kind corresponds to a specific reflection trait, /// such as [`Struct`] or [`List`], /// which itself corresponds to the kind or structure of a type. /// /// A [`ReflectKind`] is obtained via [`PartialReflect::reflect_kind`], /// or via [`ReflectRef::kind`],[`ReflectMut::kind`] or [`ReflectOwned::kind`]. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum ReflectKind { /// A [struct-like] type. /// /// [struct-like]: Struct Struct, /// A [tuple-struct-like] type. /// /// [tuple-struct-like]: TupleStruct TupleStruct, /// A [tuple-like] type. /// /// [tuple-like]: Tuple Tuple, /// A [list-like] type. /// /// [list-like]: List List, /// An [array-like] type. /// /// [array-like]: Array Array, /// A [map-like] type. /// /// [map-like]: Map Map, /// A [set-like] type. /// /// [set-like]: Set Set, /// An [enum-like] type. /// /// [enum-like]: Enum Enum, /// A [function-like] type. /// /// [function-like]: Function #[cfg(feature = "functions")] Function, /// An opaque type. /// /// This most often represents a type where it is either impossible, difficult, /// or unuseful to reflect the type further. /// /// This includes types like `String` and `Instant`. /// /// Despite not technically being opaque types, /// primitives like `u32` `i32` are considered opaque for the purposes of reflection. /// /// Additionally, any type that [derives `Reflect`] with the `#[reflect(opaque)]` attribute /// will be considered an opaque type. /// /// [derives `Reflect`]: bevy_reflect_derive::Reflect Opaque, } impl core::fmt::Display for ReflectKind { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { ReflectKind::Struct => f.pad("struct"), ReflectKind::TupleStruct => f.pad("tuple struct"), ReflectKind::Tuple => f.pad("tuple"), ReflectKind::List => f.pad("list"), ReflectKind::Array => f.pad("array"), ReflectKind::Map => f.pad("map"), ReflectKind::Set => f.pad("set"), ReflectKind::Enum => f.pad("enum"), #[cfg(feature = "functions")] ReflectKind::Function => f.pad("function"), ReflectKind::Opaque => f.pad("opaque"), } } } macro_rules! impl_reflect_kind_conversions { ($name:ident$(<$lifetime:lifetime>)?) => { impl $name$(<$lifetime>)? { /// Returns the "kind" of this reflected type without any information. pub fn kind(&self) -> ReflectKind { match self { Self::Struct(_) => ReflectKind::Struct, Self::TupleStruct(_) => ReflectKind::TupleStruct, Self::Tuple(_) => ReflectKind::Tuple, Self::List(_) => ReflectKind::List, Self::Array(_) => ReflectKind::Array, Self::Map(_) => ReflectKind::Map, Self::Set(_) => ReflectKind::Set, Self::Enum(_) => ReflectKind::Enum, #[cfg(feature = "functions")] Self::Function(_) => ReflectKind::Function, Self::Opaque(_) => ReflectKind::Opaque, } } } impl From<$name$(<$lifetime>)?> for ReflectKind { fn from(value: $name) -> Self { match value { $name::Struct(_) => Self::Struct, $name::TupleStruct(_) => Self::TupleStruct, $name::Tuple(_) => Self::Tuple, $name::List(_) => Self::List, $name::Array(_) => Self::Array, $name::Map(_) => Self::Map, $name::Set(_) => Self::Set, $name::Enum(_) => Self::Enum, #[cfg(feature = "functions")] $name::Function(_) => Self::Function, $name::Opaque(_) => Self::Opaque, } } } }; } /// Caused when a type was expected to be of a certain [kind], but was not. /// /// [kind]: ReflectKind #[derive(Debug, Error)] #[error("kind mismatch: expected {expected:?}, received {received:?}")] pub struct ReflectKindMismatchError { /// Expected kind. pub expected: ReflectKind, /// Received kind. pub received: ReflectKind, } macro_rules! impl_cast_method { ($name:ident : Opaque => $retval:ty) => { #[doc = "Attempts a cast to a [`PartialReflect`] trait object."] #[doc = "\n\nReturns an error if `self` is not the [`Self::Opaque`] variant."] pub fn $name(self) -> Result<$retval, ReflectKindMismatchError> { match self { Self::Opaque(value) => Ok(value), _ => Err(ReflectKindMismatchError { expected: ReflectKind::Opaque, received: self.kind(), }), } } }; ($name:ident : $kind:ident => $retval:ty) => { #[doc = concat!("Attempts a cast to a [`", stringify!($kind), "`] trait object.")] #[doc = concat!("\n\nReturns an error if `self` is not the [`Self::", stringify!($kind), "`] variant.")] pub fn $name(self) -> Result<$retval, ReflectKindMismatchError> { match self { Self::$kind(value) => Ok(value), _ => Err(ReflectKindMismatchError { expected: ReflectKind::$kind, received: self.kind(), }), } } }; } /// An immutable enumeration of ["kinds"] of a reflected type. /// /// Each variant contains a trait object with methods specific to a kind of /// type. /// /// A [`ReflectRef`] is obtained via [`PartialReflect::reflect_ref`]. /// /// ["kinds"]: ReflectKind pub enum ReflectRef<'a> { /// An immutable reference to a [struct-like] type. /// /// [struct-like]: Struct Struct(&'a dyn Struct), /// An immutable reference to a [tuple-struct-like] type. /// /// [tuple-struct-like]: TupleStruct TupleStruct(&'a dyn TupleStruct), /// An immutable reference to a [tuple-like] type. /// /// [tuple-like]: Tuple Tuple(&'a dyn Tuple), /// An immutable reference to a [list-like] type. /// /// [list-like]: List List(&'a dyn List), /// An immutable reference to an [array-like] type. /// /// [array-like]: Array Array(&'a dyn Array), /// An immutable reference to a [map-like] type. /// /// [map-like]: Map Map(&'a dyn Map), /// An immutable reference to a [set-like] type. /// /// [set-like]: Set Set(&'a dyn Set), /// An immutable reference to an [enum-like] type. /// /// [enum-like]: Enum Enum(&'a dyn Enum), /// An immutable reference to a [function-like] type. /// /// [function-like]: Function #[cfg(feature = "functions")] Function(&'a dyn Function), /// An immutable reference to an [opaque] type. /// /// [opaque]: ReflectKind::Opaque Opaque(&'a dyn PartialReflect), } impl_reflect_kind_conversions!(ReflectRef<'_>); impl<'a> ReflectRef<'a> { impl_cast_method!(as_struct: Struct => &'a dyn Struct); impl_cast_method!(as_tuple_struct: TupleStruct => &'a dyn TupleStruct); impl_cast_method!(as_tuple: Tuple => &'a dyn Tuple); impl_cast_method!(as_list: List => &'a dyn List); impl_cast_method!(as_array: Array => &'a dyn Array); impl_cast_method!(as_map: Map => &'a dyn Map); impl_cast_method!(as_set: Set => &'a dyn Set); impl_cast_method!(as_enum: Enum => &'a dyn Enum); impl_cast_method!(as_opaque: Opaque => &'a dyn PartialReflect); } /// A mutable enumeration of ["kinds"] of a reflected type. /// /// Each variant contains a trait object with methods specific to a kind of /// type. /// /// A [`ReflectMut`] is obtained via [`PartialReflect::reflect_mut`]. /// /// ["kinds"]: ReflectKind pub enum ReflectMut<'a> { /// A mutable reference to a [struct-like] type. /// /// [struct-like]: Struct Struct(&'a mut dyn Struct), /// A mutable reference to a [tuple-struct-like] type. /// /// [tuple-struct-like]: TupleStruct TupleStruct(&'a mut dyn TupleStruct), /// A mutable reference to a [tuple-like] type. /// /// [tuple-like]: Tuple Tuple(&'a mut dyn Tuple), /// A mutable reference to a [list-like] type. /// /// [list-like]: List List(&'a mut dyn List), /// A mutable reference to an [array-like] type. /// /// [array-like]: Array Array(&'a mut dyn Array), /// A mutable reference to a [map-like] type. /// /// [map-like]: Map Map(&'a mut dyn Map), /// A mutable reference to a [set-like] type. /// /// [set-like]: Set Set(&'a mut dyn Set), /// A mutable reference to an [enum-like] type. /// /// [enum-like]: Enum Enum(&'a mut dyn Enum), #[cfg(feature = "functions")] /// A mutable reference to a [function-like] type. /// /// [function-like]: Function Function(&'a mut dyn Function), /// A mutable reference to an [opaque] type. /// /// [opaque]: ReflectKind::Opaque Opaque(&'a mut dyn PartialReflect), } impl_reflect_kind_conversions!(ReflectMut<'_>); impl<'a> ReflectMut<'a> { impl_cast_method!(as_struct: Struct => &'a mut dyn Struct); impl_cast_method!(as_tuple_struct: TupleStruct => &'a mut dyn TupleStruct); impl_cast_method!(as_tuple: Tuple => &'a mut dyn Tuple); impl_cast_method!(as_list: List => &'a mut dyn List); impl_cast_method!(as_array: Array => &'a mut dyn Array); impl_cast_method!(as_map: Map => &'a mut dyn Map); impl_cast_method!(as_set: Set => &'a mut dyn Set); impl_cast_method!(as_enum: Enum => &'a mut dyn Enum); impl_cast_method!(as_opaque: Opaque => &'a mut dyn PartialReflect); } /// An owned enumeration of ["kinds"] of a reflected type. /// /// Each variant contains a trait object with methods specific to a kind of /// type. /// /// A [`ReflectOwned`] is obtained via [`PartialReflect::reflect_owned`]. /// /// ["kinds"]: ReflectKind pub enum ReflectOwned { /// An owned [struct-like] type. /// /// [struct-like]: Struct Struct(Box<dyn Struct>), /// An owned [tuple-struct-like] type. /// /// [tuple-struct-like]: TupleStruct TupleStruct(Box<dyn TupleStruct>), /// An owned [tuple-like] type. /// /// [tuple-like]: Tuple Tuple(Box<dyn Tuple>), /// An owned [list-like] type. /// /// [list-like]: List List(Box<dyn List>), /// An owned [array-like] type. /// /// [array-like]: Array Array(Box<dyn Array>), /// An owned [map-like] type. /// /// [map-like]: Map Map(Box<dyn Map>), /// An owned [set-like] type. /// /// [set-like]: Set Set(Box<dyn Set>), /// An owned [enum-like] type. /// /// [enum-like]: Enum Enum(Box<dyn Enum>), /// An owned [function-like] type. /// /// [function-like]: Function #[cfg(feature = "functions")] Function(Box<dyn Function>), /// An owned [opaque] type. /// /// [opaque]: ReflectKind::Opaque Opaque(Box<dyn PartialReflect>), } impl_reflect_kind_conversions!(ReflectOwned); impl ReflectOwned { impl_cast_method!(into_struct: Struct => Box<dyn Struct>); impl_cast_method!(into_tuple_struct: TupleStruct => Box<dyn TupleStruct>); impl_cast_method!(into_tuple: Tuple => Box<dyn Tuple>); impl_cast_method!(into_list: List => Box<dyn List>); impl_cast_method!(into_array: Array => Box<dyn Array>); impl_cast_method!(into_map: Map => Box<dyn Map>); impl_cast_method!(into_set: Set => Box<dyn Set>); impl_cast_method!(into_enum: Enum => Box<dyn Enum>); impl_cast_method!(into_value: Opaque => Box<dyn PartialReflect>); } #[cfg(test)] mod tests { use alloc::vec; use std::collections::HashSet; use super::*; #[test] fn should_cast_ref() { let value = vec![1, 2, 3]; let result = value.reflect_ref().as_list(); assert!(result.is_ok()); let result = value.reflect_ref().as_array(); assert!(matches!( result, Err(ReflectKindMismatchError { expected: ReflectKind::Array, received: ReflectKind::List }) )); } #[test] fn should_cast_mut() { let mut value: HashSet<i32> = HashSet::default(); let result = value.reflect_mut().as_set(); assert!(result.is_ok()); let result = value.reflect_mut().as_map(); assert!(matches!( result, Err(ReflectKindMismatchError { expected: ReflectKind::Map, received: ReflectKind::Set }) )); } #[test] fn should_cast_owned() { let value = Box::new(Some(123)); let result = value.reflect_owned().into_enum(); assert!(result.is_ok()); let value = Box::new(Some(123)); let result = value.reflect_owned().into_struct(); assert!(matches!( result, Err(ReflectKindMismatchError { expected: ReflectKind::Struct, received: ReflectKind::Enum }) )); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/error.rs
crates/bevy_reflect/src/error.rs
use crate::FieldId; use alloc::{borrow::Cow, format}; use thiserror::Error; /// An error that occurs when cloning a type via [`PartialReflect::reflect_clone`]. /// /// [`PartialReflect::reflect_clone`]: crate::PartialReflect::reflect_clone #[derive(Clone, Debug, Error, PartialEq, Eq)] pub enum ReflectCloneError { /// The type does not have a custom implementation for [`PartialReflect::reflect_clone`]. /// /// [`PartialReflect::reflect_clone`]: crate::PartialReflect::reflect_clone #[error("`PartialReflect::reflect_clone` not implemented for `{type_path}`")] NotImplemented { /// The fully qualified path of the type that [`PartialReflect::reflect_clone`](crate::PartialReflect::reflect_clone) is not implemented for. type_path: Cow<'static, str>, }, /// The type cannot be cloned via [`PartialReflect::reflect_clone`]. /// /// This type should be returned when a type is intentionally opting out of reflection cloning. /// /// [`PartialReflect::reflect_clone`]: crate::PartialReflect::reflect_clone #[error("`{type_path}` cannot be made cloneable for `PartialReflect::reflect_clone`")] NotCloneable { /// The fully qualified path of the type that cannot be cloned via [`PartialReflect::reflect_clone`](crate::PartialReflect::reflect_clone). type_path: Cow<'static, str>, }, /// The field cannot be cloned via [`PartialReflect::reflect_clone`]. /// /// When [deriving `Reflect`], this usually means that a field marked with `#[reflect(ignore)]` /// is missing a `#[reflect(clone)]` attribute. /// /// This may be intentional if the field is not meant/able to be cloned. /// /// [`PartialReflect::reflect_clone`]: crate::PartialReflect::reflect_clone /// [deriving `Reflect`]: derive@crate::Reflect #[error( "field `{}` cannot be made cloneable for `PartialReflect::reflect_clone` (are you missing a `#[reflect(clone)]` attribute?)", full_path(.field, .variant.as_deref(), .container_type_path) )] FieldNotCloneable { /// Struct field or enum variant field which cannot be cloned. field: FieldId, /// Variant this field is part of if the container is an enum, otherwise [`None`]. variant: Option<Cow<'static, str>>, /// Fully qualified path of the type containing this field. container_type_path: Cow<'static, str>, }, /// Could not downcast to the expected type. /// /// Realistically this should only occur when a type has incorrectly implemented [`Reflect`]. /// /// [`Reflect`]: crate::Reflect #[error("expected downcast to `{expected}`, but received `{received}`")] FailedDowncast { /// The fully qualified path of the type that was expected. expected: Cow<'static, str>, /// The fully qualified path of the type that was received. received: Cow<'static, str>, }, } fn full_path( field: &FieldId, variant: Option<&str>, container_type_path: &str, ) -> alloc::string::String { match variant { Some(variant) => format!("{container_type_path}::{variant}::{field}"), None => format!("{container_type_path}::{field}"), } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/tuple_struct.rs
crates/bevy_reflect/src/tuple_struct.rs
use bevy_reflect_derive::impl_type_path; use crate::generics::impl_generic_info_methods; use crate::{ attributes::{impl_custom_attribute_methods, CustomAttributes}, type_info::impl_type_methods, ApplyError, DynamicTuple, Generics, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Tuple, Type, TypeInfo, TypePath, UnnamedField, }; use alloc::{boxed::Box, vec::Vec}; use bevy_platform::sync::Arc; use core::{ fmt::{Debug, Formatter}, slice::Iter, }; /// A trait used to power [tuple struct-like] operations via [reflection]. /// /// This trait uses the [`Reflect`] trait to allow implementors to have their fields /// be dynamically addressed by index. /// /// When using [`#[derive(Reflect)]`](derive@crate::Reflect) on a tuple struct, /// this trait will be automatically implemented. /// /// # Example /// /// ``` /// use bevy_reflect::{PartialReflect, Reflect, TupleStruct}; /// /// #[derive(Reflect)] /// struct Foo(u32); /// /// let foo = Foo(123); /// /// assert_eq!(foo.field_len(), 1); /// /// let field: &dyn PartialReflect = foo.field(0).unwrap(); /// assert_eq!(field.try_downcast_ref::<u32>(), Some(&123)); /// ``` /// /// [tuple struct-like]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html#using-tuple-structs-without-named-fields-to-create-different-types /// [reflection]: crate pub trait TupleStruct: PartialReflect { /// Returns a reference to the value of the field with index `index` as a /// `&dyn Reflect`. fn field(&self, index: usize) -> Option<&dyn PartialReflect>; /// Returns a mutable reference to the value of the field with index `index` /// as a `&mut dyn Reflect`. fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>; /// Returns the number of fields in the tuple struct. fn field_len(&self) -> usize; /// Returns an iterator over the values of the tuple struct's fields. fn iter_fields(&self) -> TupleStructFieldIter<'_>; /// Creates a new [`DynamicTupleStruct`] from this tuple struct. fn to_dynamic_tuple_struct(&self) -> DynamicTupleStruct { DynamicTupleStruct { represented_type: self.get_represented_type_info(), fields: self.iter_fields().map(PartialReflect::to_dynamic).collect(), } } /// Will return `None` if [`TypeInfo`] is not available. fn get_represented_tuple_struct_info(&self) -> Option<&'static TupleStructInfo> { self.get_represented_type_info()?.as_tuple_struct().ok() } } /// A container for compile-time tuple struct info. #[derive(Clone, Debug)] pub struct TupleStructInfo { ty: Type, generics: Generics, fields: Box<[UnnamedField]>, custom_attributes: Arc<CustomAttributes>, #[cfg(feature = "reflect_documentation")] docs: Option<&'static str>, } impl TupleStructInfo { /// Create a new [`TupleStructInfo`]. /// /// # Arguments /// /// * `fields`: The fields of this struct in the order they are defined pub fn new<T: Reflect + TypePath>(fields: &[UnnamedField]) -> Self { Self { ty: Type::of::<T>(), generics: Generics::new(), fields: fields.to_vec().into_boxed_slice(), custom_attributes: Arc::new(CustomAttributes::default()), #[cfg(feature = "reflect_documentation")] docs: None, } } /// Sets the docstring for this struct. #[cfg(feature = "reflect_documentation")] pub fn with_docs(self, docs: Option<&'static str>) -> Self { Self { docs, ..self } } /// Sets the custom attributes for this struct. pub fn with_custom_attributes(self, custom_attributes: CustomAttributes) -> Self { Self { custom_attributes: Arc::new(custom_attributes), ..self } } /// Get the field at the given index. pub fn field_at(&self, index: usize) -> Option<&UnnamedField> { self.fields.get(index) } /// Iterate over the fields of this struct. pub fn iter(&self) -> Iter<'_, UnnamedField> { self.fields.iter() } /// The total number of fields in this struct. pub fn field_len(&self) -> usize { self.fields.len() } impl_type_methods!(ty); /// The docstring of this struct, if any. #[cfg(feature = "reflect_documentation")] pub fn docs(&self) -> Option<&'static str> { self.docs } impl_custom_attribute_methods!(self.custom_attributes, "struct"); impl_generic_info_methods!(generics); } /// An iterator over the field values of a tuple struct. pub struct TupleStructFieldIter<'a> { pub(crate) tuple_struct: &'a dyn TupleStruct, pub(crate) index: usize, } impl<'a> TupleStructFieldIter<'a> { /// Creates a new [`TupleStructFieldIter`]. pub fn new(value: &'a dyn TupleStruct) -> Self { TupleStructFieldIter { tuple_struct: value, index: 0, } } } impl<'a> Iterator for TupleStructFieldIter<'a> { type Item = &'a dyn PartialReflect; fn next(&mut self) -> Option<Self::Item> { let value = self.tuple_struct.field(self.index); self.index += value.is_some() as usize; value } fn size_hint(&self) -> (usize, Option<usize>) { let size = self.tuple_struct.field_len(); (size, Some(size)) } } impl<'a> ExactSizeIterator for TupleStructFieldIter<'a> {} /// A convenience trait which combines fetching and downcasting of tuple /// struct fields. /// /// # Example /// /// ``` /// use bevy_reflect::{GetTupleStructField, Reflect}; /// /// #[derive(Reflect)] /// struct Foo(String); /// /// # fn main() { /// let mut foo = Foo("Hello, world!".to_string()); /// /// foo.get_field_mut::<String>(0).unwrap().truncate(5); /// assert_eq!(foo.get_field::<String>(0), Some(&"Hello".to_string())); /// # } /// ``` pub trait GetTupleStructField { /// Returns a reference to the value of the field with index `index`, /// downcast to `T`. fn get_field<T: Reflect>(&self, index: usize) -> Option<&T>; /// Returns a mutable reference to the value of the field with index /// `index`, downcast to `T`. fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T>; } impl<S: TupleStruct> GetTupleStructField for S { fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> { self.field(index) .and_then(|value| value.try_downcast_ref::<T>()) } fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> { self.field_mut(index) .and_then(|value| value.try_downcast_mut::<T>()) } } impl GetTupleStructField for dyn TupleStruct { fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> { self.field(index) .and_then(|value| value.try_downcast_ref::<T>()) } fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> { self.field_mut(index) .and_then(|value| value.try_downcast_mut::<T>()) } } /// A tuple struct which allows fields to be added at runtime. #[derive(Default)] pub struct DynamicTupleStruct { represented_type: Option<&'static TypeInfo>, fields: Vec<Box<dyn PartialReflect>>, } impl DynamicTupleStruct { /// Sets the [type] to be represented by this `DynamicTupleStruct`. /// /// # Panics /// /// Panics if the given [type] is not a [`TypeInfo::TupleStruct`]. /// /// [type]: TypeInfo pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) { if let Some(represented_type) = represented_type { assert!( matches!(represented_type, TypeInfo::TupleStruct(_)), "expected TypeInfo::TupleStruct but received: {represented_type:?}" ); } self.represented_type = represented_type; } /// Appends an element with value `value` to the tuple struct. pub fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) { self.fields.push(value); } /// Appends a typed element with value `value` to the tuple struct. pub fn insert<T: PartialReflect>(&mut self, value: T) { self.insert_boxed(Box::new(value)); } } impl TupleStruct for DynamicTupleStruct { #[inline] fn field(&self, index: usize) -> Option<&dyn PartialReflect> { self.fields.get(index).map(|field| &**field) } #[inline] fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> { self.fields.get_mut(index).map(|field| &mut **field) } #[inline] fn field_len(&self) -> usize { self.fields.len() } #[inline] fn iter_fields(&self) -> TupleStructFieldIter<'_> { TupleStructFieldIter { tuple_struct: self, index: 0, } } } impl PartialReflect for DynamicTupleStruct { #[inline] fn get_represented_type_info(&self) -> Option<&'static TypeInfo> { self.represented_type } #[inline] fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> { self } #[inline] fn as_partial_reflect(&self) -> &dyn PartialReflect { self } #[inline] fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect { self } fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> { Err(self) } fn try_as_reflect(&self) -> Option<&dyn Reflect> { None } fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { None } fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { let tuple_struct = value.reflect_ref().as_tuple_struct()?; for (i, value) in tuple_struct.iter_fields().enumerate() { if let Some(v) = self.field_mut(i) { v.try_apply(value)?; } } Ok(()) } #[inline] fn reflect_kind(&self) -> ReflectKind { ReflectKind::TupleStruct } #[inline] fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::TupleStruct(self) } #[inline] fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::TupleStruct(self) } #[inline] fn reflect_owned(self: Box<Self>) -> ReflectOwned { ReflectOwned::TupleStruct(self) } #[inline] fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> { tuple_struct_partial_eq(self, value) } fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicTupleStruct(")?; tuple_struct_debug(self, f)?; write!(f, ")") } #[inline] fn is_dynamic(&self) -> bool { true } } impl_type_path!((in bevy_reflect) DynamicTupleStruct); impl Debug for DynamicTupleStruct { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.debug(f) } } impl From<DynamicTuple> for DynamicTupleStruct { fn from(value: DynamicTuple) -> Self { Self { represented_type: None, fields: Box::new(value).drain(), } } } impl FromIterator<Box<dyn PartialReflect>> for DynamicTupleStruct { fn from_iter<I: IntoIterator<Item = Box<dyn PartialReflect>>>(fields: I) -> Self { Self { represented_type: None, fields: fields.into_iter().collect(), } } } impl IntoIterator for DynamicTupleStruct { type Item = Box<dyn PartialReflect>; type IntoIter = alloc::vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.fields.into_iter() } } impl<'a> IntoIterator for &'a DynamicTupleStruct { type Item = &'a dyn PartialReflect; type IntoIter = TupleStructFieldIter<'a>; fn into_iter(self) -> Self::IntoIter { self.iter_fields() } } /// Compares a [`TupleStruct`] with a [`PartialReflect`] value. /// /// Returns true if and only if all of the following are true: /// - `b` is a tuple struct; /// - `b` has the same number of fields as `a`; /// - [`PartialReflect::reflect_partial_eq`] returns `Some(true)` for pairwise fields of `a` and `b`. /// /// Returns [`None`] if the comparison couldn't even be performed. #[inline] pub fn tuple_struct_partial_eq<S: TupleStruct + ?Sized>( a: &S, b: &dyn PartialReflect, ) -> Option<bool> { let ReflectRef::TupleStruct(tuple_struct) = b.reflect_ref() else { return Some(false); }; if a.field_len() != tuple_struct.field_len() { return Some(false); } for (i, value) in tuple_struct.iter_fields().enumerate() { if let Some(field_value) = a.field(i) { let eq_result = field_value.reflect_partial_eq(value); if let failed @ (Some(false) | None) = eq_result { return failed; } } else { return Some(false); } } Some(true) } /// The default debug formatter for [`TupleStruct`] types. /// /// # Example /// ``` /// use bevy_reflect::Reflect; /// #[derive(Reflect)] /// struct MyTupleStruct(usize); /// /// let my_tuple_struct: &dyn Reflect = &MyTupleStruct(123); /// println!("{:#?}", my_tuple_struct); /// /// // Output: /// /// // MyTupleStruct ( /// // 123, /// // ) /// ``` #[inline] pub fn tuple_struct_debug( dyn_tuple_struct: &dyn TupleStruct, f: &mut Formatter<'_>, ) -> core::fmt::Result { let mut debug = f.debug_tuple( dyn_tuple_struct .get_represented_type_info() .map(TypeInfo::type_path) .unwrap_or("_"), ); for field in dyn_tuple_struct.iter_fields() { debug.field(&field as &dyn Debug); } debug.finish() } #[cfg(test)] mod tests { use crate::*; #[derive(Reflect)] struct Ts(u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8); #[test] fn next_index_increment() { let mut iter = Ts(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11).iter_fields(); let size = iter.len(); iter.index = size - 1; let prev_index = iter.index; assert!(iter.next().is_some()); assert_eq!(prev_index, iter.index - 1); // When None we should no longer increase index assert!(iter.next().is_none()); assert_eq!(size, iter.index); assert!(iter.next().is_none()); assert_eq!(size, iter.index); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/type_info.rs
crates/bevy_reflect/src/type_info.rs
use crate::{ ArrayInfo, DynamicArray, DynamicEnum, DynamicList, DynamicMap, DynamicStruct, DynamicTuple, DynamicTupleStruct, EnumInfo, Generics, ListInfo, MapInfo, PartialReflect, Reflect, ReflectKind, SetInfo, StructInfo, TupleInfo, TupleStructInfo, TypePath, TypePathTable, }; use core::{ any::{Any, TypeId}, fmt::{Debug, Formatter}, hash::Hash, }; use thiserror::Error; /// A static accessor to compile-time type information. /// /// This trait is automatically implemented by the [`#[derive(Reflect)]`](derive@crate::Reflect) macro /// and allows type information to be processed without an instance of that type. /// /// If you need to use this trait as a generic bound along with other reflection traits, /// for your convenience, consider using [`Reflectable`] instead. /// /// # Implementing /// /// While it is recommended to leave implementing this trait to the `#[derive(Reflect)]` macro, /// it is possible to implement this trait manually. If a manual implementation is needed, /// you _must_ ensure that the information you provide is correct, otherwise various systems that /// rely on this trait may fail in unexpected ways. /// /// Implementors may have difficulty in generating a reference to [`TypeInfo`] with a static /// lifetime. Luckily, this crate comes with some [utility] structs, to make generating these /// statics much simpler. /// /// # Example /// /// ``` /// # use core::any::Any; /// # use bevy_reflect::{DynamicTypePath, NamedField, PartialReflect, Reflect, ReflectMut, ReflectOwned, ReflectRef, StructInfo, TypeInfo, TypePath, OpaqueInfo, ApplyError}; /// # use bevy_reflect::utility::NonGenericTypeInfoCell; /// use bevy_reflect::Typed; /// /// struct MyStruct { /// foo: usize, /// bar: (f32, f32) /// } /// /// impl Typed for MyStruct { /// fn type_info() -> &'static TypeInfo { /// static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new(); /// CELL.get_or_set(|| { /// let fields = [ /// NamedField::new::<usize >("foo"), /// NamedField::new::<(f32, f32) >("bar"), /// ]; /// let info = StructInfo::new::<Self>(&fields); /// TypeInfo::Struct(info) /// }) /// } /// } /// /// # impl TypePath for MyStruct { /// # fn type_path() -> &'static str { todo!() } /// # fn short_type_path() -> &'static str { todo!() } /// # } /// # impl PartialReflect for MyStruct { /// # fn get_represented_type_info(&self) -> Option<&'static TypeInfo> { todo!() } /// # fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> { todo!() } /// # fn as_partial_reflect(&self) -> &dyn PartialReflect { todo!() } /// # fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect { todo!() } /// # fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> { todo!() } /// # fn try_as_reflect(&self) -> Option<&dyn Reflect> { todo!() } /// # fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { todo!() } /// # fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { todo!() } /// # fn reflect_ref(&self) -> ReflectRef<'_> { todo!() } /// # fn reflect_mut(&mut self) -> ReflectMut<'_> { todo!() } /// # fn reflect_owned(self: Box<Self>) -> ReflectOwned { todo!() } /// # } /// # impl Reflect for MyStruct { /// # fn into_any(self: Box<Self>) -> Box<dyn Any> { todo!() } /// # fn as_any(&self) -> &dyn Any { todo!() } /// # fn as_any_mut(&mut self) -> &mut dyn Any { todo!() } /// # fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> { todo!() } /// # fn as_reflect(&self) -> &dyn Reflect { todo!() } /// # fn as_reflect_mut(&mut self) -> &mut dyn Reflect { todo!() } /// # fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> { todo!() } /// # } /// ``` /// /// [`Reflectable`]: crate::Reflectable /// [utility]: crate::utility #[diagnostic::on_unimplemented( message = "`{Self}` does not implement `Typed` so cannot provide static type information", note = "consider annotating `{Self}` with `#[derive(Reflect)]`" )] pub trait Typed: Reflect + TypePath { /// Returns the compile-time [info] for the underlying type. /// /// [info]: TypeInfo fn type_info() -> &'static TypeInfo; } /// A wrapper trait around [`Typed`]. /// /// This trait is used to provide a way to get compile-time type information for types that /// do implement `Typed` while also allowing for types that do not implement `Typed` to be used. /// It's used instead of `Typed` directly to avoid making dynamic types also /// implement `Typed` in order to be used as active fields. /// /// This trait has a blanket implementation for all types that implement `Typed` /// and manual implementations for all dynamic types (which simply return `None`). #[doc(hidden)] #[diagnostic::on_unimplemented( message = "`{Self}` does not implement `Typed` so cannot provide static type information", note = "consider annotating `{Self}` with `#[derive(Reflect)]`" )] pub trait MaybeTyped: PartialReflect { /// Returns the compile-time [info] for the underlying type, if it exists. /// /// [info]: TypeInfo fn maybe_type_info() -> Option<&'static TypeInfo> { None } } impl<T: Typed> MaybeTyped for T { fn maybe_type_info() -> Option<&'static TypeInfo> { Some(T::type_info()) } } impl MaybeTyped for DynamicEnum {} impl MaybeTyped for DynamicTupleStruct {} impl MaybeTyped for DynamicStruct {} impl MaybeTyped for DynamicMap {} impl MaybeTyped for DynamicList {} impl MaybeTyped for DynamicArray {} impl MaybeTyped for DynamicTuple {} /// Dynamic dispatch for [`Typed`]. /// /// Since this is a supertrait of [`Reflect`] its methods can be called on a `dyn Reflect`. /// /// [`Reflect`]: crate::Reflect #[diagnostic::on_unimplemented( message = "`{Self}` can not provide dynamic type information through reflection", note = "consider annotating `{Self}` with `#[derive(Reflect)]`" )] pub trait DynamicTyped { /// See [`Typed::type_info`]. fn reflect_type_info(&self) -> &'static TypeInfo; } impl<T: Typed> DynamicTyped for T { #[inline] fn reflect_type_info(&self) -> &'static TypeInfo { Self::type_info() } } /// A [`TypeInfo`]-specific error. #[derive(Debug, Error)] pub enum TypeInfoError { /// Caused when a type was expected to be of a certain [kind], but was not. /// /// [kind]: ReflectKind #[error("kind mismatch: expected {expected:?}, received {received:?}")] KindMismatch { /// Expected kind. expected: ReflectKind, /// Received kind. received: ReflectKind, }, } /// Compile-time type information for various reflected types. /// /// Generally, for any given type, this value can be retrieved in one of four ways: /// /// 1. [`Typed::type_info`] /// 2. [`DynamicTyped::reflect_type_info`] /// 3. [`PartialReflect::get_represented_type_info`] /// 4. [`TypeRegistry::get_type_info`] /// /// Each returns a static reference to [`TypeInfo`], but they all have their own use cases. /// For example, if you know the type at compile time, [`Typed::type_info`] is probably /// the simplest. If you have a `dyn Reflect` you can use [`DynamicTyped::reflect_type_info`]. /// If all you have is a `dyn PartialReflect`, you'll probably want [`PartialReflect::get_represented_type_info`]. /// Lastly, if all you have is a [`TypeId`] or [type path], you will need to go through /// [`TypeRegistry::get_type_info`]. /// /// You may also opt to use [`TypeRegistry::get_type_info`] in place of the other methods simply because /// it can be more performant. This is because those other methods may require attaining a lock on /// the static [`TypeInfo`], while the registry simply checks a map. /// /// [`TypeRegistry::get_type_info`]: crate::TypeRegistry::get_type_info /// [`PartialReflect::get_represented_type_info`]: crate::PartialReflect::get_represented_type_info /// [type path]: TypePath::type_path #[derive(Debug, Clone)] pub enum TypeInfo { /// Type information for a [struct-like] type. /// /// [struct-like]: crate::Struct Struct(StructInfo), /// Type information for a [tuple-struct-like] type. /// /// [tuple-struct-like]: crate::TupleStruct TupleStruct(TupleStructInfo), /// Type information for a [tuple-like] type. /// /// [tuple-like]: crate::Tuple Tuple(TupleInfo), /// Type information for a [list-like] type. /// /// [list-like]: crate::List List(ListInfo), /// Type information for an [array-like] type. /// /// [array-like]: crate::Array Array(ArrayInfo), /// Type information for a [map-like] type. /// /// [map-like]: crate::Map Map(MapInfo), /// Type information for a [set-like] type. /// /// [set-like]: crate::Set Set(SetInfo), /// Type information for an [enum-like] type. /// /// [enum-like]: crate::Enum Enum(EnumInfo), /// Type information for an opaque type - see the [`OpaqueInfo`] docs for /// a discussion of opaque types. Opaque(OpaqueInfo), } impl TypeInfo { /// The underlying Rust [type]. /// /// [type]: Type pub fn ty(&self) -> &Type { match self { Self::Struct(info) => info.ty(), Self::TupleStruct(info) => info.ty(), Self::Tuple(info) => info.ty(), Self::List(info) => info.ty(), Self::Array(info) => info.ty(), Self::Map(info) => info.ty(), Self::Set(info) => info.ty(), Self::Enum(info) => info.ty(), Self::Opaque(info) => info.ty(), } } /// The [`TypeId`] of the underlying type. #[inline] pub fn type_id(&self) -> TypeId { self.ty().id() } /// A representation of the type path of the underlying type. /// /// Provides dynamic access to all methods on [`TypePath`]. pub fn type_path_table(&self) -> &TypePathTable { self.ty().type_path_table() } /// The [stable, full type path] of the underlying type. /// /// Use [`type_path_table`] if you need access to the other methods on [`TypePath`]. /// /// [stable, full type path]: TypePath /// [`type_path_table`]: Self::type_path_table pub fn type_path(&self) -> &'static str { self.ty().path() } /// Check if the given type matches this one. /// /// This only compares the [`TypeId`] of the types /// and does not verify they share the same [`TypePath`] /// (though it implies they do). pub fn is<T: Any>(&self) -> bool { self.ty().is::<T>() } /// The docstring of the underlying type, if any. #[cfg(feature = "reflect_documentation")] pub fn docs(&self) -> Option<&str> { match self { Self::Struct(info) => info.docs(), Self::TupleStruct(info) => info.docs(), Self::Tuple(info) => info.docs(), Self::List(info) => info.docs(), Self::Array(info) => info.docs(), Self::Map(info) => info.docs(), Self::Set(info) => info.docs(), Self::Enum(info) => info.docs(), Self::Opaque(info) => info.docs(), } } /// Returns the [kind] of this `TypeInfo`. /// /// [kind]: ReflectKind pub fn kind(&self) -> ReflectKind { match self { Self::Struct(_) => ReflectKind::Struct, Self::TupleStruct(_) => ReflectKind::TupleStruct, Self::Tuple(_) => ReflectKind::Tuple, Self::List(_) => ReflectKind::List, Self::Array(_) => ReflectKind::Array, Self::Map(_) => ReflectKind::Map, Self::Set(_) => ReflectKind::Set, Self::Enum(_) => ReflectKind::Enum, Self::Opaque(_) => ReflectKind::Opaque, } } impl_generic_info_methods!(self => { match self { Self::Struct(info) => info.generics(), Self::TupleStruct(info) => info.generics(), Self::Tuple(info) => info.generics(), Self::List(info) => info.generics(), Self::Array(info) => info.generics(), Self::Map(info) => info.generics(), Self::Set(info) => info.generics(), Self::Enum(info) => info.generics(), Self::Opaque(info) => info.generics(), } }); } macro_rules! impl_cast_method { ($name:ident : $kind:ident => $info:ident) => { #[doc = concat!("Attempts a cast to [`", stringify!($info), "`].")] #[doc = concat!("\n\nReturns an error if `self` is not [`TypeInfo::", stringify!($kind), "`].")] pub fn $name(&self) -> Result<&$info, TypeInfoError> { match self { Self::$kind(info) => Ok(info), _ => Err(TypeInfoError::KindMismatch { expected: ReflectKind::$kind, received: self.kind(), }), } } }; } /// Conversion convenience methods for [`TypeInfo`]. impl TypeInfo { impl_cast_method!(as_struct: Struct => StructInfo); impl_cast_method!(as_tuple_struct: TupleStruct => TupleStructInfo); impl_cast_method!(as_tuple: Tuple => TupleInfo); impl_cast_method!(as_list: List => ListInfo); impl_cast_method!(as_array: Array => ArrayInfo); impl_cast_method!(as_map: Map => MapInfo); impl_cast_method!(as_enum: Enum => EnumInfo); impl_cast_method!(as_opaque: Opaque => OpaqueInfo); } /// The base representation of a Rust type. /// /// When possible, it is recommended to use [`&'static TypeInfo`] instead of this /// as it provides more information as well as being smaller /// (since a reference only takes the same number of bytes as a `usize`). /// /// However, where a static reference to [`TypeInfo`] is not possible, /// such as with trait objects and other types that can't implement [`Typed`], /// this type can be used instead. /// /// It only requires that the type implements [`TypePath`]. /// /// And unlike [`TypeInfo`], this type implements [`Copy`], [`Eq`], and [`Hash`], /// making it useful as a key type. /// /// It's especially helpful when compared to [`TypeId`] as it can provide the /// actual [type path] when debugging, while still having the same performance /// as hashing/comparing [`TypeId`] directly—at the cost of a little more memory. /// /// # Examples /// /// ``` /// use bevy_reflect::{Type, TypePath}; /// /// fn assert_char<T: ?Sized + TypePath>(t: &T) -> Result<(), String> { /// let ty = Type::of::<T>(); /// if Type::of::<char>() == ty { /// Ok(()) /// } else { /// Err(format!("expected `char`, got `{}`", ty.path())) /// } /// } /// /// assert_eq!( /// assert_char(&'a'), /// Ok(()) /// ); /// assert_eq!( /// assert_char(&String::from("Hello, world!")), /// Err(String::from("expected `char`, got `alloc::string::String`")) /// ); /// ``` /// /// [`&'static TypeInfo`]: TypeInfo #[derive(Copy, Clone)] pub struct Type { type_path_table: TypePathTable, type_id: TypeId, } impl Type { /// Create a new [`Type`] from a type that implements [`TypePath`]. pub fn of<T: TypePath + ?Sized>() -> Self { Self { type_path_table: TypePathTable::of::<T>(), type_id: TypeId::of::<T>(), } } /// Returns the [`TypeId`] of the type. #[inline] pub fn id(&self) -> TypeId { self.type_id } /// See [`TypePath::type_path`]. pub fn path(&self) -> &'static str { self.type_path_table.path() } /// See [`TypePath::short_type_path`]. pub fn short_path(&self) -> &'static str { self.type_path_table.short_path() } /// See [`TypePath::type_ident`]. pub fn ident(&self) -> Option<&'static str> { self.type_path_table.ident() } /// See [`TypePath::crate_name`]. pub fn crate_name(&self) -> Option<&'static str> { self.type_path_table.crate_name() } /// See [`TypePath::module_path`]. pub fn module_path(&self) -> Option<&'static str> { self.type_path_table.module_path() } /// A representation of the type path of this. /// /// Provides dynamic access to all methods on [`TypePath`]. pub fn type_path_table(&self) -> &TypePathTable { &self.type_path_table } /// Check if the given type matches this one. /// /// This only compares the [`TypeId`] of the types /// and does not verify they share the same [`TypePath`] /// (though it implies they do). pub fn is<T: Any>(&self) -> bool { TypeId::of::<T>() == self.type_id } } /// This implementation will only output the [type path] of the type. /// /// If you need to include the [`TypeId`] in the output, /// you can access it through [`Type::id`]. /// /// [type path]: TypePath impl Debug for Type { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.type_path_table.path()) } } impl Eq for Type {} /// This implementation purely relies on the [`TypeId`] of the type, /// and not on the [type path]. /// /// [type path]: TypePath impl PartialEq for Type { #[inline] fn eq(&self, other: &Self) -> bool { self.type_id == other.type_id } } /// This implementation purely relies on the [`TypeId`] of the type, /// and not on the [type path]. /// /// [type path]: TypePath impl Hash for Type { #[inline] fn hash<H: core::hash::Hasher>(&self, state: &mut H) { self.type_id.hash(state); } } macro_rules! impl_type_methods { // Generates the type methods based off a single field. ($field:ident) => { $crate::type_info::impl_type_methods!(self => { &self.$field }); }; // Generates the type methods based off a custom expression. ($self:ident => $expr:expr) => { /// The underlying Rust [type]. /// /// [type]: crate::type_info::Type pub fn ty(&$self) -> &$crate::type_info::Type { $expr } /// The [`TypeId`] of this type. /// /// [`TypeId`]: core::any::TypeId pub fn type_id(&self) -> ::core::any::TypeId { self.ty().id() } /// The [stable, full type path] of this type. /// /// Use [`type_path_table`] if you need access to the other methods on [`TypePath`]. /// /// [stable, full type path]: TypePath /// [`type_path_table`]: Self::type_path_table pub fn type_path(&self) -> &'static str { self.ty().path() } /// A representation of the type path of this type. /// /// Provides dynamic access to all methods on [`TypePath`]. /// /// [`TypePath`]: crate::type_path::TypePath pub fn type_path_table(&self) -> &$crate::type_path::TypePathTable { &self.ty().type_path_table() } /// Check if the given type matches this one. /// /// This only compares the [`TypeId`] of the types /// and does not verify they share the same [`TypePath`] /// (though it implies they do). /// /// [`TypeId`]: core::any::TypeId /// [`TypePath`]: crate::type_path::TypePath pub fn is<T: ::core::any::Any>(&self) -> bool { self.ty().is::<T>() } }; } use crate::generics::impl_generic_info_methods; pub(crate) use impl_type_methods; /// A container for compile-time info related to reflection-opaque types, including primitives. /// /// This typically represents a type which cannot be broken down any further. This is often /// due to technical reasons (or by definition), but it can also be a purposeful choice. /// /// For example, [`i32`] cannot be broken down any further, so it is represented by an [`OpaqueInfo`]. /// And while [`String`] itself is a struct, its fields are private, so we don't really treat /// it _as_ a struct. It therefore makes more sense to represent it as an [`OpaqueInfo`]. /// /// [`String`]: alloc::string::String #[derive(Debug, Clone)] pub struct OpaqueInfo { ty: Type, generics: Generics, #[cfg(feature = "reflect_documentation")] docs: Option<&'static str>, } impl OpaqueInfo { /// Creates a new [`OpaqueInfo`]. pub fn new<T: Reflect + TypePath + ?Sized>() -> Self { Self { ty: Type::of::<T>(), generics: Generics::new(), #[cfg(feature = "reflect_documentation")] docs: None, } } /// Sets the docstring for this type. #[cfg(feature = "reflect_documentation")] pub fn with_docs(self, doc: Option<&'static str>) -> Self { Self { docs: doc, ..self } } impl_type_methods!(ty); /// The docstring of this dynamic type, if any. #[cfg(feature = "reflect_documentation")] pub fn docs(&self) -> Option<&'static str> { self.docs } impl_generic_info_methods!(generics); } #[cfg(test)] mod tests { use super::*; use alloc::vec::Vec; #[test] fn should_return_error_on_invalid_cast() { let info = <Vec<i32> as Typed>::type_info(); assert!(matches!( info.as_struct(), Err(TypeInfoError::KindMismatch { expected: ReflectKind::Struct, received: ReflectKind::List }) )); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/generics.rs
crates/bevy_reflect/src/generics.rs
use crate::type_info::impl_type_methods; use crate::{Reflect, Type, TypePath}; use alloc::{borrow::Cow, boxed::Box}; use bevy_platform::sync::Arc; use core::ops::Deref; use derive_more::derive::From; /// The generic parameters of a type. /// /// This is automatically generated via the [`Reflect` derive macro] /// and stored on the [`TypeInfo`] returned by [`Typed::type_info`] /// for types that have generics. /// /// It supports both type parameters and const parameters /// so long as they implement [`TypePath`]. /// /// If the type has no generics, this will be empty. /// /// If the type is marked with `#[reflect(type_path = false)]`, /// the generics will be empty even if the type has generics. /// /// [`Reflect` derive macro]: bevy_reflect_derive::Reflect /// [`TypeInfo`]: crate::type_info::TypeInfo /// [`Typed::type_info`]: crate::Typed::type_info #[derive(Clone, Default, Debug)] pub struct Generics(Box<[GenericInfo]>); impl Generics { /// Creates an empty set of generics. pub fn new() -> Self { Self(Box::new([])) } /// Finds the generic parameter with the given name. /// /// Returns `None` if no such parameter exists. pub fn get_named(&self, name: &str) -> Option<&GenericInfo> { // For small sets of generics (the most common case), // a linear search is often faster using a `HashMap`. self.0.iter().find(|info| info.name() == name) } /// Adds the given generic parameter to the set. pub fn with(mut self, info: impl Into<GenericInfo>) -> Self { self.0 = IntoIterator::into_iter(self.0) .chain(core::iter::once(info.into())) .collect(); self } } impl<T: Into<GenericInfo>> FromIterator<T> for Generics { fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self { Self(iter.into_iter().map(Into::into).collect()) } } impl Deref for Generics { type Target = [GenericInfo]; fn deref(&self) -> &Self::Target { &self.0 } } /// An enum representing a generic parameter. #[derive(Clone, Debug, From)] pub enum GenericInfo { /// A type parameter. /// /// An example would be `T` in `struct Foo<T, U>`. Type(TypeParamInfo), /// A const parameter. /// /// An example would be `N` in `struct Foo<const N: usize>`. Const(ConstParamInfo), } impl GenericInfo { /// The name of the generic parameter. pub fn name(&self) -> &Cow<'static, str> { match self { Self::Type(info) => info.name(), Self::Const(info) => info.name(), } } /// Whether the generic parameter is a const parameter. pub fn is_const(&self) -> bool { match self { Self::Type(_) => false, Self::Const(_) => true, } } impl_type_methods!(self => { match self { Self::Type(info) => info.ty(), Self::Const(info) => info.ty(), } }); } /// Type information for a generic type parameter. /// /// An example of a type parameter would be `T` in `struct Foo<T>`. #[derive(Clone, Debug)] pub struct TypeParamInfo { name: Cow<'static, str>, ty: Type, default: Option<Type>, } impl TypeParamInfo { /// Creates a new type parameter with the given name. pub fn new<T: TypePath + ?Sized>(name: impl Into<Cow<'static, str>>) -> Self { Self { name: name.into(), ty: Type::of::<T>(), default: None, } } /// Sets the default type for the parameter. pub fn with_default<T: TypePath + ?Sized>(mut self) -> Self { self.default = Some(Type::of::<T>()); self } /// The name of the type parameter. pub fn name(&self) -> &Cow<'static, str> { &self.name } /// The default type for the parameter, if any. /// /// # Example /// /// ``` /// # use bevy_reflect::{GenericInfo, Reflect, Typed}; /// #[derive(Reflect)] /// struct Foo<T = f32>(T); /// /// let generics = Foo::<String>::type_info().generics(); /// let GenericInfo::Type(info) = generics.get_named("T").unwrap() else { /// panic!("expected a type parameter"); /// }; /// /// let default = info.default().unwrap(); /// /// assert!(default.is::<f32>()); /// ``` pub fn default(&self) -> Option<&Type> { self.default.as_ref() } impl_type_methods!(ty); } /// Type information for a const generic parameter. /// /// An example of a const parameter would be `N` in `struct Foo<const N: usize>`. #[derive(Clone, Debug)] pub struct ConstParamInfo { name: Cow<'static, str>, ty: Type, // Rust currently only allows certain primitive types in const generic position, // meaning that `Reflect` is guaranteed to be implemented for the default value. default: Option<Arc<dyn Reflect>>, } impl ConstParamInfo { /// Creates a new const parameter with the given name. pub fn new<T: TypePath + ?Sized>(name: impl Into<Cow<'static, str>>) -> Self { Self { name: name.into(), ty: Type::of::<T>(), default: None, } } /// Sets the default value for the parameter. pub fn with_default<T: Reflect + 'static>(mut self, default: T) -> Self { let arc = Arc::new(default); #[cfg(not(target_has_atomic = "ptr"))] #[expect( unsafe_code, reason = "unsized coercion is an unstable feature for non-std types" )] // SAFETY: // - Coercion from `T` to `dyn Reflect` is valid as `T: Reflect + 'static` // - `Arc::from_raw` receives a valid pointer from a previous call to `Arc::into_raw` let arc = unsafe { Arc::from_raw(Arc::into_raw(arc) as *const dyn Reflect) }; self.default = Some(arc); self } /// The name of the const parameter. pub fn name(&self) -> &Cow<'static, str> { &self.name } /// The default value for the parameter, if any. /// /// # Example /// /// ``` /// # use bevy_reflect::{GenericInfo, Reflect, Typed}; /// #[derive(Reflect)] /// struct Foo<const N: usize = 10>([u8; N]); /// /// let generics = Foo::<5>::type_info().generics(); /// let GenericInfo::Const(info) = generics.get_named("N").unwrap() else { /// panic!("expected a const parameter"); /// }; /// /// let default = info.default().unwrap(); /// /// assert_eq!(default.downcast_ref::<usize>().unwrap(), &10); /// ``` pub fn default(&self) -> Option<&dyn Reflect> { self.default.as_deref() } impl_type_methods!(ty); } macro_rules! impl_generic_info_methods { // Implements both getter and setter methods for the given field. ($field:ident) => { $crate::generics::impl_generic_info_methods!(self => &self.$field); /// Sets the generic parameters for this type. pub fn with_generics(mut self, generics: crate::generics::Generics) -> Self { self.$field = generics; self } }; // Implements only a getter method for the given expression. ($self:ident => $expr:expr) => { /// Gets the generic parameters for this type. pub fn generics(&$self) -> &crate::generics::Generics { $expr } }; } pub(crate) use impl_generic_info_methods; #[cfg(test)] mod tests { use super::*; use crate::{Reflect, Typed}; use alloc::string::String; use core::fmt::Debug; #[test] fn should_maintain_order() { #[derive(Reflect)] struct Test<T, U: Debug, const N: usize>([(T, U); N]); let generics = <Test<f32, String, 10> as Typed>::type_info() .as_tuple_struct() .unwrap() .generics(); assert_eq!(generics.len(), 3); let mut iter = generics.iter(); let t = iter.next().unwrap(); assert_eq!(t.name(), "T"); assert!(t.ty().is::<f32>()); assert!(!t.is_const()); let u = iter.next().unwrap(); assert_eq!(u.name(), "U"); assert!(u.ty().is::<String>()); assert!(!u.is_const()); let n = iter.next().unwrap(); assert_eq!(n.name(), "N"); assert!(n.ty().is::<usize>()); assert!(n.is_const()); assert!(iter.next().is_none()); } #[test] fn should_get_by_name() { #[derive(Reflect)] enum Test<T, U: Debug, const N: usize> { Array([(T, U); N]), } let generics = <Test<f32, String, 10> as Typed>::type_info() .as_enum() .unwrap() .generics(); let t = generics.get_named("T").unwrap(); assert_eq!(t.name(), "T"); assert!(t.ty().is::<f32>()); assert!(!t.is_const()); let u = generics.get_named("U").unwrap(); assert_eq!(u.name(), "U"); assert!(u.ty().is::<String>()); assert!(!u.is_const()); let n = generics.get_named("N").unwrap(); assert_eq!(n.name(), "N"); assert!(n.ty().is::<usize>()); assert!(n.is_const()); } #[test] fn should_store_defaults() { #[derive(Reflect)] struct Test<T, U: Debug = String, const N: usize = 10>([(T, U); N]); let generics = <Test<f32> as Typed>::type_info() .as_tuple_struct() .unwrap() .generics(); let GenericInfo::Type(u) = generics.get_named("U").unwrap() else { panic!("expected a type parameter"); }; assert_eq!(u.default().unwrap(), &Type::of::<String>()); let GenericInfo::Const(n) = generics.get_named("N").unwrap() else { panic!("expected a const parameter"); }; assert_eq!(n.default().unwrap().downcast_ref::<usize>().unwrap(), &10); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/map.rs
crates/bevy_reflect/src/map.rs
use core::fmt::{Debug, Formatter}; use bevy_platform::collections::HashTable; use bevy_reflect_derive::impl_type_path; use crate::{ generics::impl_generic_info_methods, type_info::impl_type_methods, ApplyError, Generics, MaybeTyped, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type, TypeInfo, TypePath, }; use alloc::{boxed::Box, format, vec::Vec}; /// A trait used to power [map-like] operations via [reflection]. /// /// Maps contain zero or more entries of a key and its associated value, /// and correspond to types like [`HashMap`] and [`BTreeMap`]. /// The order of these entries is not guaranteed by this trait. /// /// # Hashing and equality /// /// All keys are expected to return a valid hash value from [`PartialReflect::reflect_hash`] and be /// comparable using [`PartialReflect::reflect_partial_eq`]. /// If using the [`#[derive(Reflect)]`](derive@crate::Reflect) macro, this can be done by adding /// `#[reflect(Hash, PartialEq)]` to the entire struct or enum. /// The ordering is expected to be total, that is as if the reflected type implements the [`Eq`] trait. /// This is true even for manual implementors who do not hash or compare values, /// as it is still relied on by [`DynamicMap`]. /// /// # Example /// /// ``` /// use bevy_reflect::{PartialReflect, Reflect, Map}; /// use std::collections::HashMap; /// /// /// let foo: &mut dyn Map = &mut HashMap::<u32, bool>::new(); /// foo.insert_boxed(Box::new(123_u32), Box::new(true)); /// assert_eq!(foo.len(), 1); /// /// let field: &dyn PartialReflect = foo.get(&123_u32).unwrap(); /// assert_eq!(field.try_downcast_ref::<bool>(), Some(&true)); /// ``` /// /// [`HashMap`]: std::collections::HashMap /// [`BTreeMap`]: alloc::collections::BTreeMap /// [map-like]: https://doc.rust-lang.org/book/ch08-03-hash-maps.html /// [reflection]: crate pub trait Map: PartialReflect { /// Returns a reference to the value associated with the given key. /// /// If no value is associated with `key`, returns `None`. fn get(&self, key: &dyn PartialReflect) -> Option<&dyn PartialReflect>; /// Returns a mutable reference to the value associated with the given key. /// /// If no value is associated with `key`, returns `None`. fn get_mut(&mut self, key: &dyn PartialReflect) -> Option<&mut dyn PartialReflect>; /// Returns the number of elements in the map. fn len(&self) -> usize; /// Returns `true` if the list contains no elements. fn is_empty(&self) -> bool { self.len() == 0 } /// Returns an iterator over the key-value pairs of the map. fn iter(&self) -> Box<dyn Iterator<Item = (&dyn PartialReflect, &dyn PartialReflect)> + '_>; /// Drain the key-value pairs of this map to get a vector of owned values. /// /// After calling this function, `self` will be empty. fn drain(&mut self) -> Vec<(Box<dyn PartialReflect>, Box<dyn PartialReflect>)>; /// Retain only the elements specified by the predicate. /// /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`. fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect, &mut dyn PartialReflect) -> bool); /// Creates a new [`DynamicMap`] from this map. fn to_dynamic_map(&self) -> DynamicMap { let mut map = DynamicMap::default(); map.set_represented_type(self.get_represented_type_info()); for (key, value) in self.iter() { map.insert_boxed(key.to_dynamic(), value.to_dynamic()); } map } /// Inserts a key-value pair into the map. /// /// If the map did not have this key present, `None` is returned. /// If the map did have this key present, the value is updated, and the old value is returned. fn insert_boxed( &mut self, key: Box<dyn PartialReflect>, value: Box<dyn PartialReflect>, ) -> Option<Box<dyn PartialReflect>>; /// Removes an entry from the map. /// /// If the map did not have this key present, `None` is returned. /// If the map did have this key present, the removed value is returned. fn remove(&mut self, key: &dyn PartialReflect) -> Option<Box<dyn PartialReflect>>; /// Will return `None` if [`TypeInfo`] is not available. fn get_represented_map_info(&self) -> Option<&'static MapInfo> { self.get_represented_type_info()?.as_map().ok() } } /// A container for compile-time map info. #[derive(Clone, Debug)] pub struct MapInfo { ty: Type, generics: Generics, key_info: fn() -> Option<&'static TypeInfo>, key_ty: Type, value_info: fn() -> Option<&'static TypeInfo>, value_ty: Type, #[cfg(feature = "reflect_documentation")] docs: Option<&'static str>, } impl MapInfo { /// Create a new [`MapInfo`]. pub fn new< TMap: Map + TypePath, TKey: Reflect + MaybeTyped + TypePath, TValue: Reflect + MaybeTyped + TypePath, >() -> Self { Self { ty: Type::of::<TMap>(), generics: Generics::new(), key_info: TKey::maybe_type_info, key_ty: Type::of::<TKey>(), value_info: TValue::maybe_type_info, value_ty: Type::of::<TValue>(), #[cfg(feature = "reflect_documentation")] docs: None, } } /// Sets the docstring for this map. #[cfg(feature = "reflect_documentation")] pub fn with_docs(self, docs: Option<&'static str>) -> Self { Self { docs, ..self } } impl_type_methods!(ty); /// The [`TypeInfo`] of the key type. /// /// Returns `None` if the key type does not contain static type information, /// such as for dynamic types. pub fn key_info(&self) -> Option<&'static TypeInfo> { (self.key_info)() } /// The [type] of the key type. /// /// [type]: Type pub fn key_ty(&self) -> Type { self.key_ty } /// The [`TypeInfo`] of the value type. /// /// Returns `None` if the value type does not contain static type information, /// such as for dynamic types. pub fn value_info(&self) -> Option<&'static TypeInfo> { (self.value_info)() } /// The [type] of the value type. /// /// [type]: Type pub fn value_ty(&self) -> Type { self.value_ty } /// The docstring of this map, if any. #[cfg(feature = "reflect_documentation")] pub fn docs(&self) -> Option<&'static str> { self.docs } impl_generic_info_methods!(generics); } /// Used to produce an error message when an attempt is made to hash /// a [`PartialReflect`] value that does not support hashing. #[macro_export] macro_rules! hash_error { ( $key:expr ) => {{ let type_path = (*$key).reflect_type_path(); if !$key.is_dynamic() { format!( "the given key of type `{}` does not support hashing", type_path ) } else { match (*$key).get_represented_type_info() { // Handle dynamic types that do not represent a type (i.e a plain `DynamicStruct`): None => format!("the dynamic type `{}` does not support hashing", type_path), // Handle dynamic types that do represent a type (i.e. a `DynamicStruct` proxying `Foo`): Some(s) => format!( "the dynamic type `{}` (representing `{}`) does not support hashing", type_path, s.type_path() ), } } }} } /// An unordered mapping between reflected values. #[derive(Default)] pub struct DynamicMap { represented_type: Option<&'static TypeInfo>, hash_table: HashTable<(Box<dyn PartialReflect>, Box<dyn PartialReflect>)>, } impl DynamicMap { /// Sets the [type] to be represented by this `DynamicMap`. /// /// # Panics /// /// Panics if the given [type] is not a [`TypeInfo::Map`]. /// /// [type]: TypeInfo pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) { if let Some(represented_type) = represented_type { assert!( matches!(represented_type, TypeInfo::Map(_)), "expected TypeInfo::Map but received: {represented_type:?}" ); } self.represented_type = represented_type; } /// Inserts a typed key-value pair into the map. pub fn insert<K: PartialReflect, V: PartialReflect>(&mut self, key: K, value: V) { self.insert_boxed(Box::new(key), Box::new(value)); } fn internal_hash(value: &dyn PartialReflect) -> u64 { value.reflect_hash().expect(&hash_error!(value)) } fn internal_eq( key: &dyn PartialReflect, ) -> impl FnMut(&(Box<dyn PartialReflect>, Box<dyn PartialReflect>)) -> bool + '_ { |(other, _)| { key .reflect_partial_eq(&**other) .expect("underlying type does not reflect `PartialEq` and hence doesn't support equality checks") } } } impl Map for DynamicMap { fn get(&self, key: &dyn PartialReflect) -> Option<&dyn PartialReflect> { self.hash_table .find(Self::internal_hash(key), Self::internal_eq(key)) .map(|(_, value)| &**value) } fn get_mut(&mut self, key: &dyn PartialReflect) -> Option<&mut dyn PartialReflect> { self.hash_table .find_mut(Self::internal_hash(key), Self::internal_eq(key)) .map(|(_, value)| &mut **value) } fn len(&self) -> usize { self.hash_table.len() } fn iter(&self) -> Box<dyn Iterator<Item = (&dyn PartialReflect, &dyn PartialReflect)> + '_> { let iter = self.hash_table.iter().map(|(k, v)| (&**k, &**v)); Box::new(iter) } fn drain(&mut self) -> Vec<(Box<dyn PartialReflect>, Box<dyn PartialReflect>)> { self.hash_table.drain().collect() } fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect, &mut dyn PartialReflect) -> bool) { self.hash_table .retain(move |(key, value)| f(&**key, &mut **value)); } fn insert_boxed( &mut self, key: Box<dyn PartialReflect>, value: Box<dyn PartialReflect>, ) -> Option<Box<dyn PartialReflect>> { assert_eq!( key.reflect_partial_eq(&*key), Some(true), "keys inserted in `Map`-like types are expected to reflect `PartialEq`" ); let hash = Self::internal_hash(&*key); let eq = Self::internal_eq(&*key); match self.hash_table.find_mut(hash, eq) { Some((_, old)) => Some(core::mem::replace(old, value)), None => { self.hash_table.insert_unique( Self::internal_hash(key.as_ref()), (key, value), |(key, _)| Self::internal_hash(&**key), ); None } } } fn remove(&mut self, key: &dyn PartialReflect) -> Option<Box<dyn PartialReflect>> { let hash = Self::internal_hash(key); let eq = Self::internal_eq(key); match self.hash_table.find_entry(hash, eq) { Ok(entry) => { let ((_, old_value), _) = entry.remove(); Some(old_value) } Err(_) => None, } } } impl PartialReflect for DynamicMap { #[inline] fn get_represented_type_info(&self) -> Option<&'static TypeInfo> { self.represented_type } #[inline] fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> { self } #[inline] fn as_partial_reflect(&self) -> &dyn PartialReflect { self } #[inline] fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect { self } fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> { Err(self) } fn try_as_reflect(&self) -> Option<&dyn Reflect> { None } fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { None } fn apply(&mut self, value: &dyn PartialReflect) { map_apply(self, value); } fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { map_try_apply(self, value) } fn reflect_kind(&self) -> ReflectKind { ReflectKind::Map } fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Map(self) } fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Map(self) } fn reflect_owned(self: Box<Self>) -> ReflectOwned { ReflectOwned::Map(self) } fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> { map_partial_eq(self, value) } fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicMap(")?; map_debug(self, f)?; write!(f, ")") } #[inline] fn is_dynamic(&self) -> bool { true } } impl_type_path!((in bevy_reflect) DynamicMap); impl Debug for DynamicMap { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.debug(f) } } impl FromIterator<(Box<dyn PartialReflect>, Box<dyn PartialReflect>)> for DynamicMap { fn from_iter<I: IntoIterator<Item = (Box<dyn PartialReflect>, Box<dyn PartialReflect>)>>( items: I, ) -> Self { let mut map = Self::default(); for (key, value) in items.into_iter() { map.insert_boxed(key, value); } map } } impl<K: Reflect, V: Reflect> FromIterator<(K, V)> for DynamicMap { fn from_iter<I: IntoIterator<Item = (K, V)>>(items: I) -> Self { let mut map = Self::default(); for (key, value) in items.into_iter() { map.insert(key, value); } map } } impl IntoIterator for DynamicMap { type Item = (Box<dyn PartialReflect>, Box<dyn PartialReflect>); type IntoIter = bevy_platform::collections::hash_table::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.hash_table.into_iter() } } impl<'a> IntoIterator for &'a DynamicMap { type Item = (&'a dyn PartialReflect, &'a dyn PartialReflect); type IntoIter = core::iter::Map< bevy_platform::collections::hash_table::Iter< 'a, (Box<dyn PartialReflect>, Box<dyn PartialReflect>), >, fn(&'a (Box<dyn PartialReflect>, Box<dyn PartialReflect>)) -> Self::Item, >; fn into_iter(self) -> Self::IntoIter { self.hash_table .iter() .map(|(k, v)| (k.as_ref(), v.as_ref())) } } /// Compares a [`Map`] with a [`PartialReflect`] value. /// /// Returns true if and only if all of the following are true: /// - `b` is a map; /// - `b` is the same length as `a`; /// - For each key-value pair in `a`, `b` contains a value for the given key, /// and [`PartialReflect::reflect_partial_eq`] returns `Some(true)` for the two values. /// /// Returns [`None`] if the comparison couldn't even be performed. #[inline] pub fn map_partial_eq<M: Map + ?Sized>(a: &M, b: &dyn PartialReflect) -> Option<bool> { let ReflectRef::Map(map) = b.reflect_ref() else { return Some(false); }; if a.len() != map.len() { return Some(false); } for (key, value) in a.iter() { if let Some(map_value) = map.get(key) { let eq_result = value.reflect_partial_eq(map_value); if let failed @ (Some(false) | None) = eq_result { return failed; } } else { return Some(false); } } Some(true) } /// The default debug formatter for [`Map`] types. /// /// # Example /// ``` /// # use std::collections::HashMap; /// use bevy_reflect::Reflect; /// /// let mut my_map = HashMap::new(); /// my_map.insert(123, String::from("Hello")); /// println!("{:#?}", &my_map as &dyn Reflect); /// /// // Output: /// /// // { /// // 123: "Hello", /// // } /// ``` #[inline] pub fn map_debug(dyn_map: &dyn Map, f: &mut Formatter<'_>) -> core::fmt::Result { let mut debug = f.debug_map(); for (key, value) in dyn_map.iter() { debug.entry(&key as &dyn Debug, &value as &dyn Debug); } debug.finish() } /// Applies the elements of reflected map `b` to the corresponding elements of map `a`. /// /// If a key from `b` does not exist in `a`, the value is cloned and inserted. /// If a key from `a` does not exist in `b`, the value is removed. /// /// # Panics /// /// This function panics if `b` is not a reflected map. #[inline] pub fn map_apply<M: Map>(a: &mut M, b: &dyn PartialReflect) { if let Err(err) = map_try_apply(a, b) { panic!("{err}"); } } /// Tries to apply the elements of reflected map `b` to the corresponding elements of map `a` /// and returns a Result. /// /// If a key from `b` does not exist in `a`, the value is cloned and inserted. /// If a key from `a` does not exist in `b`, the value is removed. /// /// # Errors /// /// This function returns an [`ApplyError::MismatchedKinds`] if `b` is not a reflected map or if /// applying elements to each other fails. #[inline] pub fn map_try_apply<M: Map>(a: &mut M, b: &dyn PartialReflect) -> Result<(), ApplyError> { let map_value = b.reflect_ref().as_map()?; for (key, b_value) in map_value.iter() { if let Some(a_value) = a.get_mut(key) { a_value.try_apply(b_value)?; } else { a.insert_boxed(key.to_dynamic(), b_value.to_dynamic()); } } a.retain(&mut |key, _| map_value.get(key).is_some()); Ok(()) } #[cfg(test)] mod tests { use crate::PartialReflect; use super::{DynamicMap, Map}; #[test] fn remove() { let mut map = DynamicMap::default(); map.insert(0, 0); map.insert(1, 1); assert_eq!(map.remove(&0).unwrap().try_downcast_ref(), Some(&0)); assert!(map.get(&0).is_none()); assert_eq!(map.get(&1).unwrap().try_downcast_ref(), Some(&1)); assert_eq!(map.remove(&1).unwrap().try_downcast_ref(), Some(&1)); assert!(map.get(&1).is_none()); assert!(map.remove(&1).is_none()); assert!(map.get(&1).is_none()); } #[test] fn apply() { let mut map_a = DynamicMap::default(); map_a.insert(0, 0); map_a.insert(1, 1); let mut map_b = DynamicMap::default(); map_b.insert(10, 10); map_b.insert(1, 5); map_a.apply(&map_b); assert!(map_a.get(&0).is_none()); assert_eq!(map_a.get(&1).unwrap().try_downcast_ref(), Some(&5)); assert_eq!(map_a.get(&10).unwrap().try_downcast_ref(), Some(&10)); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/struct_trait.rs
crates/bevy_reflect/src/struct_trait.rs
use crate::generics::impl_generic_info_methods; use crate::{ attributes::{impl_custom_attribute_methods, CustomAttributes}, type_info::impl_type_methods, ApplyError, Generics, NamedField, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type, TypeInfo, TypePath, }; use alloc::{borrow::Cow, boxed::Box, vec::Vec}; use bevy_platform::collections::HashMap; use bevy_platform::sync::Arc; use bevy_reflect_derive::impl_type_path; use core::{ fmt::{Debug, Formatter}, slice::Iter, }; /// A trait used to power [struct-like] operations via [reflection]. /// /// This trait uses the [`Reflect`] trait to allow implementors to have their fields /// be dynamically addressed by both name and index. /// /// When using [`#[derive(Reflect)]`](derive@crate::Reflect) on a standard struct, /// this trait will be automatically implemented. /// This goes for [unit structs] as well. /// /// # Example /// /// ``` /// use bevy_reflect::{PartialReflect, Reflect, Struct}; /// /// #[derive(Reflect)] /// struct Foo { /// bar: u32, /// } /// /// let foo = Foo { bar: 123 }; /// /// assert_eq!(foo.field_len(), 1); /// assert_eq!(foo.name_at(0), Some("bar")); /// /// let field: &dyn PartialReflect = foo.field("bar").unwrap(); /// assert_eq!(field.try_downcast_ref::<u32>(), Some(&123)); /// ``` /// /// [struct-like]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html /// [reflection]: crate /// [unit structs]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html#unit-like-structs-without-any-fields pub trait Struct: PartialReflect { /// Returns a reference to the value of the field named `name` as a `&dyn /// PartialReflect`. fn field(&self, name: &str) -> Option<&dyn PartialReflect>; /// Returns a mutable reference to the value of the field named `name` as a /// `&mut dyn PartialReflect`. fn field_mut(&mut self, name: &str) -> Option<&mut dyn PartialReflect>; /// Returns a reference to the value of the field with index `index` as a /// `&dyn PartialReflect`. fn field_at(&self, index: usize) -> Option<&dyn PartialReflect>; /// Returns a mutable reference to the value of the field with index `index` /// as a `&mut dyn PartialReflect`. fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>; /// Returns the name of the field with index `index`. fn name_at(&self, index: usize) -> Option<&str>; /// Returns the number of fields in the struct. fn field_len(&self) -> usize; /// Returns an iterator over the values of the reflectable fields for this struct. fn iter_fields(&self) -> FieldIter<'_>; /// Creates a new [`DynamicStruct`] from this struct. fn to_dynamic_struct(&self) -> DynamicStruct { let mut dynamic_struct = DynamicStruct::default(); dynamic_struct.set_represented_type(self.get_represented_type_info()); for (i, value) in self.iter_fields().enumerate() { dynamic_struct.insert_boxed(self.name_at(i).unwrap(), value.to_dynamic()); } dynamic_struct } /// Will return `None` if [`TypeInfo`] is not available. fn get_represented_struct_info(&self) -> Option<&'static StructInfo> { self.get_represented_type_info()?.as_struct().ok() } } /// A container for compile-time named struct info. #[derive(Clone, Debug)] pub struct StructInfo { ty: Type, generics: Generics, fields: Box<[NamedField]>, field_names: Box<[&'static str]>, field_indices: HashMap<&'static str, usize>, custom_attributes: Arc<CustomAttributes>, #[cfg(feature = "reflect_documentation")] docs: Option<&'static str>, } impl StructInfo { /// Create a new [`StructInfo`]. /// /// # Arguments /// /// * `fields`: The fields of this struct in the order they are defined pub fn new<T: Reflect + TypePath>(fields: &[NamedField]) -> Self { let field_indices = fields .iter() .enumerate() .map(|(index, field)| (field.name(), index)) .collect::<HashMap<_, _>>(); let field_names = fields.iter().map(NamedField::name).collect(); Self { ty: Type::of::<T>(), generics: Generics::new(), fields: fields.to_vec().into_boxed_slice(), field_names, field_indices, custom_attributes: Arc::new(CustomAttributes::default()), #[cfg(feature = "reflect_documentation")] docs: None, } } /// Sets the docstring for this struct. #[cfg(feature = "reflect_documentation")] pub fn with_docs(self, docs: Option<&'static str>) -> Self { Self { docs, ..self } } /// Sets the custom attributes for this struct. pub fn with_custom_attributes(self, custom_attributes: CustomAttributes) -> Self { Self { custom_attributes: Arc::new(custom_attributes), ..self } } /// A slice containing the names of all fields in order. pub fn field_names(&self) -> &[&'static str] { &self.field_names } /// Get the field with the given name. pub fn field(&self, name: &str) -> Option<&NamedField> { self.field_indices .get(name) .map(|index| &self.fields[*index]) } /// Get the field at the given index. pub fn field_at(&self, index: usize) -> Option<&NamedField> { self.fields.get(index) } /// Get the index of the field with the given name. pub fn index_of(&self, name: &str) -> Option<usize> { self.field_indices.get(name).copied() } /// Iterate over the fields of this struct. pub fn iter(&self) -> Iter<'_, NamedField> { self.fields.iter() } /// The total number of fields in this struct. pub fn field_len(&self) -> usize { self.fields.len() } impl_type_methods!(ty); /// The docstring of this struct, if any. #[cfg(feature = "reflect_documentation")] pub fn docs(&self) -> Option<&'static str> { self.docs } impl_custom_attribute_methods!(self.custom_attributes, "struct"); impl_generic_info_methods!(generics); } /// An iterator over the field values of a struct. pub struct FieldIter<'a> { pub(crate) struct_val: &'a dyn Struct, pub(crate) index: usize, } impl<'a> FieldIter<'a> { /// Creates a new [`FieldIter`]. pub fn new(value: &'a dyn Struct) -> Self { FieldIter { struct_val: value, index: 0, } } } impl<'a> Iterator for FieldIter<'a> { type Item = &'a dyn PartialReflect; fn next(&mut self) -> Option<Self::Item> { let value = self.struct_val.field_at(self.index); self.index += value.is_some() as usize; value } fn size_hint(&self) -> (usize, Option<usize>) { let size = self.struct_val.field_len(); (size, Some(size)) } } impl<'a> ExactSizeIterator for FieldIter<'a> {} /// A convenience trait which combines fetching and downcasting of struct /// fields. /// /// # Example /// /// ``` /// use bevy_reflect::{GetField, Reflect}; /// /// #[derive(Reflect)] /// struct Foo { /// bar: String, /// } /// /// # fn main() { /// let mut foo = Foo { bar: "Hello, world!".to_string() }; /// /// foo.get_field_mut::<String>("bar").unwrap().truncate(5); /// assert_eq!(foo.get_field::<String>("bar"), Some(&"Hello".to_string())); /// # } /// ``` pub trait GetField { /// Returns a reference to the value of the field named `name`, downcast to /// `T`. fn get_field<T: Reflect>(&self, name: &str) -> Option<&T>; /// Returns a mutable reference to the value of the field named `name`, /// downcast to `T`. fn get_field_mut<T: Reflect>(&mut self, name: &str) -> Option<&mut T>; } impl<S: Struct> GetField for S { fn get_field<T: Reflect>(&self, name: &str) -> Option<&T> { self.field(name) .and_then(|value| value.try_downcast_ref::<T>()) } fn get_field_mut<T: Reflect>(&mut self, name: &str) -> Option<&mut T> { self.field_mut(name) .and_then(|value| value.try_downcast_mut::<T>()) } } impl GetField for dyn Struct { fn get_field<T: Reflect>(&self, name: &str) -> Option<&T> { self.field(name) .and_then(|value| value.try_downcast_ref::<T>()) } fn get_field_mut<T: Reflect>(&mut self, name: &str) -> Option<&mut T> { self.field_mut(name) .and_then(|value| value.try_downcast_mut::<T>()) } } /// A struct type which allows fields to be added at runtime. #[derive(Default)] pub struct DynamicStruct { represented_type: Option<&'static TypeInfo>, fields: Vec<Box<dyn PartialReflect>>, field_names: Vec<Cow<'static, str>>, field_indices: HashMap<Cow<'static, str>, usize>, } impl DynamicStruct { /// Sets the [type] to be represented by this `DynamicStruct`. /// /// # Panics /// /// Panics if the given [type] is not a [`TypeInfo::Struct`]. /// /// [type]: TypeInfo pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) { if let Some(represented_type) = represented_type { assert!( matches!(represented_type, TypeInfo::Struct(_)), "expected TypeInfo::Struct but received: {represented_type:?}" ); } self.represented_type = represented_type; } /// Inserts a field named `name` with value `value` into the struct. /// /// If the field already exists, it is overwritten. pub fn insert_boxed<'a>( &mut self, name: impl Into<Cow<'a, str>>, value: Box<dyn PartialReflect>, ) { let name: Cow<str> = name.into(); if let Some(index) = self.field_indices.get(&name) { self.fields[*index] = value; } else { self.fields.push(value); self.field_indices .insert(Cow::Owned(name.clone().into_owned()), self.fields.len() - 1); self.field_names.push(Cow::Owned(name.into_owned())); } } /// Inserts a field named `name` with the typed value `value` into the struct. /// /// If the field already exists, it is overwritten. pub fn insert<'a, T: PartialReflect>(&mut self, name: impl Into<Cow<'a, str>>, value: T) { self.insert_boxed(name, Box::new(value)); } /// Gets the index of the field with the given name. pub fn index_of(&self, name: &str) -> Option<usize> { self.field_indices.get(name).copied() } } impl Struct for DynamicStruct { #[inline] fn field(&self, name: &str) -> Option<&dyn PartialReflect> { self.field_indices .get(name) .map(|index| &*self.fields[*index]) } #[inline] fn field_mut(&mut self, name: &str) -> Option<&mut dyn PartialReflect> { if let Some(index) = self.field_indices.get(name) { Some(&mut *self.fields[*index]) } else { None } } #[inline] fn field_at(&self, index: usize) -> Option<&dyn PartialReflect> { self.fields.get(index).map(|value| &**value) } #[inline] fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> { self.fields.get_mut(index).map(|value| &mut **value) } #[inline] fn name_at(&self, index: usize) -> Option<&str> { self.field_names.get(index).map(AsRef::as_ref) } #[inline] fn field_len(&self) -> usize { self.fields.len() } #[inline] fn iter_fields(&self) -> FieldIter<'_> { FieldIter { struct_val: self, index: 0, } } } impl PartialReflect for DynamicStruct { #[inline] fn get_represented_type_info(&self) -> Option<&'static TypeInfo> { self.represented_type } #[inline] fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> { self } #[inline] fn as_partial_reflect(&self) -> &dyn PartialReflect { self } #[inline] fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect { self } fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> { Err(self) } fn try_as_reflect(&self) -> Option<&dyn Reflect> { None } fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { None } fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { let struct_value = value.reflect_ref().as_struct()?; for (i, value) in struct_value.iter_fields().enumerate() { let name = struct_value.name_at(i).unwrap(); if let Some(v) = self.field_mut(name) { v.try_apply(value)?; } } Ok(()) } #[inline] fn reflect_kind(&self) -> ReflectKind { ReflectKind::Struct } #[inline] fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Struct(self) } #[inline] fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Struct(self) } #[inline] fn reflect_owned(self: Box<Self>) -> ReflectOwned { ReflectOwned::Struct(self) } fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> { struct_partial_eq(self, value) } fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicStruct(")?; struct_debug(self, f)?; write!(f, ")") } #[inline] fn is_dynamic(&self) -> bool { true } } impl_type_path!((in bevy_reflect) DynamicStruct); impl Debug for DynamicStruct { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.debug(f) } } impl<'a, N> FromIterator<(N, Box<dyn PartialReflect>)> for DynamicStruct where N: Into<Cow<'a, str>>, { /// Create a dynamic struct that doesn't represent a type from the /// field name, field value pairs. fn from_iter<I: IntoIterator<Item = (N, Box<dyn PartialReflect>)>>(fields: I) -> Self { let mut dynamic_struct = Self::default(); for (name, value) in fields.into_iter() { dynamic_struct.insert_boxed(name, value); } dynamic_struct } } impl IntoIterator for DynamicStruct { type Item = Box<dyn PartialReflect>; type IntoIter = alloc::vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.fields.into_iter() } } impl<'a> IntoIterator for &'a DynamicStruct { type Item = &'a dyn PartialReflect; type IntoIter = FieldIter<'a>; fn into_iter(self) -> Self::IntoIter { self.iter_fields() } } /// Compares a [`Struct`] with a [`PartialReflect`] value. /// /// Returns true if and only if all of the following are true: /// - `b` is a struct; /// - For each field in `a`, `b` contains a field with the same name and /// [`PartialReflect::reflect_partial_eq`] returns `Some(true)` for the two field /// values. /// /// Returns [`None`] if the comparison couldn't even be performed. #[inline] pub fn struct_partial_eq<S: Struct + ?Sized>(a: &S, b: &dyn PartialReflect) -> Option<bool> { let ReflectRef::Struct(struct_value) = b.reflect_ref() else { return Some(false); }; if a.field_len() != struct_value.field_len() { return Some(false); } for (i, value) in struct_value.iter_fields().enumerate() { let name = struct_value.name_at(i).unwrap(); if let Some(field_value) = a.field(name) { let eq_result = field_value.reflect_partial_eq(value); if let failed @ (Some(false) | None) = eq_result { return failed; } } else { return Some(false); } } Some(true) } /// The default debug formatter for [`Struct`] types. /// /// # Example /// ``` /// use bevy_reflect::Reflect; /// #[derive(Reflect)] /// struct MyStruct { /// foo: usize /// } /// /// let my_struct: &dyn Reflect = &MyStruct { foo: 123 }; /// println!("{:#?}", my_struct); /// /// // Output: /// /// // MyStruct { /// // foo: 123, /// // } /// ``` #[inline] pub fn struct_debug(dyn_struct: &dyn Struct, f: &mut Formatter<'_>) -> core::fmt::Result { let mut debug = f.debug_struct( dyn_struct .get_represented_type_info() .map(TypeInfo::type_path) .unwrap_or("_"), ); for field_index in 0..dyn_struct.field_len() { let field = dyn_struct.field_at(field_index).unwrap(); debug.field( dyn_struct.name_at(field_index).unwrap(), &field as &dyn Debug, ); } debug.finish() } #[cfg(test)] mod tests { use crate::*; #[derive(Reflect, Default)] struct MyStruct { a: (), b: (), c: (), } #[test] fn next_index_increment() { let my_struct = MyStruct::default(); let mut iter = my_struct.iter_fields(); iter.index = iter.len() - 1; let prev_index = iter.index; assert!(iter.next().is_some()); assert_eq!(prev_index, iter.index - 1); // When None we should no longer increase index let prev_index = iter.index; assert!(iter.next().is_none()); assert_eq!(prev_index, iter.index); assert!(iter.next().is_none()); assert_eq!(prev_index, iter.index); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/tuple.rs
crates/bevy_reflect/src/tuple.rs
use bevy_reflect_derive::impl_type_path; use variadics_please::all_tuples; use crate::generics::impl_generic_info_methods; use crate::{ type_info::impl_type_methods, utility::GenericTypePathCell, ApplyError, FromReflect, Generics, GetTypeRegistration, MaybeTyped, PartialReflect, Reflect, ReflectCloneError, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type, TypeInfo, TypePath, TypeRegistration, TypeRegistry, Typed, UnnamedField, }; use alloc::{boxed::Box, vec, vec::Vec}; use core::{ any::Any, fmt::{Debug, Formatter}, slice::Iter, }; /// A trait used to power [tuple-like] operations via [reflection]. /// /// This trait uses the [`Reflect`] trait to allow implementors to have their fields /// be dynamically addressed by index. /// /// This trait is automatically implemented for arbitrary tuples of up to 12 /// elements, provided that each element implements [`Reflect`]. /// /// # Example /// /// ``` /// use bevy_reflect::{PartialReflect, Tuple}; /// /// let foo = (123_u32, true); /// assert_eq!(foo.field_len(), 2); /// /// let field: &dyn PartialReflect = foo.field(0).unwrap(); /// assert_eq!(field.try_downcast_ref::<u32>(), Some(&123)); /// ``` /// /// [tuple-like]: https://doc.rust-lang.org/book/ch03-02-data-types.html#the-tuple-type /// [reflection]: crate pub trait Tuple: PartialReflect { /// Returns a reference to the value of the field with index `index` as a /// `&dyn Reflect`. fn field(&self, index: usize) -> Option<&dyn PartialReflect>; /// Returns a mutable reference to the value of the field with index `index` /// as a `&mut dyn Reflect`. fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>; /// Returns the number of fields in the tuple. fn field_len(&self) -> usize; /// Returns an iterator over the values of the tuple's fields. fn iter_fields(&self) -> TupleFieldIter<'_>; /// Drain the fields of this tuple to get a vector of owned values. fn drain(self: Box<Self>) -> Vec<Box<dyn PartialReflect>>; /// Creates a new [`DynamicTuple`] from this tuple. fn to_dynamic_tuple(&self) -> DynamicTuple { DynamicTuple { represented_type: self.get_represented_type_info(), fields: self.iter_fields().map(PartialReflect::to_dynamic).collect(), } } /// Will return `None` if [`TypeInfo`] is not available. fn get_represented_tuple_info(&self) -> Option<&'static TupleInfo> { self.get_represented_type_info()?.as_tuple().ok() } } /// An iterator over the field values of a tuple. pub struct TupleFieldIter<'a> { pub(crate) tuple: &'a dyn Tuple, pub(crate) index: usize, } impl<'a> TupleFieldIter<'a> { /// Creates a new [`TupleFieldIter`]. pub fn new(value: &'a dyn Tuple) -> Self { TupleFieldIter { tuple: value, index: 0, } } } impl<'a> Iterator for TupleFieldIter<'a> { type Item = &'a dyn PartialReflect; fn next(&mut self) -> Option<Self::Item> { let value = self.tuple.field(self.index); self.index += value.is_some() as usize; value } fn size_hint(&self) -> (usize, Option<usize>) { let size = self.tuple.field_len(); (size, Some(size)) } } impl<'a> ExactSizeIterator for TupleFieldIter<'a> {} /// A convenience trait which combines fetching and downcasting of tuple /// fields. /// /// # Example /// /// ``` /// use bevy_reflect::GetTupleField; /// /// # fn main() { /// let foo = ("blue".to_string(), 42_i32); /// /// assert_eq!(foo.get_field::<String>(0), Some(&"blue".to_string())); /// assert_eq!(foo.get_field::<i32>(1), Some(&42)); /// # } /// ``` pub trait GetTupleField { /// Returns a reference to the value of the field with index `index`, /// downcast to `T`. fn get_field<T: Reflect>(&self, index: usize) -> Option<&T>; /// Returns a mutable reference to the value of the field with index /// `index`, downcast to `T`. fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T>; } impl<S: Tuple> GetTupleField for S { fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> { self.field(index) .and_then(|value| value.try_downcast_ref::<T>()) } fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> { self.field_mut(index) .and_then(|value| value.try_downcast_mut::<T>()) } } impl GetTupleField for dyn Tuple { fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> { self.field(index) .and_then(|value| value.try_downcast_ref::<T>()) } fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> { self.field_mut(index) .and_then(|value| value.try_downcast_mut::<T>()) } } /// A container for compile-time tuple info. #[derive(Clone, Debug)] pub struct TupleInfo { ty: Type, generics: Generics, fields: Box<[UnnamedField]>, #[cfg(feature = "reflect_documentation")] docs: Option<&'static str>, } impl TupleInfo { /// Create a new [`TupleInfo`]. /// /// # Arguments /// /// * `fields`: The fields of this tuple in the order they are defined pub fn new<T: Reflect + TypePath>(fields: &[UnnamedField]) -> Self { Self { ty: Type::of::<T>(), generics: Generics::new(), fields: fields.to_vec().into_boxed_slice(), #[cfg(feature = "reflect_documentation")] docs: None, } } /// Sets the docstring for this tuple. #[cfg(feature = "reflect_documentation")] pub fn with_docs(self, docs: Option<&'static str>) -> Self { Self { docs, ..self } } /// Get the field at the given index. pub fn field_at(&self, index: usize) -> Option<&UnnamedField> { self.fields.get(index) } /// Iterate over the fields of this tuple. pub fn iter(&self) -> Iter<'_, UnnamedField> { self.fields.iter() } /// The total number of fields in this tuple. pub fn field_len(&self) -> usize { self.fields.len() } impl_type_methods!(ty); /// The docstring of this tuple, if any. #[cfg(feature = "reflect_documentation")] pub fn docs(&self) -> Option<&'static str> { self.docs } impl_generic_info_methods!(generics); } /// A tuple which allows fields to be added at runtime. #[derive(Default, Debug)] pub struct DynamicTuple { represented_type: Option<&'static TypeInfo>, fields: Vec<Box<dyn PartialReflect>>, } impl DynamicTuple { /// Sets the [type] to be represented by this `DynamicTuple`. /// /// # Panics /// /// Panics if the given [type] is not a [`TypeInfo::Tuple`]. /// /// [type]: TypeInfo pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) { if let Some(represented_type) = represented_type { assert!( matches!(represented_type, TypeInfo::Tuple(_)), "expected TypeInfo::Tuple but received: {represented_type:?}" ); } self.represented_type = represented_type; } /// Appends an element with value `value` to the tuple. pub fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) { self.represented_type = None; self.fields.push(value); } /// Appends a typed element with value `value` to the tuple. pub fn insert<T: PartialReflect>(&mut self, value: T) { self.represented_type = None; self.insert_boxed(Box::new(value)); } } impl Tuple for DynamicTuple { #[inline] fn field(&self, index: usize) -> Option<&dyn PartialReflect> { self.fields.get(index).map(|field| &**field) } #[inline] fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> { self.fields.get_mut(index).map(|field| &mut **field) } #[inline] fn field_len(&self) -> usize { self.fields.len() } #[inline] fn iter_fields(&self) -> TupleFieldIter<'_> { TupleFieldIter { tuple: self, index: 0, } } #[inline] fn drain(self: Box<Self>) -> Vec<Box<dyn PartialReflect>> { self.fields } } impl PartialReflect for DynamicTuple { #[inline] fn get_represented_type_info(&self) -> Option<&'static TypeInfo> { self.represented_type } #[inline] fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> { self } fn as_partial_reflect(&self) -> &dyn PartialReflect { self } fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect { self } fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> { Err(self) } fn try_as_reflect(&self) -> Option<&dyn Reflect> { None } fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { None } fn apply(&mut self, value: &dyn PartialReflect) { tuple_apply(self, value); } #[inline] fn reflect_kind(&self) -> ReflectKind { ReflectKind::Tuple } #[inline] fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Tuple(self) } #[inline] fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Tuple(self) } #[inline] fn reflect_owned(self: Box<Self>) -> ReflectOwned { ReflectOwned::Tuple(self) } fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { tuple_try_apply(self, value) } fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> { tuple_partial_eq(self, value) } fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicTuple(")?; tuple_debug(self, f)?; write!(f, ")") } #[inline] fn is_dynamic(&self) -> bool { true } } impl_type_path!((in bevy_reflect) DynamicTuple); impl FromIterator<Box<dyn PartialReflect>> for DynamicTuple { fn from_iter<I: IntoIterator<Item = Box<dyn PartialReflect>>>(fields: I) -> Self { Self { represented_type: None, fields: fields.into_iter().collect(), } } } impl IntoIterator for DynamicTuple { type Item = Box<dyn PartialReflect>; type IntoIter = vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.fields.into_iter() } } impl<'a> IntoIterator for &'a DynamicTuple { type Item = &'a dyn PartialReflect; type IntoIter = TupleFieldIter<'a>; fn into_iter(self) -> Self::IntoIter { self.iter_fields() } } /// Applies the elements of `b` to the corresponding elements of `a`. /// /// # Panics /// /// This function panics if `b` is not a tuple. #[inline] pub fn tuple_apply<T: Tuple>(a: &mut T, b: &dyn PartialReflect) { if let Err(err) = tuple_try_apply(a, b) { panic!("{err}"); } } /// Tries to apply the elements of `b` to the corresponding elements of `a` and /// returns a Result. /// /// # Errors /// /// This function returns an [`ApplyError::MismatchedKinds`] if `b` is not a tuple or if /// applying elements to each other fails. #[inline] pub fn tuple_try_apply<T: Tuple>(a: &mut T, b: &dyn PartialReflect) -> Result<(), ApplyError> { let tuple = b.reflect_ref().as_tuple()?; for (i, value) in tuple.iter_fields().enumerate() { if let Some(v) = a.field_mut(i) { v.try_apply(value)?; } } Ok(()) } /// Compares a [`Tuple`] with a [`PartialReflect`] value. /// /// Returns true if and only if all of the following are true: /// - `b` is a tuple; /// - `b` has the same number of elements as `a`; /// - [`PartialReflect::reflect_partial_eq`] returns `Some(true)` for pairwise elements of `a` and `b`. /// /// Returns [`None`] if the comparison couldn't even be performed. #[inline] pub fn tuple_partial_eq<T: Tuple + ?Sized>(a: &T, b: &dyn PartialReflect) -> Option<bool> { let ReflectRef::Tuple(b) = b.reflect_ref() else { return Some(false); }; if a.field_len() != b.field_len() { return Some(false); } for (a_field, b_field) in a.iter_fields().zip(b.iter_fields()) { let eq_result = a_field.reflect_partial_eq(b_field); if let failed @ (Some(false) | None) = eq_result { return failed; } } Some(true) } /// The default debug formatter for [`Tuple`] types. /// /// # Example /// ``` /// use bevy_reflect::Reflect; /// /// let my_tuple: &dyn Reflect = &(1, 2, 3); /// println!("{:#?}", my_tuple); /// /// // Output: /// /// // ( /// // 1, /// // 2, /// // 3, /// // ) /// ``` #[inline] pub fn tuple_debug(dyn_tuple: &dyn Tuple, f: &mut Formatter<'_>) -> core::fmt::Result { let mut debug = f.debug_tuple(""); for field in dyn_tuple.iter_fields() { debug.field(&field as &dyn Debug); } debug.finish() } macro_rules! impl_reflect_tuple { {$($index:tt : $name:tt),*} => { impl<$($name: Reflect + MaybeTyped + TypePath + GetTypeRegistration),*> Tuple for ($($name,)*) { #[inline] fn field(&self, index: usize) -> Option<&dyn PartialReflect> { match index { $($index => Some(&self.$index as &dyn PartialReflect),)* _ => None, } } #[inline] fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> { match index { $($index => Some(&mut self.$index as &mut dyn PartialReflect),)* _ => None, } } #[inline] fn field_len(&self) -> usize { let indices: &[usize] = &[$($index as usize),*]; indices.len() } #[inline] fn iter_fields(&self) -> TupleFieldIter<'_> { TupleFieldIter { tuple: self, index: 0, } } #[inline] fn drain(self: Box<Self>) -> Vec<Box<dyn PartialReflect>> { vec![ $(Box::new(self.$index),)* ] } } impl<$($name: Reflect + MaybeTyped + TypePath + GetTypeRegistration),*> PartialReflect for ($($name,)*) { fn get_represented_type_info(&self) -> Option<&'static TypeInfo> { Some(<Self as Typed>::type_info()) } #[inline] fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> { self } fn as_partial_reflect(&self) -> &dyn PartialReflect { self } fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect { self } fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> { Ok(self) } fn try_as_reflect(&self) -> Option<&dyn Reflect> { Some(self) } fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { Some(self) } fn reflect_kind(&self) -> ReflectKind { ReflectKind::Tuple } fn reflect_ref(&self) -> ReflectRef <'_> { ReflectRef::Tuple(self) } fn reflect_mut(&mut self) -> ReflectMut <'_> { ReflectMut::Tuple(self) } fn reflect_owned(self: Box<Self>) -> ReflectOwned { ReflectOwned::Tuple(self) } fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> { crate::tuple_partial_eq(self, value) } fn apply(&mut self, value: &dyn PartialReflect) { crate::tuple_apply(self, value); } fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { crate::tuple_try_apply(self, value) } fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> { Ok(Box::new(( $( self.$index.reflect_clone()? .take::<$name>() .expect("`Reflect::reflect_clone` should return the same type"), )* ))) } } impl<$($name: Reflect + MaybeTyped + TypePath + GetTypeRegistration),*> Reflect for ($($name,)*) { fn into_any(self: Box<Self>) -> Box<dyn Any> { self } fn as_any(&self) -> &dyn Any { self } fn as_any_mut(&mut self) -> &mut dyn Any { self } fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> { self } fn as_reflect(&self) -> &dyn Reflect { self } fn as_reflect_mut(&mut self) -> &mut dyn Reflect { self } fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> { *self = value.take()?; Ok(()) } } impl <$($name: Reflect + MaybeTyped + TypePath + GetTypeRegistration),*> Typed for ($($name,)*) { fn type_info() -> &'static TypeInfo { static CELL: $crate::utility::GenericTypeInfoCell = $crate::utility::GenericTypeInfoCell::new(); CELL.get_or_insert::<Self, _>(|| { let fields = [ $(UnnamedField::new::<$name>($index),)* ]; let info = TupleInfo::new::<Self>(&fields); TypeInfo::Tuple(info) }) } } impl<$($name: Reflect + MaybeTyped + TypePath + GetTypeRegistration),*> GetTypeRegistration for ($($name,)*) { fn get_type_registration() -> TypeRegistration { TypeRegistration::of::<($($name,)*)>() } fn register_type_dependencies(_registry: &mut TypeRegistry) { $(_registry.register::<$name>();)* } } impl<$($name: FromReflect + MaybeTyped + TypePath + GetTypeRegistration),*> FromReflect for ($($name,)*) { fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> { let _ref_tuple = reflect.reflect_ref().as_tuple().ok()?; Some( ( $( <$name as FromReflect>::from_reflect(_ref_tuple.field($index)?)?, )* ) ) } } } } impl_reflect_tuple! {} impl_reflect_tuple! {0: A} impl_reflect_tuple! {0: A, 1: B} impl_reflect_tuple! {0: A, 1: B, 2: C} impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D} impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E} impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F} impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G} impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H} impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I} impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J} impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K} impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L} macro_rules! impl_type_path_tuple { ($(#[$meta:meta])*) => { $(#[$meta])* impl TypePath for () { fn type_path() -> &'static str { "()" } fn short_type_path() -> &'static str { "()" } } }; ($(#[$meta:meta])* $param:ident) => { $(#[$meta])* impl <$param: TypePath> TypePath for ($param,) { fn type_path() -> &'static str { use $crate::__macro_exports::alloc_utils::ToOwned; static CELL: GenericTypePathCell = GenericTypePathCell::new(); CELL.get_or_insert::<Self, _>(|| { "(".to_owned() + $param::type_path() + ",)" }) } fn short_type_path() -> &'static str { use $crate::__macro_exports::alloc_utils::ToOwned; static CELL: GenericTypePathCell = GenericTypePathCell::new(); CELL.get_or_insert::<Self, _>(|| { "(".to_owned() + $param::short_type_path() + ",)" }) } } }; ($(#[$meta:meta])* $last:ident $(,$param:ident)*) => { $(#[$meta])* impl <$($param: TypePath,)* $last: TypePath> TypePath for ($($param,)* $last) { fn type_path() -> &'static str { use $crate::__macro_exports::alloc_utils::ToOwned; static CELL: GenericTypePathCell = GenericTypePathCell::new(); CELL.get_or_insert::<Self, _>(|| { "(".to_owned() $(+ $param::type_path() + ", ")* + $last::type_path() + ")" }) } fn short_type_path() -> &'static str { use $crate::__macro_exports::alloc_utils::ToOwned; static CELL: GenericTypePathCell = GenericTypePathCell::new(); CELL.get_or_insert::<Self, _>(|| { "(".to_owned() $(+ $param::short_type_path() + ", ")* + $last::short_type_path() + ")" }) } } }; } all_tuples!( #[doc(fake_variadic)] impl_type_path_tuple, 0, 12, P ); #[cfg(feature = "functions")] const _: () = { macro_rules! impl_get_ownership_tuple { ($(#[$meta:meta])* $($name: ident),*) => { $(#[$meta])* $crate::func::args::impl_get_ownership!(($($name,)*); <$($name),*>); }; } all_tuples!( #[doc(fake_variadic)] impl_get_ownership_tuple, 0, 12, P ); macro_rules! impl_from_arg_tuple { ($(#[$meta:meta])* $($name: ident),*) => { $(#[$meta])* $crate::func::args::impl_from_arg!(($($name,)*); <$($name: FromReflect + MaybeTyped + TypePath + GetTypeRegistration),*>); }; } all_tuples!( #[doc(fake_variadic)] impl_from_arg_tuple, 0, 12, P ); macro_rules! impl_into_return_tuple { ($(#[$meta:meta])* $($name: ident),+) => { $(#[$meta])* $crate::func::impl_into_return!(($($name,)*); <$($name: FromReflect + MaybeTyped + TypePath + GetTypeRegistration),*>); }; } // The unit type (i.e. `()`) is special-cased, so we skip implementing it here. all_tuples!( #[doc(fake_variadic)] impl_into_return_tuple, 1, 12, P ); }; #[cfg(test)] mod tests { use super::Tuple; #[test] fn next_index_increment() { let mut iter = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11).iter_fields(); let size = iter.len(); iter.index = size - 1; let prev_index = iter.index; assert!(iter.next().is_some()); assert_eq!(prev_index, iter.index - 1); // When None we should no longer increase index assert!(iter.next().is_none()); assert_eq!(size, iter.index); assert!(iter.next().is_none()); assert_eq!(size, iter.index); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/from_reflect.rs
crates/bevy_reflect/src/from_reflect.rs
use crate::{FromType, PartialReflect, Reflect}; use alloc::boxed::Box; /// A trait that enables types to be dynamically constructed from reflected data. /// /// It's recommended to use the [derive macro] rather than manually implementing this trait. /// /// `FromReflect` allows dynamic proxy types, like [`DynamicStruct`], to be used to generate /// their concrete counterparts. /// It can also be used to partially or fully clone a type (depending on whether it has /// ignored fields or not). /// /// In some cases, this trait may even be required. /// Deriving [`Reflect`] on an enum requires all its fields to implement `FromReflect`. /// Additionally, some complex types like `Vec<T>` require that their element types /// implement this trait. /// The reason for such requirements is that some operations require new data to be constructed, /// such as swapping to a new variant or pushing data to a homogeneous list. /// /// See the [crate-level documentation] to see how this trait can be used. /// /// [derive macro]: bevy_reflect_derive::FromReflect /// [`DynamicStruct`]: crate::DynamicStruct /// [crate-level documentation]: crate #[diagnostic::on_unimplemented( message = "`{Self}` does not implement `FromReflect` so cannot be created through reflection", note = "consider annotating `{Self}` with `#[derive(Reflect)]`" )] pub trait FromReflect: Reflect + Sized { /// Constructs a concrete instance of `Self` from a reflected value. fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self>; /// Attempts to downcast the given value to `Self` using, /// constructing the value using [`from_reflect`] if that fails. /// /// This method is more efficient than using [`from_reflect`] for cases where /// the given value is likely a boxed instance of `Self` (i.e. `Box<Self>`) /// rather than a boxed dynamic type (e.g. [`DynamicStruct`], [`DynamicList`], etc.). /// /// [`from_reflect`]: Self::from_reflect /// [`DynamicStruct`]: crate::DynamicStruct /// [`DynamicList`]: crate::DynamicList fn take_from_reflect( reflect: Box<dyn PartialReflect>, ) -> Result<Self, Box<dyn PartialReflect>> { match reflect.try_take::<Self>() { Ok(value) => Ok(value), Err(value) => match Self::from_reflect(value.as_ref()) { None => Err(value), Some(value) => Ok(value), }, } } } /// Type data that represents the [`FromReflect`] trait and allows it to be used dynamically. /// /// `FromReflect` allows dynamic types (e.g. [`DynamicStruct`], [`DynamicEnum`], etc.) to be converted /// to their full, concrete types. This is most important when it comes to deserialization where it isn't /// guaranteed that every field exists when trying to construct the final output. /// /// However, to do this, you normally need to specify the exact concrete type: /// /// ``` /// # use bevy_reflect::{DynamicTupleStruct, FromReflect, Reflect}; /// #[derive(Reflect, PartialEq, Eq, Debug)] /// struct Foo(#[reflect(default = "default_value")] usize); /// /// fn default_value() -> usize { 123 } /// /// let reflected = DynamicTupleStruct::default(); /// /// let concrete: Foo = <Foo as FromReflect>::from_reflect(&reflected).unwrap(); /// /// assert_eq!(Foo(123), concrete); /// ``` /// /// In a dynamic context where the type might not be known at compile-time, this is nearly impossible to do. /// That is why this type data struct exists— it allows us to construct the full type without knowing /// what the actual type is. /// /// # Example /// /// ``` /// # use bevy_reflect::{DynamicTupleStruct, Reflect, ReflectFromReflect, Typed, TypeRegistry, TypePath}; /// # #[derive(Reflect, PartialEq, Eq, Debug)] /// # struct Foo(#[reflect(default = "default_value")] usize); /// # fn default_value() -> usize { 123 } /// # let mut registry = TypeRegistry::new(); /// # registry.register::<Foo>(); /// /// let mut reflected = DynamicTupleStruct::default(); /// reflected.set_represented_type(Some(<Foo as Typed>::type_info())); /// /// let registration = registry.get_with_type_path(<Foo as TypePath>::type_path()).unwrap(); /// let rfr = registration.data::<ReflectFromReflect>().unwrap(); /// /// let concrete: Box<dyn Reflect> = rfr.from_reflect(&reflected).unwrap(); /// /// assert_eq!(Foo(123), concrete.take::<Foo>().unwrap()); /// ``` /// /// [`DynamicStruct`]: crate::DynamicStruct /// [`DynamicEnum`]: crate::DynamicEnum #[derive(Clone)] pub struct ReflectFromReflect { from_reflect: fn(&dyn PartialReflect) -> Option<Box<dyn Reflect>>, } impl ReflectFromReflect { /// Perform a [`FromReflect::from_reflect`] conversion on the given reflection object. /// /// This will convert the object to a concrete type if it wasn't already, and return /// the value as `Box<dyn Reflect>`. pub fn from_reflect(&self, reflect_value: &dyn PartialReflect) -> Option<Box<dyn Reflect>> { (self.from_reflect)(reflect_value) } } impl<T: FromReflect> FromType<T> for ReflectFromReflect { fn from_type() -> Self { Self { from_reflect: |reflect_value| { T::from_reflect(reflect_value).map(|value| Box::new(value) as Box<dyn Reflect>) }, } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/utility.rs
crates/bevy_reflect/src/utility.rs
//! Helpers for working with Bevy reflection. use crate::TypeInfo; use alloc::boxed::Box; use bevy_platform::{ hash::{DefaultHasher, FixedHasher, NoOpHash}, sync::{OnceLock, PoisonError, RwLock}, }; use bevy_utils::TypeIdMap; use core::{ any::{Any, TypeId}, hash::BuildHasher, }; /// A type that can be stored in a ([`Non`])[`GenericTypeCell`]. /// /// [`Non`]: NonGenericTypeCell pub trait TypedProperty: sealed::Sealed { /// The type of the value stored in [`GenericTypeCell`]. type Stored: 'static; } /// Used to store a [`String`] in a [`GenericTypePathCell`] as part of a [`TypePath`] implementation. /// /// [`TypePath`]: crate::TypePath /// [`String`]: alloc::string::String pub struct TypePathComponent; mod sealed { use super::{TypeInfo, TypePathComponent, TypedProperty}; use alloc::string::String; pub trait Sealed {} impl Sealed for TypeInfo {} impl Sealed for TypePathComponent {} impl TypedProperty for TypeInfo { type Stored = Self; } impl TypedProperty for TypePathComponent { type Stored = String; } } /// A container for [`TypeInfo`] over non-generic types, allowing instances to be stored statically. /// /// This is specifically meant for use with _non_-generic types. If your type _is_ generic, /// then use [`GenericTypeCell`] instead. Otherwise, it will not take into account all /// monomorphizations of your type. /// /// Non-generic [`TypePath`]s should be trivially generated with string literals and [`concat!`]. /// /// ## Example /// /// ``` /// # use core::any::Any; /// # use bevy_reflect::{DynamicTypePath, NamedField, PartialReflect, Reflect, ReflectMut, ReflectOwned, ReflectRef, StructInfo, Typed, TypeInfo, TypePath, ApplyError}; /// use bevy_reflect::utility::NonGenericTypeInfoCell; /// /// struct Foo { /// bar: i32 /// } /// /// impl Typed for Foo { /// fn type_info() -> &'static TypeInfo { /// static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new(); /// CELL.get_or_set(|| { /// let fields = [NamedField::new::<i32>("bar")]; /// let info = StructInfo::new::<Self>(&fields); /// TypeInfo::Struct(info) /// }) /// } /// } /// # impl TypePath for Foo { /// # fn type_path() -> &'static str { todo!() } /// # fn short_type_path() -> &'static str { todo!() } /// # } /// # impl PartialReflect for Foo { /// # fn get_represented_type_info(&self) -> Option<&'static TypeInfo> { todo!() } /// # fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> { todo!() } /// # fn as_partial_reflect(&self) -> &dyn PartialReflect { todo!() } /// # fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect { todo!() } /// # fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> { todo!() } /// # fn try_as_reflect(&self) -> Option<&dyn Reflect> { todo!() } /// # fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { todo!() } /// # fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { todo!() } /// # fn reflect_ref(&self) -> ReflectRef<'_> { todo!() } /// # fn reflect_mut(&mut self) -> ReflectMut<'_> { todo!() } /// # fn reflect_owned(self: Box<Self>) -> ReflectOwned { todo!() } /// # } /// # impl Reflect for Foo { /// # fn into_any(self: Box<Self>) -> Box<dyn Any> { todo!() } /// # fn as_any(&self) -> &dyn Any { todo!() } /// # fn as_any_mut(&mut self) -> &mut dyn Any { todo!() } /// # fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> { todo!() } /// # fn as_reflect(&self) -> &dyn Reflect { todo!() } /// # fn as_reflect_mut(&mut self) -> &mut dyn Reflect { todo!() } /// # fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> { todo!() } /// # } /// ``` /// /// [`TypePath`]: crate::TypePath pub struct NonGenericTypeCell<T: TypedProperty>(OnceLock<T::Stored>); /// See [`NonGenericTypeCell`]. pub type NonGenericTypeInfoCell = NonGenericTypeCell<TypeInfo>; impl<T: TypedProperty> NonGenericTypeCell<T> { /// Initialize a [`NonGenericTypeCell`] for non-generic types. pub const fn new() -> Self { Self(OnceLock::new()) } /// Returns a reference to the [`TypedProperty`] stored in the cell. /// /// If there is no entry found, a new one will be generated from the given function. pub fn get_or_set<F>(&self, f: F) -> &T::Stored where F: FnOnce() -> T::Stored, { self.0.get_or_init(f) } } impl<T: TypedProperty> Default for NonGenericTypeCell<T> { fn default() -> Self { Self::new() } } /// A container for [`TypedProperty`] over generic types, allowing instances to be stored statically. /// /// This is specifically meant for use with generic types. If your type isn't generic, /// then use [`NonGenericTypeCell`] instead as it should be much more performant. /// /// `#[derive(TypePath)]` and [`impl_type_path`] should always be used over [`GenericTypePathCell`] /// where possible. /// /// ## Examples /// /// Implementing [`TypeInfo`] with generics. /// /// ``` /// # use core::any::Any; /// # use bevy_reflect::{DynamicTypePath, PartialReflect, Reflect, ReflectMut, ReflectOwned, ReflectRef, TupleStructInfo, Typed, TypeInfo, TypePath, UnnamedField, ApplyError, Generics, TypeParamInfo}; /// use bevy_reflect::utility::GenericTypeInfoCell; /// /// struct Foo<T>(T); /// /// impl<T: Reflect + Typed + TypePath> Typed for Foo<T> { /// fn type_info() -> &'static TypeInfo { /// static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new(); /// CELL.get_or_insert::<Self, _>(|| { /// let fields = [UnnamedField::new::<T>(0)]; /// let info = TupleStructInfo::new::<Self>(&fields) /// .with_generics(Generics::from_iter([TypeParamInfo::new::<T>("T")])); /// TypeInfo::TupleStruct(info) /// }) /// } /// } /// # impl<T: TypePath> TypePath for Foo<T> { /// # fn type_path() -> &'static str { todo!() } /// # fn short_type_path() -> &'static str { todo!() } /// # } /// # impl<T: PartialReflect + TypePath> PartialReflect for Foo<T> { /// # fn get_represented_type_info(&self) -> Option<&'static TypeInfo> { todo!() } /// # fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> { todo!() } /// # fn as_partial_reflect(&self) -> &dyn PartialReflect { todo!() } /// # fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect { todo!() } /// # fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> { todo!() } /// # fn try_as_reflect(&self) -> Option<&dyn Reflect> { todo!() } /// # fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { todo!() } /// # fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { todo!() } /// # fn reflect_ref(&self) -> ReflectRef<'_> { todo!() } /// # fn reflect_mut(&mut self) -> ReflectMut<'_> { todo!() } /// # fn reflect_owned(self: Box<Self>) -> ReflectOwned { todo!() } /// # } /// # impl<T: Reflect + Typed + TypePath> Reflect for Foo<T> { /// # fn into_any(self: Box<Self>) -> Box<dyn Any> { todo!() } /// # fn as_any(&self) -> &dyn Any { todo!() } /// # fn as_any_mut(&mut self) -> &mut dyn Any { todo!() } /// # fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> { todo!() } /// # fn as_reflect(&self) -> &dyn Reflect { todo!() } /// # fn as_reflect_mut(&mut self) -> &mut dyn Reflect { todo!() } /// # fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> { todo!() } /// # } /// ``` /// /// Implementing [`TypePath`] with generics. /// /// ``` /// # use core::any::Any; /// # use bevy_reflect::TypePath; /// use bevy_reflect::utility::GenericTypePathCell; /// /// struct Foo<T>(T); /// /// impl<T: TypePath> TypePath for Foo<T> { /// fn type_path() -> &'static str { /// static CELL: GenericTypePathCell = GenericTypePathCell::new(); /// CELL.get_or_insert::<Self, _>(|| format!("my_crate::foo::Foo<{}>", T::type_path())) /// } /// /// fn short_type_path() -> &'static str { /// static CELL: GenericTypePathCell = GenericTypePathCell::new(); /// CELL.get_or_insert::<Self, _>(|| format!("Foo<{}>", T::short_type_path())) /// } /// /// fn type_ident() -> Option<&'static str> { /// Some("Foo") /// } /// /// fn module_path() -> Option<&'static str> { /// Some("my_crate::foo") /// } /// /// fn crate_name() -> Option<&'static str> { /// Some("my_crate") /// } /// } /// ``` /// [`impl_type_path`]: crate::impl_type_path /// [`TypePath`]: crate::TypePath pub struct GenericTypeCell<T: TypedProperty>(RwLock<TypeIdMap<&'static T::Stored>>); /// See [`GenericTypeCell`]. pub type GenericTypeInfoCell = GenericTypeCell<TypeInfo>; /// See [`GenericTypeCell`]. pub type GenericTypePathCell = GenericTypeCell<TypePathComponent>; impl<T: TypedProperty> GenericTypeCell<T> { /// Initialize a [`GenericTypeCell`] for generic types. pub const fn new() -> Self { Self(RwLock::new(TypeIdMap::with_hasher(NoOpHash))) } /// Returns a reference to the [`TypedProperty`] stored in the cell. /// /// This method will then return the correct [`TypedProperty`] reference for the given type `T`. /// If there is no entry found, a new one will be generated from the given function. pub fn get_or_insert<G, F>(&self, f: F) -> &T::Stored where G: Any + ?Sized, F: FnOnce() -> T::Stored, { self.get_or_insert_by_type_id(TypeId::of::<G>(), f) } /// Returns a reference to the [`TypedProperty`] stored in the cell, if any. /// /// This method will then return the correct [`TypedProperty`] reference for the given type `T`. fn get_by_type_id(&self, type_id: TypeId) -> Option<&T::Stored> { self.0 .read() .unwrap_or_else(PoisonError::into_inner) .get(&type_id) .copied() } /// Returns a reference to the [`TypedProperty`] stored in the cell. /// /// This method will then return the correct [`TypedProperty`] reference for the given type `T`. /// If there is no entry found, a new one will be generated from the given function. fn get_or_insert_by_type_id<F>(&self, type_id: TypeId, f: F) -> &T::Stored where F: FnOnce() -> T::Stored, { match self.get_by_type_id(type_id) { Some(info) => info, None => self.insert_by_type_id(type_id, f()), } } fn insert_by_type_id(&self, type_id: TypeId, value: T::Stored) -> &T::Stored { let mut write_lock = self.0.write().unwrap_or_else(PoisonError::into_inner); write_lock .entry(type_id) .insert({ // We leak here in order to obtain a `&'static` reference. // Otherwise, we won't be able to return a reference due to the `RwLock`. // This should be okay, though, since we expect it to remain statically // available over the course of the application. Box::leak(Box::new(value)) }) .get() } } impl<T: TypedProperty> Default for GenericTypeCell<T> { fn default() -> Self { Self::new() } } /// Deterministic fixed state hasher to be used by implementors of [`Reflect::reflect_hash`]. /// /// Hashes should be deterministic across processes so hashes can be used as /// checksums for saved scenes, rollback snapshots etc. This function returns /// such a hasher. /// /// [`Reflect::reflect_hash`]: crate::Reflect #[inline] pub fn reflect_hasher() -> DefaultHasher<'static> { FixedHasher.build_hasher() }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/attributes.rs
crates/bevy_reflect/src/attributes.rs
//! Types and functions for creating, manipulating and querying [`CustomAttributes`]. use crate::Reflect; use alloc::boxed::Box; use bevy_utils::TypeIdMap; use core::{ any::TypeId, fmt::{Debug, Formatter}, }; /// A collection of custom attributes for a type, field, or variant. /// /// These attributes can be created with the [`Reflect` derive macro]. /// /// Attributes are stored by their [`TypeId`]. /// Because of this, there can only be one attribute per type. /// /// # Example /// /// ``` /// # use bevy_reflect::{Reflect, Typed, TypeInfo}; /// use core::ops::RangeInclusive; /// #[derive(Reflect)] /// struct Slider { /// #[reflect(@RangeInclusive::<f32>::new(0.0, 1.0))] /// value: f32 /// } /// /// let TypeInfo::Struct(info) = <Slider as Typed>::type_info() else { /// panic!("expected struct info"); /// }; /// /// let range = info.field("value").unwrap().get_attribute::<RangeInclusive<f32>>().unwrap(); /// assert_eq!(0.0..=1.0, *range); /// ``` /// /// [`Reflect` derive macro]: derive@crate::Reflect #[derive(Default)] pub struct CustomAttributes { attributes: TypeIdMap<CustomAttribute>, } impl CustomAttributes { /// Inserts a custom attribute into the collection. /// /// Note that this will overwrite any existing attribute of the same type. pub fn with_attribute<T: Reflect>(mut self, value: T) -> Self { self.attributes .insert(TypeId::of::<T>(), CustomAttribute::new(value)); self } /// Returns `true` if this collection contains a custom attribute of the specified type. pub fn contains<T: Reflect>(&self) -> bool { self.attributes.contains_key(&TypeId::of::<T>()) } /// Returns `true` if this collection contains a custom attribute with the specified [`TypeId`]. pub fn contains_by_id(&self, id: TypeId) -> bool { self.attributes.contains_key(&id) } /// Gets a custom attribute by type. pub fn get<T: Reflect>(&self) -> Option<&T> { self.attributes.get(&TypeId::of::<T>())?.value::<T>() } /// Gets a custom attribute by its [`TypeId`]. pub fn get_by_id(&self, id: TypeId) -> Option<&dyn Reflect> { Some(self.attributes.get(&id)?.reflect_value()) } /// Returns an iterator over all custom attributes. pub fn iter(&self) -> impl ExactSizeIterator<Item = (&TypeId, &dyn Reflect)> { self.attributes .iter() .map(|(key, value)| (key, value.reflect_value())) } /// Returns the number of custom attributes in this collection. pub fn len(&self) -> usize { self.attributes.len() } /// Returns `true` if this collection is empty. pub fn is_empty(&self) -> bool { self.attributes.is_empty() } } impl Debug for CustomAttributes { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { f.debug_set().entries(self.attributes.values()).finish() } } struct CustomAttribute { value: Box<dyn Reflect>, } impl CustomAttribute { /// Creates a new [`CustomAttribute`] containing `value`. pub fn new<T: Reflect>(value: T) -> Self { Self { value: Box::new(value), } } /// Returns a reference to the attribute's value if it is of type `T`, or [`None`] if not. pub fn value<T: Reflect>(&self) -> Option<&T> { self.value.downcast_ref() } /// Returns a reference to the attribute's value as a [`Reflect`] trait object. pub fn reflect_value(&self) -> &dyn Reflect { &*self.value } } impl Debug for CustomAttribute { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.value.debug(f) } } /// Implements methods for accessing custom attributes. /// /// Implements the following methods: /// /// * `fn custom_attributes(&self) -> &CustomAttributes` /// * `fn get_attribute<T: Reflect>(&self) -> Option<&T>` /// * `fn get_attribute_by_id(&self, id: TypeId) -> Option<&dyn Reflect>` /// * `fn has_attribute<T: Reflect>(&self) -> bool` /// * `fn has_attribute_by_id(&self, id: TypeId) -> bool` /// /// # Params /// /// * `$self` - The name of the variable containing the custom attributes (usually `self`). /// * `$attributes` - The name of the field containing the [`CustomAttributes`]. /// * `$term` - (Optional) The term used to describe the type containing the custom attributes. /// This is purely used to generate better documentation. Defaults to `"item"`. macro_rules! impl_custom_attribute_methods { ($self:ident . $attributes:ident, $term:literal) => { $crate::attributes::impl_custom_attribute_methods!($self, &$self.$attributes, "item"); }; ($self:ident, $attributes:expr, $term:literal) => { #[doc = concat!("Returns the custom attributes for this ", $term, ".")] pub fn custom_attributes(&$self) -> &$crate::attributes::CustomAttributes { $attributes } /// Gets a custom attribute by type. /// /// For dynamically accessing an attribute, see [`get_attribute_by_id`](Self::get_attribute_by_id). pub fn get_attribute<T: $crate::Reflect>(&$self) -> Option<&T> { $self.custom_attributes().get::<T>() } /// Gets a custom attribute by its [`TypeId`](core::any::TypeId). /// /// This is the dynamic equivalent of [`get_attribute`](Self::get_attribute). pub fn get_attribute_by_id(&$self, id: ::core::any::TypeId) -> Option<&dyn $crate::Reflect> { $self.custom_attributes().get_by_id(id) } #[doc = concat!("Returns `true` if this ", $term, " has a custom attribute of the specified type.")] #[doc = "\n\nFor dynamically checking if an attribute exists, see [`has_attribute_by_id`](Self::has_attribute_by_id)."] pub fn has_attribute<T: $crate::Reflect>(&$self) -> bool { $self.custom_attributes().contains::<T>() } #[doc = concat!("Returns `true` if this ", $term, " has a custom attribute with the specified [`TypeId`](::core::any::TypeId).")] #[doc = "\n\nThis is the dynamic equivalent of [`has_attribute`](Self::has_attribute)"] pub fn has_attribute_by_id(&$self, id: ::core::any::TypeId) -> bool { $self.custom_attributes().contains_by_id(id) } }; } pub(crate) use impl_custom_attribute_methods; #[cfg(test)] mod tests { use super::*; use crate::{type_info::Typed, TypeInfo, VariantInfo}; use alloc::{format, string::String}; use core::ops::RangeInclusive; #[derive(Reflect, PartialEq, Debug)] struct Tooltip(String); impl Tooltip { fn new(value: impl Into<String>) -> Self { Self(value.into()) } } #[test] fn should_get_custom_attribute() { let attributes = CustomAttributes::default().with_attribute(0.0..=1.0); let value = attributes.get::<RangeInclusive<f64>>().unwrap(); assert_eq!(&(0.0..=1.0), value); } #[test] fn should_get_custom_attribute_dynamically() { let attributes = CustomAttributes::default().with_attribute(String::from("Hello, World!")); let value = attributes.get_by_id(TypeId::of::<String>()).unwrap(); assert!(value .reflect_partial_eq(&String::from("Hello, World!")) .unwrap()); } #[test] fn should_debug_custom_attributes() { let attributes = CustomAttributes::default().with_attribute("My awesome custom attribute!"); let debug = format!("{attributes:?}"); assert_eq!(r#"{"My awesome custom attribute!"}"#, debug); #[derive(Reflect)] struct Foo { value: i32, } let attributes = CustomAttributes::default().with_attribute(Foo { value: 42 }); let debug = format!("{attributes:?}"); assert_eq!( r#"{bevy_reflect::attributes::tests::Foo { value: 42 }}"#, debug ); } #[test] fn should_derive_custom_attributes_on_struct_container() { #[derive(Reflect)] #[reflect(@Tooltip::new("My awesome custom attribute!"))] struct Slider { value: f32, } let TypeInfo::Struct(info) = Slider::type_info() else { panic!("expected struct info"); }; let tooltip = info.get_attribute::<Tooltip>().unwrap(); assert_eq!(&Tooltip::new("My awesome custom attribute!"), tooltip); } #[test] fn should_derive_custom_attributes_on_struct_fields() { #[derive(Reflect)] struct Slider { #[reflect(@0.0..=1.0)] #[reflect(@Tooltip::new("Range: 0.0 to 1.0"))] value: f32, } let TypeInfo::Struct(info) = Slider::type_info() else { panic!("expected struct info"); }; let field = info.field("value").unwrap(); let range = field.get_attribute::<RangeInclusive<f64>>().unwrap(); assert_eq!(&(0.0..=1.0), range); let tooltip = field.get_attribute::<Tooltip>().unwrap(); assert_eq!(&Tooltip::new("Range: 0.0 to 1.0"), tooltip); } #[test] fn should_derive_custom_attributes_on_tuple_container() { #[derive(Reflect)] #[reflect(@Tooltip::new("My awesome custom attribute!"))] struct Slider(f32); let TypeInfo::TupleStruct(info) = Slider::type_info() else { panic!("expected tuple struct info"); }; let tooltip = info.get_attribute::<Tooltip>().unwrap(); assert_eq!(&Tooltip::new("My awesome custom attribute!"), tooltip); } #[test] fn should_derive_custom_attributes_on_tuple_struct_fields() { #[derive(Reflect)] struct Slider( #[reflect(@0.0..=1.0)] #[reflect(@Tooltip::new("Range: 0.0 to 1.0"))] f32, ); let TypeInfo::TupleStruct(info) = Slider::type_info() else { panic!("expected tuple struct info"); }; let field = info.field_at(0).unwrap(); let range = field.get_attribute::<RangeInclusive<f64>>().unwrap(); assert_eq!(&(0.0..=1.0), range); let tooltip = field.get_attribute::<Tooltip>().unwrap(); assert_eq!(&Tooltip::new("Range: 0.0 to 1.0"), tooltip); } #[test] fn should_derive_custom_attributes_on_enum_container() { #[derive(Reflect)] #[reflect(@Tooltip::new("My awesome custom attribute!"))] enum Color { Transparent, Grayscale(f32), Rgb { r: u8, g: u8, b: u8 }, } let TypeInfo::Enum(info) = Color::type_info() else { panic!("expected enum info"); }; let tooltip = info.get_attribute::<Tooltip>().unwrap(); assert_eq!(&Tooltip::new("My awesome custom attribute!"), tooltip); } #[test] fn should_derive_custom_attributes_on_enum_variants() { #[derive(Reflect, Debug, PartialEq)] enum Display { Toggle, Slider, Picker, } #[derive(Reflect)] enum Color { #[reflect(@Display::Toggle)] Transparent, #[reflect(@Display::Slider)] Grayscale(f32), #[reflect(@Display::Picker)] Rgb { r: u8, g: u8, b: u8 }, } let TypeInfo::Enum(info) = Color::type_info() else { panic!("expected enum info"); }; let VariantInfo::Unit(transparent_variant) = info.variant("Transparent").unwrap() else { panic!("expected unit variant"); }; let display = transparent_variant.get_attribute::<Display>().unwrap(); assert_eq!(&Display::Toggle, display); let VariantInfo::Tuple(grayscale_variant) = info.variant("Grayscale").unwrap() else { panic!("expected tuple variant"); }; let display = grayscale_variant.get_attribute::<Display>().unwrap(); assert_eq!(&Display::Slider, display); let VariantInfo::Struct(rgb_variant) = info.variant("Rgb").unwrap() else { panic!("expected struct variant"); }; let display = rgb_variant.get_attribute::<Display>().unwrap(); assert_eq!(&Display::Picker, display); } #[test] fn should_derive_custom_attributes_on_enum_variant_fields() { #[derive(Reflect)] enum Color { Transparent, Grayscale(#[reflect(@0.0..=1.0_f32)] f32), Rgb { #[reflect(@0..=255u8)] r: u8, #[reflect(@0..=255u8)] g: u8, #[reflect(@0..=255u8)] b: u8, }, } let TypeInfo::Enum(info) = Color::type_info() else { panic!("expected enum info"); }; let VariantInfo::Tuple(grayscale_variant) = info.variant("Grayscale").unwrap() else { panic!("expected tuple variant"); }; let field = grayscale_variant.field_at(0).unwrap(); let range = field.get_attribute::<RangeInclusive<f32>>().unwrap(); assert_eq!(&(0.0..=1.0), range); let VariantInfo::Struct(rgb_variant) = info.variant("Rgb").unwrap() else { panic!("expected struct variant"); }; let field = rgb_variant.field("g").unwrap(); let range = field.get_attribute::<RangeInclusive<u8>>().unwrap(); assert_eq!(&(0..=255), range); } #[test] fn should_allow_unit_struct_attribute_values() { #[derive(Reflect)] struct Required; #[derive(Reflect)] struct Foo { #[reflect(@Required)] value: i32, } let TypeInfo::Struct(info) = Foo::type_info() else { panic!("expected struct info"); }; let field = info.field("value").unwrap(); assert!(field.has_attribute::<Required>()); } #[test] fn should_accept_last_attribute() { #[derive(Reflect)] struct Foo { #[reflect(@false)] #[reflect(@true)] value: i32, } let TypeInfo::Struct(info) = Foo::type_info() else { panic!("expected struct info"); }; let field = info.field("value").unwrap(); assert!(field.get_attribute::<bool>().unwrap()); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/is.rs
crates/bevy_reflect/src/is.rs
use core::any::{Any, TypeId}; /// Checks if the current type "is" another type, using a [`TypeId`] equality comparison. pub trait Is { /// Checks if the current type "is" another type, using a [`TypeId`] equality comparison. /// This is most useful in the context of generic logic. /// /// ``` /// # use bevy_reflect::Is; /// # use std::any::Any; /// fn greet_if_u32<T: Any>() { /// if T::is::<u32>() { /// println!("Hello"); /// } /// } /// // this will print "Hello" /// greet_if_u32::<u32>(); /// // this will not print "Hello" /// greet_if_u32::<String>(); /// assert!(u32::is::<u32>()); /// assert!(!usize::is::<u32>()); /// ``` fn is<T: Any>() -> bool; } impl<A: Any> Is for A { #[inline] fn is<T: Any>() -> bool { TypeId::of::<A>() == TypeId::of::<T>() } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/set.rs
crates/bevy_reflect/src/set.rs
use alloc::{boxed::Box, format, vec::Vec}; use core::fmt::{Debug, Formatter}; use bevy_platform::collections::{hash_table::OccupiedEntry as HashTableOccupiedEntry, HashTable}; use bevy_reflect_derive::impl_type_path; use crate::{ generics::impl_generic_info_methods, hash_error, type_info::impl_type_methods, ApplyError, Generics, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type, TypeInfo, TypePath, }; /// A trait used to power [set-like] operations via [reflection]. /// /// Sets contain zero or more entries of a fixed type, and correspond to types /// like [`HashSet`] and [`BTreeSet`]. /// The order of these entries is not guaranteed by this trait. /// /// # Hashing and equality /// /// All values are expected to return a valid hash value from [`PartialReflect::reflect_hash`] and be /// comparable using [`PartialReflect::reflect_partial_eq`]. /// If using the [`#[derive(Reflect)]`](derive@crate::Reflect) macro, this can be done by adding /// `#[reflect(Hash, PartialEq)]` to the entire struct or enum. /// The ordering is expected to be total, that is as if the reflected type implements the [`Eq`] trait. /// This is true even for manual implementors who do not hash or compare values, /// as it is still relied on by [`DynamicSet`]. /// /// # Example /// /// ``` /// use bevy_reflect::{PartialReflect, Set}; /// use std::collections::HashSet; /// /// /// let foo: &mut dyn Set = &mut HashSet::<u32>::new(); /// foo.insert_boxed(Box::new(123_u32)); /// assert_eq!(foo.len(), 1); /// /// let field: &dyn PartialReflect = foo.get(&123_u32).unwrap(); /// assert_eq!(field.try_downcast_ref::<u32>(), Some(&123_u32)); /// ``` /// /// [`HashSet`]: std::collections::HashSet /// [`BTreeSet`]: alloc::collections::BTreeSet /// [set-like]: https://doc.rust-lang.org/stable/std/collections/struct.HashSet.html /// [reflection]: crate pub trait Set: PartialReflect { /// Returns a reference to the value. /// /// If no value is contained, returns `None`. fn get(&self, value: &dyn PartialReflect) -> Option<&dyn PartialReflect>; /// Returns the number of elements in the set. fn len(&self) -> usize; /// Returns `true` if the list contains no elements. fn is_empty(&self) -> bool { self.len() == 0 } /// Returns an iterator over the values of the set. fn iter(&self) -> Box<dyn Iterator<Item = &dyn PartialReflect> + '_>; /// Drain the values of this set to get a vector of owned values. /// /// After calling this function, `self` will be empty. fn drain(&mut self) -> Vec<Box<dyn PartialReflect>>; /// Retain only the elements specified by the predicate. /// /// In other words, remove all elements `e` for which `f(&e)` returns `false`. fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect) -> bool); /// Creates a new [`DynamicSet`] from this set. fn to_dynamic_set(&self) -> DynamicSet { let mut set = DynamicSet::default(); set.set_represented_type(self.get_represented_type_info()); for value in self.iter() { set.insert_boxed(value.to_dynamic()); } set } /// Inserts a value into the set. /// /// If the set did not have this value present, `true` is returned. /// If the set did have this value present, `false` is returned. fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) -> bool; /// Removes a value from the set. /// /// If the set did not have this value present, `true` is returned. /// If the set did have this value present, `false` is returned. fn remove(&mut self, value: &dyn PartialReflect) -> bool; /// Checks if the given value is contained in the set fn contains(&self, value: &dyn PartialReflect) -> bool; } /// A container for compile-time set info. #[derive(Clone, Debug)] pub struct SetInfo { ty: Type, generics: Generics, value_ty: Type, #[cfg(feature = "reflect_documentation")] docs: Option<&'static str>, } impl SetInfo { /// Create a new [`SetInfo`]. pub fn new<TSet: Set + TypePath, TValue: Reflect + TypePath>() -> Self { Self { ty: Type::of::<TSet>(), generics: Generics::new(), value_ty: Type::of::<TValue>(), #[cfg(feature = "reflect_documentation")] docs: None, } } /// Sets the docstring for this set. #[cfg(feature = "reflect_documentation")] pub fn with_docs(self, docs: Option<&'static str>) -> Self { Self { docs, ..self } } impl_type_methods!(ty); /// The [type] of the value. /// /// [type]: Type pub fn value_ty(&self) -> Type { self.value_ty } /// The docstring of this set, if any. #[cfg(feature = "reflect_documentation")] pub fn docs(&self) -> Option<&'static str> { self.docs } impl_generic_info_methods!(generics); } /// An unordered set of reflected values. #[derive(Default)] pub struct DynamicSet { represented_type: Option<&'static TypeInfo>, hash_table: HashTable<Box<dyn PartialReflect>>, } impl DynamicSet { /// Sets the [type] to be represented by this `DynamicSet`. /// /// # Panics /// /// Panics if the given [type] is not a [`TypeInfo::Set`]. /// /// [type]: TypeInfo pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) { if let Some(represented_type) = represented_type { assert!( matches!(represented_type, TypeInfo::Set(_)), "expected TypeInfo::Set but received: {represented_type:?}" ); } self.represented_type = represented_type; } /// Inserts a typed value into the set. pub fn insert<V: Reflect>(&mut self, value: V) { self.insert_boxed(Box::new(value)); } fn internal_hash(value: &dyn PartialReflect) -> u64 { value.reflect_hash().expect(&hash_error!(value)) } fn internal_eq( value: &dyn PartialReflect, ) -> impl FnMut(&Box<dyn PartialReflect>) -> bool + '_ { |other| { value .reflect_partial_eq(&**other) .expect("Underlying type does not reflect `PartialEq` and hence doesn't support equality checks") } } } impl Set for DynamicSet { fn get(&self, value: &dyn PartialReflect) -> Option<&dyn PartialReflect> { self.hash_table .find(Self::internal_hash(value), Self::internal_eq(value)) .map(|value| &**value) } fn len(&self) -> usize { self.hash_table.len() } fn iter(&self) -> Box<dyn Iterator<Item = &dyn PartialReflect> + '_> { let iter = self.hash_table.iter().map(|v| &**v); Box::new(iter) } fn drain(&mut self) -> Vec<Box<dyn PartialReflect>> { self.hash_table.drain().collect::<Vec<_>>() } fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect) -> bool) { self.hash_table.retain(move |value| f(&**value)); } fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) -> bool { assert_eq!( value.reflect_partial_eq(&*value), Some(true), "Values inserted in `Set` like types are expected to reflect `PartialEq`" ); match self .hash_table .find_mut(Self::internal_hash(&*value), Self::internal_eq(&*value)) { Some(old) => { *old = value; false } None => { self.hash_table.insert_unique( Self::internal_hash(value.as_ref()), value, |boxed| Self::internal_hash(boxed.as_ref()), ); true } } } fn remove(&mut self, value: &dyn PartialReflect) -> bool { self.hash_table .find_entry(Self::internal_hash(value), Self::internal_eq(value)) .map(HashTableOccupiedEntry::remove) .is_ok() } fn contains(&self, value: &dyn PartialReflect) -> bool { self.hash_table .find(Self::internal_hash(value), Self::internal_eq(value)) .is_some() } } impl PartialReflect for DynamicSet { #[inline] fn get_represented_type_info(&self) -> Option<&'static TypeInfo> { self.represented_type } #[inline] fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> { self } #[inline] fn as_partial_reflect(&self) -> &dyn PartialReflect { self } #[inline] fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect { self } #[inline] fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> { Err(self) } #[inline] fn try_as_reflect(&self) -> Option<&dyn Reflect> { None } #[inline] fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { None } fn apply(&mut self, value: &dyn PartialReflect) { set_apply(self, value); } fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { set_try_apply(self, value) } fn reflect_kind(&self) -> ReflectKind { ReflectKind::Set } fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Set(self) } fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Set(self) } fn reflect_owned(self: Box<Self>) -> ReflectOwned { ReflectOwned::Set(self) } fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> { set_partial_eq(self, value) } fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicSet(")?; set_debug(self, f)?; write!(f, ")") } #[inline] fn is_dynamic(&self) -> bool { true } } impl_type_path!((in bevy_reflect) DynamicSet); impl Debug for DynamicSet { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.debug(f) } } impl FromIterator<Box<dyn PartialReflect>> for DynamicSet { fn from_iter<I: IntoIterator<Item = Box<dyn PartialReflect>>>(values: I) -> Self { let mut this = Self { represented_type: None, hash_table: HashTable::new(), }; for value in values { this.insert_boxed(value); } this } } impl<T: Reflect> FromIterator<T> for DynamicSet { fn from_iter<I: IntoIterator<Item = T>>(values: I) -> Self { let mut this = Self { represented_type: None, hash_table: HashTable::new(), }; for value in values { this.insert(value); } this } } impl IntoIterator for DynamicSet { type Item = Box<dyn PartialReflect>; type IntoIter = bevy_platform::collections::hash_table::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.hash_table.into_iter() } } impl<'a> IntoIterator for &'a DynamicSet { type Item = &'a dyn PartialReflect; type IntoIter = core::iter::Map< bevy_platform::collections::hash_table::Iter<'a, Box<dyn PartialReflect>>, fn(&'a Box<dyn PartialReflect>) -> Self::Item, >; fn into_iter(self) -> Self::IntoIter { self.hash_table.iter().map(|v| v.as_ref()) } } /// Compares a [`Set`] with a [`PartialReflect`] value. /// /// Returns true if and only if all of the following are true: /// - `b` is a set; /// - `b` is the same length as `a`; /// - For each value pair in `a`, `b` contains the value too, /// and [`PartialReflect::reflect_partial_eq`] returns `Some(true)` for the two values. /// /// Returns [`None`] if the comparison couldn't even be performed. #[inline] pub fn set_partial_eq<M: Set>(a: &M, b: &dyn PartialReflect) -> Option<bool> { let ReflectRef::Set(set) = b.reflect_ref() else { return Some(false); }; if a.len() != set.len() { return Some(false); } for value in a.iter() { if let Some(set_value) = set.get(value) { let eq_result = value.reflect_partial_eq(set_value); if let failed @ (Some(false) | None) = eq_result { return failed; } } else { return Some(false); } } Some(true) } /// The default debug formatter for [`Set`] types. /// /// # Example /// ``` /// # use std::collections::HashSet; /// use bevy_reflect::Reflect; /// /// let mut my_set = HashSet::new(); /// my_set.insert(String::from("Hello")); /// println!("{:#?}", &my_set as &dyn Reflect); /// /// // Output: /// /// // { /// // "Hello", /// // } /// ``` #[inline] pub fn set_debug(dyn_set: &dyn Set, f: &mut Formatter<'_>) -> core::fmt::Result { let mut debug = f.debug_set(); for value in dyn_set.iter() { debug.entry(&value as &dyn Debug); } debug.finish() } /// Applies the elements of reflected set `b` to the corresponding elements of set `a`. /// /// If a value from `b` does not exist in `a`, the value is cloned and inserted. /// If a value from `a` does not exist in `b`, the value is removed. /// /// # Panics /// /// This function panics if `b` is not a reflected set. #[inline] pub fn set_apply<M: Set>(a: &mut M, b: &dyn PartialReflect) { if let Err(err) = set_try_apply(a, b) { panic!("{err}"); } } /// Tries to apply the elements of reflected set `b` to the corresponding elements of set `a` /// and returns a Result. /// /// If a value from `b` does not exist in `a`, the value is cloned and inserted. /// If a value from `a` does not exist in `b`, the value is removed. /// /// # Errors /// /// This function returns an [`ApplyError::MismatchedKinds`] if `b` is not a reflected set or if /// applying elements to each other fails. #[inline] pub fn set_try_apply<S: Set>(a: &mut S, b: &dyn PartialReflect) -> Result<(), ApplyError> { let set_value = b.reflect_ref().as_set()?; for b_value in set_value.iter() { if a.get(b_value).is_none() { a.insert_boxed(b_value.to_dynamic()); } } a.retain(&mut |value| set_value.get(value).is_some()); Ok(()) } #[cfg(test)] mod tests { use crate::{PartialReflect, Set}; use super::DynamicSet; use alloc::string::{String, ToString}; #[test] fn test_into_iter() { let expected = ["foo", "bar", "baz"]; let mut set = DynamicSet::default(); set.insert(expected[0].to_string()); set.insert(expected[1].to_string()); set.insert(expected[2].to_string()); for item in set.into_iter() { let value = item .try_take::<String>() .expect("couldn't downcast to String"); let index = expected .iter() .position(|i| *i == value.as_str()) .expect("Element found in expected array"); assert_eq!(expected[index], value); } } #[test] fn apply() { let mut map_a = DynamicSet::default(); map_a.insert(0); map_a.insert(1); let mut map_b = DynamicSet::default(); map_b.insert(1); map_b.insert(2); map_a.apply(&map_b); assert!(map_a.get(&0).is_none()); assert_eq!(map_a.get(&1).unwrap().try_downcast_ref(), Some(&1)); assert_eq!(map_a.get(&2).unwrap().try_downcast_ref(), Some(&2)); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/signature.rs
crates/bevy_reflect/src/func/signature.rs
//! Function signature types. //! //! Function signatures differ from [`FunctionInfo`] and [`SignatureInfo`] in that they //! are only concerned about the types and order of the arguments and return type of a function. //! //! The names of arguments do not matter, //! nor does any other information about the function such as its name or other attributes. //! //! This makes signatures useful for comparing or hashing functions strictly based on their //! arguments and return type. //! //! [`FunctionInfo`]: crate::func::info::FunctionInfo use crate::func::args::ArgInfo; use crate::func::{ArgList, SignatureInfo}; use crate::Type; use alloc::boxed::Box; use bevy_platform::collections::Equivalent; use core::borrow::Borrow; use core::fmt::{Debug, Formatter}; use core::hash::{Hash, Hasher}; use core::ops::{Deref, DerefMut}; /// The signature of a function. /// /// This can be used as a way to compare or hash functions based on their arguments and return type. #[derive(Clone, PartialEq, Eq, Hash)] pub struct Signature { args: ArgumentSignature, ret: Type, } impl Signature { /// Create a new function signature with the given argument signature and return type. pub fn new(args: ArgumentSignature, ret: Type) -> Self { Self { args, ret } } /// Get the argument signature of the function. pub fn args(&self) -> &ArgumentSignature { &self.args } /// Get the return type of the function. pub fn return_type(&self) -> &Type { &self.ret } } impl Debug for Signature { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "{:?} -> {:?}", self.args, self.ret) } } impl<T: Borrow<SignatureInfo>> From<T> for Signature { fn from(info: T) -> Self { let info = info.borrow(); Self::new(ArgumentSignature::from(info), *info.return_info().ty()) } } /// A wrapper around a borrowed [`ArgList`] that can be used as an /// [equivalent] of an [`ArgumentSignature`]. /// /// [equivalent]: Equivalent pub(super) struct ArgListSignature<'a, 'b>(&'a ArgList<'b>); impl Equivalent<ArgumentSignature> for ArgListSignature<'_, '_> { fn equivalent(&self, key: &ArgumentSignature) -> bool { self.len() == key.len() && self.iter().eq(key.iter()) } } impl<'a, 'b> ArgListSignature<'a, 'b> { pub fn iter(&self) -> impl ExactSizeIterator<Item = &Type> { self.0.iter().map(|arg| { arg.value() .get_represented_type_info() .unwrap_or_else(|| { panic!("no `TypeInfo` found for argument: {:?}", arg); }) .ty() }) } pub fn len(&self) -> usize { self.0.len() } } impl Eq for ArgListSignature<'_, '_> {} impl PartialEq for ArgListSignature<'_, '_> { fn eq(&self, other: &Self) -> bool { self.len() == other.len() && self.iter().eq(other.iter()) } } impl Hash for ArgListSignature<'_, '_> { fn hash<H: Hasher>(&self, state: &mut H) { self.0.iter().for_each(|arg| { arg.value() .get_represented_type_info() .unwrap_or_else(|| { panic!("no `TypeInfo` found for argument: {:?}", arg); }) .ty() .hash(state); }); } } impl<'a, 'b> From<&'a ArgList<'b>> for ArgListSignature<'a, 'b> { fn from(args: &'a ArgList<'b>) -> Self { Self(args) } } /// The argument-portion of a function signature. /// /// For example, given a function signature `(a: i32, b: f32) -> u32`, /// the argument signature would be `(i32, f32)`. /// /// This can be used as a way to compare or hash functions based on their arguments. #[derive(Clone)] pub struct ArgumentSignature(Box<[Type]>); impl Debug for ArgumentSignature { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { let mut tuple = f.debug_tuple(""); for ty in self.0.iter() { tuple.field(ty); } tuple.finish() } } impl Deref for ArgumentSignature { type Target = [Type]; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for ArgumentSignature { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl Eq for ArgumentSignature {} impl PartialEq for ArgumentSignature { fn eq(&self, other: &Self) -> bool { self.0.len() == other.0.len() && self.0.iter().eq(other.0.iter()) } } impl Hash for ArgumentSignature { fn hash<H: Hasher>(&self, state: &mut H) { self.0.iter().for_each(|ty| ty.hash(state)); } } impl FromIterator<Type> for ArgumentSignature { fn from_iter<T: IntoIterator<Item = Type>>(iter: T) -> Self { Self(iter.into_iter().collect()) } } impl<T: Borrow<SignatureInfo>> From<T> for ArgumentSignature { fn from(info: T) -> Self { Self( info.borrow() .args() .iter() .map(ArgInfo::ty) .copied() .collect(), ) } } impl From<&ArgList<'_>> for ArgumentSignature { fn from(args: &ArgList) -> Self { Self( args.iter() .map(|arg| { arg.value() .get_represented_type_info() .unwrap_or_else(|| { panic!("no `TypeInfo` found for argument: {:?}", arg); }) .ty() }) .copied() .collect(), ) } } #[cfg(test)] mod tests { use super::*; use crate::func::TypedFunction; use alloc::{format, string::String, vec}; #[test] fn should_generate_signature_from_function_info() { fn add(a: i32, b: f32) -> u32 { (a as f32 + b).round() as u32 } let info = add.get_function_info(); let signature = Signature::from(info.base()); assert_eq!(signature.args().0.len(), 2); assert_eq!(signature.args().0[0], Type::of::<i32>()); assert_eq!(signature.args().0[1], Type::of::<f32>()); assert_eq!(*signature.return_type(), Type::of::<u32>()); } #[test] fn should_debug_signature() { let signature = Signature::new( ArgumentSignature::from_iter(vec![Type::of::<&mut String>(), Type::of::<i32>()]), Type::of::<()>(), ); assert_eq!( format!("{signature:?}"), "(&mut alloc::string::String, i32) -> ()" ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/into_function_mut.rs
crates/bevy_reflect/src/func/into_function_mut.rs
use crate::func::{DynamicFunctionMut, ReflectFnMut, TypedFunction}; /// A trait for types that can be converted into a [`DynamicFunctionMut`]. /// /// This trait is automatically implemented for any type that implements /// [`ReflectFnMut`] and [`TypedFunction`]. /// /// This trait can be seen as a superset of [`IntoFunction`]. /// /// See the [module-level documentation] for more information. /// /// # Trait Parameters /// /// This trait has a `Marker` type parameter that is used to get around issues with /// [unconstrained type parameters] when defining impls with generic arguments or return types. /// This `Marker` can be any type, provided it doesn't conflict with other implementations. /// /// Additionally, it has a lifetime parameter, `'env`, that is used to bound the lifetime of the function. /// For named functions and some closures, this will end up just being `'static`, /// however, closures that borrow from their environment will have a lifetime bound to that environment. /// /// [`IntoFunction`]: crate::func::IntoFunction /// [module-level documentation]: crate::func /// [unconstrained type parameters]: https://doc.rust-lang.org/error_codes/E0207.html pub trait IntoFunctionMut<'env, Marker> { /// Converts [`Self`] into a [`DynamicFunctionMut`]. fn into_function_mut(self) -> DynamicFunctionMut<'env>; } impl<'env, F, Marker1, Marker2> IntoFunctionMut<'env, (Marker1, Marker2)> for F where F: ReflectFnMut<'env, Marker1> + TypedFunction<Marker2> + 'env, { fn into_function_mut(mut self) -> DynamicFunctionMut<'env> { DynamicFunctionMut::new( move |args| self.reflect_call_mut(args), Self::function_info(), ) } } #[cfg(test)] mod tests { use super::*; use crate::func::{ArgList, IntoFunction}; #[test] fn should_create_dynamic_function_mut_from_closure() { let c = 23; let func = (|a: i32, b: i32| a + b + c).into_function(); let args = ArgList::new().with_owned(25_i32).with_owned(75_i32); let result = func.call(args).unwrap().unwrap_owned(); assert_eq!(result.try_downcast_ref::<i32>(), Some(&123)); } #[test] fn should_create_dynamic_function_mut_from_closure_with_mutable_capture() { let mut total = 0; let func = (|a: i32, b: i32| total = a + b).into_function_mut(); let args = ArgList::new().with_owned(25_i32).with_owned(75_i32); func.call_once(args).unwrap(); assert_eq!(total, 100); } #[test] fn should_create_dynamic_function_mut_from_function() { fn add(a: i32, b: i32) -> i32 { a + b } let mut func = add.into_function_mut(); let args = ArgList::new().with_owned(25_i32).with_owned(75_i32); let result = func.call(args).unwrap().unwrap_owned(); assert_eq!(result.try_downcast_ref::<i32>(), Some(&100)); } #[test] fn should_default_closure_name_to_none() { let mut total = 0; let func = (|a: i32, b: i32| total = a + b).into_function_mut(); assert!(func.name().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_reflect/src/func/dynamic_function.rs
crates/bevy_reflect/src/func/dynamic_function.rs
use crate::{ __macro_exports::RegisterForReflection, func::{ args::{ArgCount, ArgList}, dynamic_function_internal::DynamicFunctionInternal, info::FunctionInfo, DynamicFunctionMut, Function, FunctionOverloadError, FunctionResult, IntoFunction, IntoFunctionMut, }, ApplyError, MaybeTyped, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, TypeInfo, TypePath, }; use alloc::{borrow::Cow, boxed::Box}; use bevy_platform::sync::Arc; use bevy_reflect_derive::impl_type_path; use core::fmt::{Debug, Formatter}; /// An [`Arc`] containing a callback to a reflected function. /// /// The `Arc` is used to both ensure that it is `Send + Sync` /// and to allow for the callback to be cloned. /// /// Note that cloning is okay since we only ever need an immutable reference /// to call a `dyn Fn` function. /// If we were to contain a `dyn FnMut` instead, cloning would be a lot more complicated. type ArcFn<'env> = Arc<dyn for<'a> Fn(ArgList<'a>) -> FunctionResult<'a> + Send + Sync + 'env>; /// A dynamic representation of a function. /// /// This type can be used to represent any callable that satisfies [`Fn`] /// (or the reflection-based equivalent, [`ReflectFn`]). /// That is, any function or closure that does not mutably borrow data from its environment. /// /// For functions that do need to capture their environment mutably (i.e. mutable closures), /// see [`DynamicFunctionMut`]. /// /// See the [module-level documentation] for more information. /// /// You will generally not need to construct this manually. /// Instead, many functions and closures can be automatically converted using the [`IntoFunction`] trait. /// /// # Example /// /// Most of the time, a [`DynamicFunction`] can be created using the [`IntoFunction`] trait: /// /// ``` /// # use bevy_reflect::func::{ArgList, DynamicFunction, IntoFunction}; /// # /// fn add(a: i32, b: i32) -> i32 { /// a + b /// } /// /// // Convert the function into a dynamic function using `IntoFunction::into_function`: /// let mut func: DynamicFunction = add.into_function(); /// /// // Dynamically call it: /// let args = ArgList::default().with_owned(25_i32).with_owned(75_i32); /// let value = func.call(args).unwrap().unwrap_owned(); /// /// // Check the result: /// assert_eq!(value.try_downcast_ref::<i32>(), Some(&100)); /// ``` /// /// [`ReflectFn`]: crate::func::ReflectFn /// [module-level documentation]: crate::func #[derive(Clone)] pub struct DynamicFunction<'env> { pub(super) internal: DynamicFunctionInternal<ArcFn<'env>>, } impl<'env> DynamicFunction<'env> { /// Create a new [`DynamicFunction`]. /// /// The given function can be used to call out to any other callable, /// including functions, closures, or methods. /// /// It's important that the function signature matches the provided [`FunctionInfo`]. /// as this will be used to validate arguments when [calling] the function. /// This is also required in order for [function overloading] to work correctly. /// /// # Panics /// /// This function may panic for any of the following reasons: /// - No [`SignatureInfo`] is provided. /// - A provided [`SignatureInfo`] has more arguments than [`ArgCount::MAX_COUNT`]. /// - The conversion to [`FunctionInfo`] fails. /// /// [calling]: crate::func::dynamic_function::DynamicFunction::call /// [`SignatureInfo`]: crate::func::SignatureInfo /// [function overloading]: Self::with_overload pub fn new<F: for<'a> Fn(ArgList<'a>) -> FunctionResult<'a> + Send + Sync + 'env>( func: F, info: impl TryInto<FunctionInfo, Error: Debug>, ) -> Self { let arc = Arc::new(func); #[cfg(not(target_has_atomic = "ptr"))] #[expect( unsafe_code, reason = "unsized coercion is an unstable feature for non-std types" )] // SAFETY: // - Coercion from `T` to `dyn for<'a> Fn(ArgList<'a>) -> FunctionResult<'a> + Send + Sync + 'env` // is valid as `T: for<'a> Fn(ArgList<'a>) -> FunctionResult<'a> + Send + Sync + 'env` // - `Arc::from_raw` receives a valid pointer from a previous call to `Arc::into_raw` let arc = unsafe { ArcFn::<'env>::from_raw(Arc::into_raw(arc) as *const _) }; Self { internal: DynamicFunctionInternal::new(arc, info.try_into().unwrap()), } } /// Set the name of the function. /// /// For [`DynamicFunctions`] created using [`IntoFunction`], /// the default name will always be the full path to the function as returned by [`core::any::type_name`], /// unless the function is a closure, anonymous function, or function pointer, /// in which case the name will be `None`. /// /// [`DynamicFunctions`]: DynamicFunction pub fn with_name(mut self, name: impl Into<Cow<'static, str>>) -> Self { self.internal = self.internal.with_name(name); self } /// Add an overload to this function. /// /// Overloads allow a single [`DynamicFunction`] to represent multiple functions of different signatures. /// /// This can be used to handle multiple monomorphizations of a generic function /// or to allow functions with a variable number of arguments. /// /// Any functions with the same [argument signature] will be overwritten by the one from the new function, `F`. /// For example, if the existing function had the signature `(i32, i32) -> i32`, /// and the new function, `F`, also had the signature `(i32, i32) -> i32`, /// the one from `F` would replace the one from the existing function. /// /// Overloaded functions retain the [name] of the original function. /// /// # Panics /// /// Panics if the function, `F`, contains a signature already found in this function. /// /// For a non-panicking version, see [`try_with_overload`]. /// /// # Examples /// /// ``` /// # use std::ops::Add; /// # use bevy_reflect::func::{ArgList, IntoFunction}; /// # /// fn add<T: Add<Output = T>>(a: T, b: T) -> T { /// a + b /// } /// /// // Currently, the only generic type `func` supports is `i32`: /// let mut func = add::<i32>.into_function(); /// /// // However, we can add an overload to handle `f32` as well: /// func = func.with_overload(add::<f32>); /// /// // Test `i32`: /// let args = ArgList::default().with_owned(25_i32).with_owned(75_i32); /// let result = func.call(args).unwrap().unwrap_owned(); /// assert_eq!(result.try_take::<i32>().unwrap(), 100); /// /// // Test `f32`: /// let args = ArgList::default().with_owned(25.0_f32).with_owned(75.0_f32); /// let result = func.call(args).unwrap().unwrap_owned(); /// assert_eq!(result.try_take::<f32>().unwrap(), 100.0); ///``` /// /// ``` /// # use bevy_reflect::func::{ArgList, IntoFunction}; /// # /// fn add_2(a: i32, b: i32) -> i32 { /// a + b /// } /// /// fn add_3(a: i32, b: i32, c: i32) -> i32 { /// a + b + c /// } /// /// // Currently, `func` only supports two arguments. /// let mut func = add_2.into_function(); /// /// // However, we can add an overload to handle three arguments as well. /// func = func.with_overload(add_3); /// /// // Test two arguments: /// let args = ArgList::default().with_owned(25_i32).with_owned(75_i32); /// let result = func.call(args).unwrap().unwrap_owned(); /// assert_eq!(result.try_take::<i32>().unwrap(), 100); /// /// // Test three arguments: /// let args = ArgList::default() /// .with_owned(25_i32) /// .with_owned(75_i32) /// .with_owned(100_i32); /// let result = func.call(args).unwrap().unwrap_owned(); /// assert_eq!(result.try_take::<i32>().unwrap(), 200); /// ``` /// ///```should_panic /// # use bevy_reflect::func::IntoFunction; /// /// fn add(a: i32, b: i32) -> i32 { /// a + b /// } /// /// fn sub(a: i32, b: i32) -> i32 { /// a - b /// } /// /// let mut func = add.into_function(); /// /// // This will panic because the function already has an argument signature for `(i32, i32)`: /// func = func.with_overload(sub); /// ``` /// /// [argument signature]: crate::func::signature::ArgumentSignature /// [name]: Self::name /// [`try_with_overload`]: Self::try_with_overload pub fn with_overload<'a, F: IntoFunction<'a, Marker>, Marker>( self, function: F, ) -> DynamicFunction<'a> where 'env: 'a, { self.try_with_overload(function).unwrap_or_else(|(_, err)| { panic!("{}", err); }) } /// Attempt to add an overload to this function. /// /// If the function, `F`, contains a signature already found in this function, /// an error will be returned along with the original function. /// /// For a panicking version, see [`with_overload`]. /// /// [`with_overload`]: Self::with_overload pub fn try_with_overload<F: IntoFunction<'env, Marker>, Marker>( mut self, function: F, ) -> Result<Self, (Box<Self>, FunctionOverloadError)> { let function = function.into_function(); match self.internal.merge(function.internal) { Ok(_) => Ok(self), Err(err) => Err((Box::new(self), err)), } } /// Call the function with the given arguments. /// /// # Example /// /// ``` /// # use bevy_reflect::func::{IntoFunction, ArgList}; /// let c = 23; /// let add = |a: i32, b: i32| -> i32 { /// a + b + c /// }; /// /// let mut func = add.into_function().with_name("add"); /// let args = ArgList::new().with_owned(25_i32).with_owned(75_i32); /// let result = func.call(args).unwrap().unwrap_owned(); /// assert_eq!(result.try_take::<i32>().unwrap(), 123); /// ``` /// /// # Errors /// /// This method will return an error if the number of arguments provided does not match /// the number of arguments expected by the function's [`FunctionInfo`]. /// /// The function itself may also return any errors it needs to. pub fn call<'a>(&self, args: ArgList<'a>) -> FunctionResult<'a> { self.internal.validate_args(&args)?; let func = self.internal.get(&args)?; func(args) } /// Returns the function info. pub fn info(&self) -> &FunctionInfo { self.internal.info() } /// The name of the function. /// /// For [`DynamicFunctions`] created using [`IntoFunction`], /// the default name will always be the full path to the function as returned by [`core::any::type_name`], /// unless the function is a closure, anonymous function, or function pointer, /// in which case the name will be `None`. /// /// This can be overridden using [`with_name`]. /// /// If the function was [overloaded], it will retain its original name if it had one. /// /// [`DynamicFunctions`]: DynamicFunction /// [`with_name`]: Self::with_name /// [overloaded]: Self::with_overload pub fn name(&self) -> Option<&Cow<'static, str>> { self.internal.name() } /// Returns `true` if the function is [overloaded]. /// /// # Example /// /// ``` /// # use bevy_reflect::func::IntoFunction; /// let add = (|a: i32, b: i32| a + b).into_function(); /// assert!(!add.is_overloaded()); /// /// let add = add.with_overload(|a: f32, b: f32| a + b); /// assert!(add.is_overloaded()); /// ``` /// /// [overloaded]: Self::with_overload pub fn is_overloaded(&self) -> bool { self.internal.is_overloaded() } /// Returns the number of arguments the function expects. /// /// For [overloaded] functions that can have a variable number of arguments, /// this will contain the full set of counts for all signatures. /// /// # Example /// /// ``` /// # use bevy_reflect::func::IntoFunction; /// let add = (|a: i32, b: i32| a + b).into_function(); /// assert!(add.arg_count().contains(2)); /// /// let add = add.with_overload(|a: f32, b: f32, c: f32| a + b + c); /// assert!(add.arg_count().contains(2)); /// assert!(add.arg_count().contains(3)); /// ``` /// /// [overloaded]: Self::with_overload pub fn arg_count(&self) -> ArgCount { self.internal.arg_count() } } impl Function for DynamicFunction<'static> { fn name(&self) -> Option<&Cow<'static, str>> { self.internal.name() } fn info(&self) -> &FunctionInfo { self.internal.info() } fn reflect_call<'a>(&self, args: ArgList<'a>) -> FunctionResult<'a> { self.call(args) } fn to_dynamic_function(&self) -> DynamicFunction<'static> { self.clone() } } impl PartialReflect for DynamicFunction<'static> { fn get_represented_type_info(&self) -> Option<&'static TypeInfo> { None } fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> { self } fn as_partial_reflect(&self) -> &dyn PartialReflect { self } fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect { self } fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> { Err(self) } fn try_as_reflect(&self) -> Option<&dyn Reflect> { None } fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { None } fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { match value.reflect_ref() { ReflectRef::Function(func) => { *self = func.to_dynamic_function(); Ok(()) } _ => Err(ApplyError::MismatchedTypes { from_type: value.reflect_type_path().into(), to_type: Self::type_path().into(), }), } } fn reflect_kind(&self) -> ReflectKind { ReflectKind::Function } fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Function(self) } fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Function(self) } fn reflect_owned(self: Box<Self>) -> ReflectOwned { ReflectOwned::Function(self) } fn reflect_hash(&self) -> Option<u64> { None } fn reflect_partial_eq(&self, _value: &dyn PartialReflect) -> Option<bool> { None } fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { Debug::fmt(self, f) } fn is_dynamic(&self) -> bool { true } } impl MaybeTyped for DynamicFunction<'static> {} impl RegisterForReflection for DynamicFunction<'static> {} impl_type_path!((in bevy_reflect) DynamicFunction<'env>); /// Outputs the function's signature. /// /// This takes the format: `DynamicFunction(fn {name}({arg1}: {type1}, {arg2}: {type2}, ...) -> {return_type})`. /// /// Names for arguments and the function itself are optional and will default to `_` if not provided. /// /// If the function is [overloaded], the output will include the signatures of all overloads as a set. /// For example, `DynamicFunction(fn add{(_: i32, _: i32) -> i32, (_: f32, _: f32) -> f32})`. /// /// [overloaded]: DynamicFunction::with_overload impl<'env> Debug for DynamicFunction<'env> { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicFunction({:?})", &self.internal) } } impl<'env> IntoFunction<'env, ()> for DynamicFunction<'env> { #[inline] fn into_function(self) -> DynamicFunction<'env> { self } } impl<'env> IntoFunctionMut<'env, ()> for DynamicFunction<'env> { #[inline] fn into_function_mut(self) -> DynamicFunctionMut<'env> { DynamicFunctionMut::from(self) } } #[cfg(test)] mod tests { use super::*; use crate::func::signature::ArgumentSignature; use crate::func::{FunctionError, IntoReturn, SignatureInfo}; use crate::Type; use alloc::{format, string::String, vec, vec::Vec}; use bevy_platform::collections::HashSet; use core::ops::Add; #[test] fn should_overwrite_function_name() { let c = 23; let func = (|a: i32, b: i32| a + b + c).into_function(); assert!(func.name().is_none()); let func = func.with_name("my_function"); assert_eq!(func.name().unwrap(), "my_function"); } #[test] fn should_convert_dynamic_function_with_into_function() { fn make_closure<'env, F: IntoFunction<'env, M>, M>(f: F) -> DynamicFunction<'env> { f.into_function() } let c = 23; let function: DynamicFunction = make_closure(|a: i32, b: i32| a + b + c); let _: DynamicFunction = make_closure(function); } #[test] fn should_return_error_on_arg_count_mismatch() { let func = (|a: i32, b: i32| a + b).into_function(); let args = ArgList::default().with_owned(25_i32); let error = func.call(args).unwrap_err(); assert_eq!( error, FunctionError::ArgCountMismatch { expected: ArgCount::new(2).unwrap(), received: 1 } ); } #[test] fn should_return_error_on_arg_count_mismatch_overloaded() { let func = (|a: i32, b: i32| a + b) .into_function() .with_overload(|a: i32, b: i32, c: i32| a + b + c); let args = ArgList::default() .with_owned(1_i32) .with_owned(2_i32) .with_owned(3_i32) .with_owned(4_i32); let error = func.call(args).unwrap_err(); let mut expected_count = ArgCount::new(2).unwrap(); expected_count.add(3); assert_eq!( error, FunctionError::ArgCountMismatch { expected: expected_count, received: 4 } ); } #[test] fn should_clone_dynamic_function() { let hello = String::from("Hello"); let greet = |name: &String| -> String { format!("{hello}, {name}!") }; let greet = greet.into_function().with_name("greet"); let clone = greet.clone(); assert_eq!(greet.name().unwrap(), "greet"); assert_eq!(clone.name().unwrap(), "greet"); let cloned_value = clone .call(ArgList::default().with_ref(&String::from("world"))) .unwrap() .unwrap_owned() .try_take::<String>() .unwrap(); assert_eq!(cloned_value, "Hello, world!"); } #[test] fn should_apply_function() { let mut func: Box<dyn Function> = Box::new((|a: i32, b: i32| a + b).into_function()); func.apply(&((|a: i32, b: i32| a * b).into_function())); let args = ArgList::new().with_owned(5_i32).with_owned(5_i32); let result = func.reflect_call(args).unwrap().unwrap_owned(); assert_eq!(result.try_take::<i32>().unwrap(), 25); } #[test] fn should_allow_recursive_dynamic_function() { let factorial = DynamicFunction::new( |mut args| { let curr = args.pop::<i32>()?; if curr == 0 { return Ok(1_i32.into_return()); } let arg = args.pop_arg()?; let this = arg.value(); match this.reflect_ref() { ReflectRef::Function(func) => { let result = func.reflect_call( ArgList::new() .with_ref(this.as_partial_reflect()) .with_owned(curr - 1), ); let value = result.unwrap().unwrap_owned().try_take::<i32>().unwrap(); Ok((curr * value).into_return()) } _ => panic!("expected function"), } }, // The `FunctionInfo` doesn't really matter for this test // so we can just give it dummy information. SignatureInfo::anonymous() .with_arg::<i32>("curr") .with_arg::<()>("this"), ); let args = ArgList::new().with_ref(&factorial).with_owned(5_i32); let value = factorial.call(args).unwrap().unwrap_owned(); assert_eq!(value.try_take::<i32>().unwrap(), 120); } #[test] fn should_allow_creating_manual_generic_dynamic_function() { let func = DynamicFunction::new( |mut args| { let a = args.take_arg()?; let b = args.take_arg()?; if a.is::<i32>() { let a = a.take::<i32>()?; let b = b.take::<i32>()?; Ok((a + b).into_return()) } else { let a = a.take::<f32>()?; let b = b.take::<f32>()?; Ok((a + b).into_return()) } }, vec![ SignatureInfo::named("add::<i32>") .with_arg::<i32>("a") .with_arg::<i32>("b") .with_return::<i32>(), SignatureInfo::named("add::<f32>") .with_arg::<f32>("a") .with_arg::<f32>("b") .with_return::<f32>(), ], ); assert_eq!(func.name().unwrap(), "add::<i32>"); let func = func.with_name("add"); assert_eq!(func.name().unwrap(), "add"); let args = ArgList::default().with_owned(25_i32).with_owned(75_i32); let result = func.call(args).unwrap().unwrap_owned(); assert_eq!(result.try_take::<i32>().unwrap(), 100); let args = ArgList::default().with_owned(25.0_f32).with_owned(75.0_f32); let result = func.call(args).unwrap().unwrap_owned(); assert_eq!(result.try_take::<f32>().unwrap(), 100.0); } #[test] #[should_panic(expected = "called `Result::unwrap()` on an `Err` value: MissingSignature")] fn should_panic_on_missing_function_info() { let _ = DynamicFunction::new(|_| Ok(().into_return()), Vec::new()); } #[test] fn should_allow_function_overloading() { fn add<T: Add<Output = T>>(a: T, b: T) -> T { a + b } let func = add::<i32>.into_function().with_overload(add::<f32>); let args = ArgList::default().with_owned(25_i32).with_owned(75_i32); let result = func.call(args).unwrap().unwrap_owned(); assert_eq!(result.try_take::<i32>().unwrap(), 100); let args = ArgList::default().with_owned(25.0_f32).with_owned(75.0_f32); let result = func.call(args).unwrap().unwrap_owned(); assert_eq!(result.try_take::<f32>().unwrap(), 100.0); } #[test] fn should_allow_variable_arguments_via_overloading() { fn add_2(a: i32, b: i32) -> i32 { a + b } fn add_3(a: i32, b: i32, c: i32) -> i32 { a + b + c } let func = add_2.into_function().with_overload(add_3); let args = ArgList::default().with_owned(25_i32).with_owned(75_i32); let result = func.call(args).unwrap().unwrap_owned(); assert_eq!(result.try_take::<i32>().unwrap(), 100); let args = ArgList::default() .with_owned(25_i32) .with_owned(75_i32) .with_owned(100_i32); let result = func.call(args).unwrap().unwrap_owned(); assert_eq!(result.try_take::<i32>().unwrap(), 200); } #[test] fn should_allow_function_overloading_with_manual_overload() { let manual = DynamicFunction::new( |mut args| { let a = args.take_arg()?; let b = args.take_arg()?; if a.is::<i32>() { let a = a.take::<i32>()?; let b = b.take::<i32>()?; Ok((a + b).into_return()) } else { let a = a.take::<f32>()?; let b = b.take::<f32>()?; Ok((a + b).into_return()) } }, vec![ SignatureInfo::named("add::<i32>") .with_arg::<i32>("a") .with_arg::<i32>("b") .with_return::<i32>(), SignatureInfo::named("add::<f32>") .with_arg::<f32>("a") .with_arg::<f32>("b") .with_return::<f32>(), ], ); let func = manual.with_overload(|a: u32, b: u32| a + b); let args = ArgList::default().with_owned(25_i32).with_owned(75_i32); let result = func.call(args).unwrap().unwrap_owned(); assert_eq!(result.try_take::<i32>().unwrap(), 100); let args = ArgList::default().with_owned(25_u32).with_owned(75_u32); let result = func.call(args).unwrap().unwrap_owned(); assert_eq!(result.try_take::<u32>().unwrap(), 100); } #[test] fn should_return_error_on_unknown_overload() { fn add<T: Add<Output = T>>(a: T, b: T) -> T { a + b } let func = add::<i32>.into_function().with_overload(add::<f32>); let args = ArgList::default().with_owned(25_u32).with_owned(75_u32); let result = func.call(args); assert_eq!( result.unwrap_err(), FunctionError::NoOverload { expected: [ ArgumentSignature::from_iter(vec![Type::of::<i32>(), Type::of::<i32>()]), ArgumentSignature::from_iter(vec![Type::of::<f32>(), Type::of::<f32>()]) ] .into_iter() .collect::<HashSet<_>>(), received: ArgumentSignature::from_iter(vec![Type::of::<u32>(), Type::of::<u32>()]), } ); } #[test] fn should_debug_dynamic_function() { fn greet(name: &String) -> String { format!("Hello, {name}!") } let function = greet.into_function(); let debug = format!("{function:?}"); assert_eq!(debug, "DynamicFunction(fn bevy_reflect::func::dynamic_function::tests::should_debug_dynamic_function::greet(_: &alloc::string::String) -> alloc::string::String)"); } #[test] fn should_debug_anonymous_dynamic_function() { let function = (|a: i32, b: i32| a + b).into_function(); let debug = format!("{function:?}"); assert_eq!(debug, "DynamicFunction(fn _(_: i32, _: i32) -> i32)"); } #[test] fn should_debug_overloaded_dynamic_function() { fn add<T: Add<Output = T>>(a: T, b: T) -> T { a + b } let function = add::<i32> .into_function() .with_overload(add::<f32>) .with_name("add"); let debug = format!("{function:?}"); assert_eq!( debug, "DynamicFunction(fn add{(_: i32, _: i32) -> i32, (_: f32, _: f32) -> f32})" ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/info.rs
crates/bevy_reflect/src/func/info.rs
use alloc::{borrow::Cow, boxed::Box, vec, vec::Vec}; use core::fmt::{Debug, Formatter}; use crate::{ func::args::{ArgCount, ArgCountOutOfBoundsError, ArgInfo, GetOwnership, Ownership}, func::signature::ArgumentSignature, func::FunctionOverloadError, type_info::impl_type_methods, Type, TypePath, }; use variadics_please::all_tuples; /// Type information for a [`DynamicFunction`] or [`DynamicFunctionMut`]. /// /// This information can be retrieved directly from certain functions and closures /// using the [`TypedFunction`] trait, and manually constructed otherwise. /// /// It is compromised of one or more [`SignatureInfo`] structs, /// allowing it to represent functions with multiple sets of arguments (i.e. "overloaded functions"). /// /// [`DynamicFunction`]: crate::func::DynamicFunction /// [`DynamicFunctionMut`]: crate::func::DynamicFunctionMut #[derive(Debug, Clone)] pub struct FunctionInfo { name: Option<Cow<'static, str>>, arg_count: ArgCount, signatures: Box<[SignatureInfo]>, } impl FunctionInfo { /// Create a new [`FunctionInfo`] for a function with the given signature. /// /// # Panics /// /// Panics if the given signature has more than the maximum number of arguments /// as specified by [`ArgCount::MAX_COUNT`]. pub fn new(signature: SignatureInfo) -> Self { Self { name: signature.name.clone(), arg_count: ArgCount::new(signature.arg_count()).unwrap(), signatures: vec![signature].into(), } } /// Create a new [`FunctionInfo`] from a set of signatures. /// /// Returns an error if the given iterator is empty or contains duplicate signatures. pub fn try_from_iter( signatures: impl IntoIterator<Item = SignatureInfo>, ) -> Result<Self, FunctionOverloadError> { let mut iter = signatures.into_iter(); let base = iter.next().ok_or(FunctionOverloadError::MissingSignature)?; if base.arg_count() > ArgCount::MAX_COUNT { return Err(FunctionOverloadError::TooManyArguments( ArgumentSignature::from(&base), )); } let mut info = Self::new(base); for signature in iter { if signature.arg_count() > ArgCount::MAX_COUNT { return Err(FunctionOverloadError::TooManyArguments( ArgumentSignature::from(&signature), )); } info = info.with_overload(signature).map_err(|sig| { FunctionOverloadError::DuplicateSignature(ArgumentSignature::from(&sig)) })?; } Ok(info) } /// The base signature for this function. /// /// All functions—including overloaded functions—are guaranteed to have at least one signature. /// The first signature used to define the [`FunctionInfo`] is considered the base signature. pub fn base(&self) -> &SignatureInfo { &self.signatures[0] } /// Whether this function is overloaded. /// /// This is determined by the existence of multiple signatures. pub fn is_overloaded(&self) -> bool { self.signatures.len() > 1 } /// Set the name of the function. pub fn with_name(mut self, name: Option<impl Into<Cow<'static, str>>>) -> Self { self.name = name.map(Into::into); self } /// The name of the function. /// /// For [`DynamicFunctions`] created using [`IntoFunction`] or [`DynamicFunctionMuts`] created using [`IntoFunctionMut`], /// the default name will always be the full path to the function as returned by [`std::any::type_name`], /// unless the function is a closure, anonymous function, or function pointer, /// in which case the name will be `None`. /// /// For overloaded functions, this will be the name of the base signature, /// unless manually overwritten using [`Self::with_name`]. /// /// [`DynamicFunctions`]: crate::func::DynamicFunction /// [`IntoFunction`]: crate::func::IntoFunction /// [`DynamicFunctionMuts`]: crate::func::DynamicFunctionMut /// [`IntoFunctionMut`]: crate::func::IntoFunctionMut pub fn name(&self) -> Option<&Cow<'static, str>> { self.name.as_ref() } /// Add a signature to this function. /// /// If a signature with the same [`ArgumentSignature`] already exists, /// an error is returned with the given signature. /// /// # Panics /// /// Panics if the given signature has more than the maximum number of arguments /// as specified by [`ArgCount::MAX_COUNT`]. pub fn with_overload(mut self, signature: SignatureInfo) -> Result<Self, SignatureInfo> { let is_duplicate = self.signatures.iter().any(|s| { s.arg_count() == signature.arg_count() && ArgumentSignature::from(s) == ArgumentSignature::from(&signature) }); if is_duplicate { return Err(signature); } self.arg_count.add(signature.arg_count()); self.signatures = IntoIterator::into_iter(self.signatures) .chain(Some(signature)) .collect(); Ok(self) } /// Returns the number of arguments the function expects. /// /// For [overloaded] functions that can have a variable number of arguments, /// this will contain the full set of counts for all signatures. /// /// [overloaded]: crate::func#overloading-functions pub fn arg_count(&self) -> ArgCount { self.arg_count } /// The signatures of the function. /// /// This is guaranteed to always contain at least one signature. /// Overloaded functions will contain two or more. pub fn signatures(&self) -> &[SignatureInfo] { &self.signatures } /// Returns a wrapper around this info that implements [`Debug`] for pretty-printing the function. /// /// This can be useful for more readable debugging and logging. /// /// # Example /// /// ``` /// # use bevy_reflect::func::{FunctionInfo, TypedFunction}; /// # /// fn add(a: i32, b: i32) -> i32 { /// a + b /// } /// /// let info = add.get_function_info(); /// /// let pretty = info.pretty_printer(); /// assert_eq!(format!("{:?}", pretty), "(_: i32, _: i32) -> i32"); /// ``` pub fn pretty_printer(&self) -> PrettyPrintFunctionInfo<'_> { PrettyPrintFunctionInfo::new(self) } /// Extend this [`FunctionInfo`] with another without checking for duplicates. /// /// # Panics /// /// Panics if the given signature has more than the maximum number of arguments /// as specified by [`ArgCount::MAX_COUNT`]. pub(super) fn extend_unchecked(&mut self, other: FunctionInfo) { if self.name.is_none() { self.name = other.name; } let signatures = core::mem::take(&mut self.signatures); self.signatures = IntoIterator::into_iter(signatures) .chain(IntoIterator::into_iter(other.signatures)) .collect(); self.arg_count = self .signatures .iter() .fold(ArgCount::default(), |mut count, sig| { count.add(sig.arg_count()); count }); } } impl TryFrom<SignatureInfo> for FunctionInfo { type Error = ArgCountOutOfBoundsError; fn try_from(signature: SignatureInfo) -> Result<Self, Self::Error> { let count = signature.arg_count(); if count > ArgCount::MAX_COUNT { return Err(ArgCountOutOfBoundsError(count)); } Ok(Self::new(signature)) } } impl TryFrom<Vec<SignatureInfo>> for FunctionInfo { type Error = FunctionOverloadError; fn try_from(signatures: Vec<SignatureInfo>) -> Result<Self, Self::Error> { Self::try_from_iter(signatures) } } impl<const N: usize> TryFrom<[SignatureInfo; N]> for FunctionInfo { type Error = FunctionOverloadError; fn try_from(signatures: [SignatureInfo; N]) -> Result<Self, Self::Error> { Self::try_from_iter(signatures) } } /// Type information for the signature of a [`DynamicFunction`] or [`DynamicFunctionMut`]. /// /// Every [`FunctionInfo`] contains one or more [`SignatureInfo`]s. /// /// [`DynamicFunction`]: crate::func::DynamicFunction /// [`DynamicFunctionMut`]: crate::func::DynamicFunctionMut #[derive(Debug, Clone)] pub struct SignatureInfo { name: Option<Cow<'static, str>>, args: Box<[ArgInfo]>, return_info: ReturnInfo, } impl SignatureInfo { /// Create a new [`SignatureInfo`] for a function with the given name. pub fn named(name: impl Into<Cow<'static, str>>) -> Self { Self { name: Some(name.into()), args: Box::new([]), return_info: ReturnInfo::new::<()>(), } } /// Create a new [`SignatureInfo`] with no name. /// /// For the purposes of debugging and [registration], /// it's recommended to use [`Self::named`] instead. /// /// [registration]: crate::func::FunctionRegistry pub fn anonymous() -> Self { Self { name: None, args: Box::new([]), return_info: ReturnInfo::new::<()>(), } } /// Set the name of the function. pub fn with_name(mut self, name: impl Into<Cow<'static, str>>) -> Self { self.name = Some(name.into()); self } /// Push an argument onto the function's argument list. /// /// The order in which this method is called matters as it will determine the index of the argument /// based on the current number of arguments. pub fn with_arg<T: TypePath + GetOwnership>( mut self, name: impl Into<Cow<'static, str>>, ) -> Self { let index = self.args.len(); self.args = IntoIterator::into_iter(self.args) .chain(Some(ArgInfo::new::<T>(index).with_name(name))) .collect(); self } /// Set the arguments of the function. /// /// This will completely replace any existing arguments. /// /// It's preferable to use [`Self::with_arg`] to add arguments to the function /// as it will automatically set the index of the argument. pub fn with_args(mut self, args: Vec<ArgInfo>) -> Self { self.args = IntoIterator::into_iter(self.args).chain(args).collect(); self } /// Set the [return information] of the function. /// /// To manually set the [`ReturnInfo`] of the function, see [`Self::with_return_info`]. /// /// [return information]: ReturnInfo pub fn with_return<T: TypePath + GetOwnership>(mut self) -> Self { self.return_info = ReturnInfo::new::<T>(); self } /// Set the [return information] of the function. /// /// This will completely replace any existing return information. /// /// For a simpler, static version of this method, see [`Self::with_return`]. /// /// [return information]: ReturnInfo pub fn with_return_info(mut self, return_info: ReturnInfo) -> Self { self.return_info = return_info; self } /// The name of the function. /// /// For [`DynamicFunctions`] created using [`IntoFunction`] or [`DynamicFunctionMuts`] created using [`IntoFunctionMut`], /// the default name will always be the full path to the function as returned by [`core::any::type_name`], /// unless the function is a closure, anonymous function, or function pointer, /// in which case the name will be `None`. /// /// [`DynamicFunctions`]: crate::func::DynamicFunction /// [`IntoFunction`]: crate::func::IntoFunction /// [`DynamicFunctionMuts`]: crate::func::DynamicFunctionMut /// [`IntoFunctionMut`]: crate::func::IntoFunctionMut pub fn name(&self) -> Option<&Cow<'static, str>> { self.name.as_ref() } /// The arguments of the function. pub fn args(&self) -> &[ArgInfo] { &self.args } /// The number of arguments the function takes. pub fn arg_count(&self) -> usize { self.args.len() } /// The return information of the function. pub fn return_info(&self) -> &ReturnInfo { &self.return_info } } /// Information about the return type of a [`DynamicFunction`] or [`DynamicFunctionMut`]. /// /// [`DynamicFunction`]: crate::func::DynamicFunction /// [`DynamicFunctionMut`]: crate::func::DynamicFunctionMut #[derive(Debug, Clone)] pub struct ReturnInfo { ty: Type, ownership: Ownership, } impl ReturnInfo { /// Create a new [`ReturnInfo`] representing the given type, `T`. pub fn new<T: TypePath + GetOwnership>() -> Self { Self { ty: Type::of::<T>(), ownership: T::ownership(), } } impl_type_methods!(ty); /// The ownership of this type. pub fn ownership(&self) -> Ownership { self.ownership } } /// A wrapper around [`FunctionInfo`] that implements [`Debug`] for pretty-printing function information. /// /// # Example /// /// ``` /// # use bevy_reflect::func::{FunctionInfo, PrettyPrintFunctionInfo, TypedFunction}; /// # /// fn add(a: i32, b: i32) -> i32 { /// a + b /// } /// /// let info = add.get_function_info(); /// /// let pretty = PrettyPrintFunctionInfo::new(&info); /// assert_eq!(format!("{:?}", pretty), "(_: i32, _: i32) -> i32"); /// ``` pub struct PrettyPrintFunctionInfo<'a> { info: &'a FunctionInfo, include_fn_token: bool, include_name: bool, } impl<'a> PrettyPrintFunctionInfo<'a> { /// Create a new pretty-printer for the given [`FunctionInfo`]. pub fn new(info: &'a FunctionInfo) -> Self { Self { info, include_fn_token: false, include_name: false, } } /// Include the function name in the pretty-printed output. pub fn include_name(mut self) -> Self { self.include_name = true; self } /// Include the `fn` token in the pretty-printed output. pub fn include_fn_token(mut self) -> Self { self.include_fn_token = true; self } } impl<'a> Debug for PrettyPrintFunctionInfo<'a> { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { if self.include_fn_token { write!(f, "fn")?; if self.include_name { write!(f, " ")?; } } match (self.include_name, self.info.name()) { (true, Some(name)) => write!(f, "{name}")?, (true, None) => write!(f, "_")?, _ => {} } if self.info.is_overloaded() { // `{(arg0: i32, arg1: i32) -> (), (arg0: f32, arg1: f32) -> ()}` let mut set = f.debug_set(); for signature in self.info.signatures() { set.entry(&PrettyPrintSignatureInfo::new(signature)); } set.finish() } else { // `(arg0: i32, arg1: i32) -> ()` PrettyPrintSignatureInfo::new(self.info.base()).fmt(f) } } } /// A wrapper around [`SignatureInfo`] that implements [`Debug`] for pretty-printing function signature information. /// /// # Example /// /// ``` /// # use bevy_reflect::func::{FunctionInfo, PrettyPrintSignatureInfo, TypedFunction}; /// # /// fn add(a: i32, b: i32) -> i32 { /// a + b /// } /// /// let info = add.get_function_info(); /// /// let pretty = PrettyPrintSignatureInfo::new(info.base()); /// assert_eq!(format!("{:?}", pretty), "(_: i32, _: i32) -> i32"); /// ``` pub struct PrettyPrintSignatureInfo<'a> { info: &'a SignatureInfo, include_fn_token: bool, include_name: bool, } impl<'a> PrettyPrintSignatureInfo<'a> { /// Create a new pretty-printer for the given [`SignatureInfo`]. pub fn new(info: &'a SignatureInfo) -> Self { Self { info, include_fn_token: false, include_name: false, } } /// Include the function name in the pretty-printed output. pub fn include_name(mut self) -> Self { self.include_name = true; self } /// Include the `fn` token in the pretty-printed output. pub fn include_fn_token(mut self) -> Self { self.include_fn_token = true; self } } impl<'a> Debug for PrettyPrintSignatureInfo<'a> { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { if self.include_fn_token { write!(f, "fn")?; if self.include_name { write!(f, " ")?; } } match (self.include_name, self.info.name()) { (true, Some(name)) => write!(f, "{name}")?, (true, None) => write!(f, "_")?, _ => {} } write!(f, "(")?; // We manually write the args instead of using `DebugTuple` to avoid trailing commas // and (when used with `{:#?}`) unnecessary newlines for (index, arg) in self.info.args().iter().enumerate() { if index > 0 { write!(f, ", ")?; } let name = arg.name().unwrap_or("_"); let ty = arg.type_path(); write!(f, "{name}: {ty}")?; } let ret = self.info.return_info().type_path(); write!(f, ") -> {ret}") } } /// A static accessor to compile-time type information for functions. /// /// This is the equivalent of [`Typed`], but for function. /// /// # Blanket Implementation /// /// This trait has a blanket implementation that covers: /// - Functions and methods defined with the `fn` keyword /// - Anonymous functions /// - Function pointers /// - Closures that capture immutable references to their environment /// - Closures that capture mutable references to their environment /// - Closures that take ownership of captured variables /// /// For each of the above cases, the function signature may only have up to 15 arguments, /// not including an optional receiver argument (often `&self` or `&mut self`). /// This optional receiver argument may be either a mutable or immutable reference to a type. /// If the return type is also a reference, its lifetime will be bound to the lifetime of this receiver. /// /// See the [module-level documentation] for more information on valid signatures. /// /// Arguments and the return type are expected to implement both [`GetOwnership`] and [`TypePath`]. /// By default, these traits are automatically implemented when using the `Reflect` [derive macro]. /// /// # Example /// /// ``` /// # use bevy_reflect::func::{ArgList, ReflectFnMut, TypedFunction}; /// # /// fn print(value: String) { /// println!("{}", value); /// } /// /// let info = print.get_function_info(); /// assert!(info.name().unwrap().ends_with("print")); /// assert!(info.arg_count().contains(1)); /// assert_eq!(info.base().args()[0].type_path(), "alloc::string::String"); /// assert_eq!(info.base().return_info().type_path(), "()"); /// ``` /// /// # Trait Parameters /// /// This trait has a `Marker` type parameter that is used to get around issues with /// [unconstrained type parameters] when defining impls with generic arguments or return types. /// This `Marker` can be any type, provided it doesn't conflict with other implementations. /// /// [module-level documentation]: crate::func /// [`Typed`]: crate::Typed /// [unconstrained type parameters]: https://doc.rust-lang.org/error_codes/E0207.html pub trait TypedFunction<Marker> { /// Get the [`FunctionInfo`] for this type. fn function_info() -> FunctionInfo; /// Get the [`FunctionInfo`] for this type. fn get_function_info(&self) -> FunctionInfo { Self::function_info() } } /// Helper macro for implementing [`TypedFunction`] on Rust functions. /// /// This currently implements it for the following signatures (where `ArgX` may be any of `T`, `&T`, or `&mut T`): /// - `FnMut(Arg0, Arg1, ..., ArgN) -> R` /// - `FnMut(&Receiver, Arg0, Arg1, ..., ArgN) -> &R` /// - `FnMut(&mut Receiver, Arg0, Arg1, ..., ArgN) -> &mut R` /// - `FnMut(&mut Receiver, Arg0, Arg1, ..., ArgN) -> &R` macro_rules! impl_typed_function { ($($Arg:ident),*) => { // === (...) -> ReturnType === // impl<$($Arg,)* ReturnType, Function> TypedFunction<fn($($Arg),*) -> [ReturnType]> for Function where $($Arg: TypePath + GetOwnership,)* ReturnType: TypePath + GetOwnership, Function: FnMut($($Arg),*) -> ReturnType, { fn function_info() -> FunctionInfo { FunctionInfo::new( create_info::<Function>() .with_args({ let mut _index = 0; vec![ $(ArgInfo::new::<$Arg>({ _index += 1; _index - 1 }),)* ] }) .with_return_info(ReturnInfo::new::<ReturnType>()) ) } } // === (&self, ...) -> &ReturnType === // impl<Receiver, $($Arg,)* ReturnType, Function> TypedFunction<fn(&Receiver, $($Arg),*) -> &ReturnType> for Function where for<'a> &'a Receiver: TypePath + GetOwnership, $($Arg: TypePath + GetOwnership,)* for<'a> &'a ReturnType: TypePath + GetOwnership, Function: for<'a> FnMut(&'a Receiver, $($Arg),*) -> &'a ReturnType, { fn function_info() -> FunctionInfo { FunctionInfo::new( create_info::<Function>() .with_args({ let mut _index = 1; vec![ ArgInfo::new::<&Receiver>(0), $($crate::func::args::ArgInfo::new::<$Arg>({ _index += 1; _index - 1 }),)* ] }) .with_return_info(ReturnInfo::new::<&ReturnType>()) ) } } // === (&mut self, ...) -> &mut ReturnType === // impl<Receiver, $($Arg,)* ReturnType, Function> TypedFunction<fn(&mut Receiver, $($Arg),*) -> &mut ReturnType> for Function where for<'a> &'a mut Receiver: TypePath + GetOwnership, $($Arg: TypePath + GetOwnership,)* for<'a> &'a mut ReturnType: TypePath + GetOwnership, Function: for<'a> FnMut(&'a mut Receiver, $($Arg),*) -> &'a mut ReturnType, { fn function_info() -> FunctionInfo { FunctionInfo::new( create_info::<Function>() .with_args({ let mut _index = 1; vec![ ArgInfo::new::<&mut Receiver>(0), $(ArgInfo::new::<$Arg>({ _index += 1; _index - 1 }),)* ] }) .with_return_info(ReturnInfo::new::<&mut ReturnType>()) ) } } // === (&mut self, ...) -> &ReturnType === // impl<Receiver, $($Arg,)* ReturnType, Function> TypedFunction<fn(&mut Receiver, $($Arg),*) -> &ReturnType> for Function where for<'a> &'a mut Receiver: TypePath + GetOwnership, $($Arg: TypePath + GetOwnership,)* for<'a> &'a ReturnType: TypePath + GetOwnership, Function: for<'a> FnMut(&'a mut Receiver, $($Arg),*) -> &'a ReturnType, { fn function_info() -> FunctionInfo { FunctionInfo::new( create_info::<Function>() .with_args({ let mut _index = 1; vec![ ArgInfo::new::<&mut Receiver>(0), $(ArgInfo::new::<$Arg>({ _index += 1; _index - 1 }),)* ] }) .with_return_info(ReturnInfo::new::<&ReturnType>()) ) } } }; } all_tuples!(impl_typed_function, 0, 15, Arg); /// Helper function for creating [`FunctionInfo`] with the proper name value. /// /// Names are only given if: /// - The function is not a closure /// - The function is not a function pointer /// - The function is not an anonymous function /// /// This function relies on the [`type_name`] of `F` to determine this. /// The following table describes the behavior for different types of functions: /// /// | Category | `type_name` | `FunctionInfo::name` | /// | ------------------ | ----------------------- | ----------------------- | /// | Named function | `foo::bar::baz` | `Some("foo::bar::baz")` | /// | Closure | `foo::bar::{{closure}}` | `None` | /// | Anonymous function | `foo::bar::{{closure}}` | `None` | /// | Function pointer | `fn() -> String` | `None` | /// /// [`type_name`]: core::any::type_name fn create_info<F>() -> SignatureInfo { let name = core::any::type_name::<F>(); if name.ends_with("{{closure}}") || name.starts_with("fn(") { SignatureInfo::anonymous() } else { SignatureInfo::named(name) } } #[cfg(test)] mod tests { use super::*; #[test] fn should_create_function_info() { fn add(a: i32, b: i32) -> i32 { a + b } // Sanity check: assert_eq!( core::any::type_name_of_val(&add), "bevy_reflect::func::info::tests::should_create_function_info::add" ); let info = add.get_function_info(); assert_eq!( info.name().unwrap(), "bevy_reflect::func::info::tests::should_create_function_info::add" ); assert_eq!(info.base().arg_count(), 2); assert_eq!(info.base().args()[0].type_path(), "i32"); assert_eq!(info.base().args()[1].type_path(), "i32"); assert_eq!(info.base().return_info().type_path(), "i32"); } #[test] fn should_create_function_pointer_info() { fn add(a: i32, b: i32) -> i32 { a + b } let add = add as fn(i32, i32) -> i32; // Sanity check: assert_eq!(core::any::type_name_of_val(&add), "fn(i32, i32) -> i32"); let info = add.get_function_info(); assert!(info.name().is_none()); assert_eq!(info.base().arg_count(), 2); assert_eq!(info.base().args()[0].type_path(), "i32"); assert_eq!(info.base().args()[1].type_path(), "i32"); assert_eq!(info.base().return_info().type_path(), "i32"); } #[test] fn should_create_anonymous_function_info() { let add = |a: i32, b: i32| a + b; // Sanity check: assert_eq!( core::any::type_name_of_val(&add), "bevy_reflect::func::info::tests::should_create_anonymous_function_info::{{closure}}" ); let info = add.get_function_info(); assert!(info.name().is_none()); assert_eq!(info.base().arg_count(), 2); assert_eq!(info.base().args()[0].type_path(), "i32"); assert_eq!(info.base().args()[1].type_path(), "i32"); assert_eq!(info.base().return_info().type_path(), "i32"); } #[test] fn should_create_closure_info() { let mut total = 0; let add = |a: i32, b: i32| total = a + b; // Sanity check: assert_eq!( core::any::type_name_of_val(&add), "bevy_reflect::func::info::tests::should_create_closure_info::{{closure}}" ); let info = add.get_function_info(); assert!(info.name().is_none()); assert_eq!(info.base().arg_count(), 2); assert_eq!(info.base().args()[0].type_path(), "i32"); assert_eq!(info.base().args()[1].type_path(), "i32"); assert_eq!(info.base().return_info().type_path(), "()"); } #[test] fn should_pretty_print_info() { // fn add(a: i32, b: i32) -> i32 { // a + b // } // // let info = add.get_function_info().with_name("add"); // // let pretty = info.pretty_printer(); // assert_eq!(format!("{:?}", pretty), "(_: i32, _: i32) -> i32"); // // let pretty = info.pretty_printer().include_fn_token(); // assert_eq!(format!("{:?}", pretty), "fn(_: i32, _: i32) -> i32"); // // let pretty = info.pretty_printer().include_name(); // assert_eq!(format!("{:?}", pretty), "add(_: i32, _: i32) -> i32"); // // let pretty = info.pretty_printer().include_fn_token().include_name(); // assert_eq!(format!("{:?}", pretty), "fn add(_: i32, _: i32) -> i32"); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/function.rs
crates/bevy_reflect/src/func/function.rs
use crate::{ func::{ args::{ArgCount, ArgList}, DynamicFunction, FunctionInfo, FunctionResult, }, PartialReflect, }; use alloc::borrow::Cow; use core::fmt::Debug; /// A trait used to power [function-like] operations via [reflection]. /// /// This trait allows types to be called like regular functions /// with [`Reflect`]-based [arguments] and return values. /// /// By default, this trait is currently only implemented for [`DynamicFunction`], /// however, it is possible to implement this trait for custom function-like types. /// /// # Example /// /// ``` /// # use bevy_reflect::func::{IntoFunction, ArgList, Function}; /// fn add(a: i32, b: i32) -> i32 { /// a + b /// } /// /// let func: Box<dyn Function> = Box::new(add.into_function()); /// let args = ArgList::new().with_owned(25_i32).with_owned(75_i32); /// let value = func.reflect_call(args).unwrap().unwrap_owned(); /// assert_eq!(value.try_take::<i32>().unwrap(), 100); /// ``` /// /// [function-like]: crate::func /// [reflection]: crate::Reflect /// [`Reflect`]: crate::Reflect /// [arguments]: crate::func::args /// [`DynamicFunction`]: crate::func::DynamicFunction pub trait Function: PartialReflect + Debug { /// The name of the function, if any. /// /// For [`DynamicFunctions`] created using [`IntoFunction`], /// the default name will always be the full path to the function as returned by [`core::any::type_name`], /// unless the function is a closure, anonymous function, or function pointer, /// in which case the name will be `None`. /// /// [`DynamicFunctions`]: crate::func::DynamicFunction /// [`IntoFunction`]: crate::func::IntoFunction fn name(&self) -> Option<&Cow<'static, str>>; /// Returns the number of arguments the function expects. /// /// For [overloaded] functions that can have a variable number of arguments, /// this will contain the full set of counts for all signatures. /// /// [overloaded]: crate::func#overloading-functions fn arg_count(&self) -> ArgCount { self.info().arg_count() } /// The [`FunctionInfo`] for this function. fn info(&self) -> &FunctionInfo; /// Call this function with the given arguments. fn reflect_call<'a>(&self, args: ArgList<'a>) -> FunctionResult<'a>; /// Creates a new [`DynamicFunction`] from this function. fn to_dynamic_function(&self) -> DynamicFunction<'static>; } #[cfg(test)] mod tests { use super::*; use crate::func::IntoFunction; use alloc::boxed::Box; #[test] fn should_call_dyn_function() { fn add(a: i32, b: i32) -> i32 { a + b } let func: Box<dyn Function> = Box::new(add.into_function()); let args = ArgList::new().with_owned(25_i32).with_owned(75_i32); let value = func.reflect_call(args).unwrap().unwrap_owned(); assert_eq!(value.try_take::<i32>().unwrap(), 100); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/error.rs
crates/bevy_reflect/src/func/error.rs
use crate::func::signature::ArgumentSignature; use crate::func::{ args::{ArgCount, ArgError}, Return, }; use alloc::borrow::Cow; use bevy_platform::collections::HashSet; use thiserror::Error; /// An error that occurs when calling a [`DynamicFunction`] or [`DynamicFunctionMut`]. /// /// [`DynamicFunction`]: crate::func::DynamicFunction /// [`DynamicFunctionMut`]: crate::func::DynamicFunctionMut #[derive(Debug, Error, PartialEq)] pub enum FunctionError { /// An error occurred while converting an argument. #[error(transparent)] ArgError(#[from] ArgError), /// The number of arguments provided does not match the expected number. #[error("received {received} arguments but expected one of {expected:?}")] ArgCountMismatch { /// Expected argument count. [`ArgCount`] for overloaded functions will contain multiple possible counts. expected: ArgCount, /// Number of arguments received. received: usize, }, /// No overload was found for the given set of arguments. #[error("no overload found for arguments with signature `{received:?}`, expected one of `{expected:?}`")] NoOverload { /// The set of available argument signatures. expected: HashSet<ArgumentSignature>, /// The received argument signature. received: ArgumentSignature, }, } /// The result of calling a [`DynamicFunction`] or [`DynamicFunctionMut`]. /// /// Returns `Ok(value)` if the function was called successfully, /// where `value` is the [`Return`] value of the function. /// /// [`DynamicFunction`]: crate::func::DynamicFunction /// [`DynamicFunctionMut`]: crate::func::DynamicFunctionMut pub type FunctionResult<'a> = Result<Return<'a>, FunctionError>; /// An error that occurs when attempting to add a function overload. #[derive(Debug, Error, PartialEq)] pub enum FunctionOverloadError { /// A [`SignatureInfo`] was expected, but none was found. /// /// [`SignatureInfo`]: crate::func::info::SignatureInfo #[error("expected at least one `SignatureInfo` but found none")] MissingSignature, /// An error that occurs when attempting to add a function overload with a duplicate signature. #[error("could not add function overload: duplicate found for signature `{0:?}`")] DuplicateSignature(ArgumentSignature), /// An attempt was made to add an overload with more than [`ArgCount::MAX_COUNT`] arguments. /// /// [`ArgCount::MAX_COUNT`]: crate::func::args::ArgCount #[error( "argument signature `{:?}` has too many arguments (max {})", 0, ArgCount::MAX_COUNT )] TooManyArguments(ArgumentSignature), } /// An error that occurs when registering a function into a [`FunctionRegistry`]. /// /// [`FunctionRegistry`]: crate::func::FunctionRegistry #[derive(Debug, Error, PartialEq)] pub enum FunctionRegistrationError { /// A function with the given name has already been registered. /// /// Contains the duplicate function name. #[error("a function has already been registered with name {0:?}")] DuplicateName(Cow<'static, str>), /// The function is missing a name by which it can be registered. #[error("function name is missing")] MissingName, }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/macros.rs
crates/bevy_reflect/src/func/macros.rs
/// Helper macro to implement the necessary traits for function reflection. /// /// This macro calls the following macros: /// - [`impl_get_ownership`](crate::func::args::impl_get_ownership) /// - [`impl_from_arg`](crate::func::args::impl_from_arg) /// - [`impl_into_return`](crate::func::impl_into_return) /// /// # Syntax /// /// For non-generic types, the macro simply expects the type: /// /// ```ignore /// impl_function_traits!(foo::bar::Baz); /// ``` /// /// For generic types, however, the generic type parameters must also be given in angle brackets (`<` and `>`): /// /// ```ignore /// impl_function_traits!(foo::bar::Baz<T, U>; <T: Clone, U>); /// ``` /// /// For generic const parameters, they must be given in square brackets (`[` and `]`): /// /// ```ignore /// impl_function_traits!(foo::bar::Baz<T, N>; <T> [const N: usize]); /// ``` macro_rules! impl_function_traits { ( $ty: ty $(; < $($T: ident $(: $T1: tt $(+ $T2: tt)*)?),* > )? $( [ $(const $N: ident : $size: ident),* ] )? $( where $($U: ty $(: $U1: tt $(+ $U2: tt)*)?),* )? ) => { $crate::func::args::impl_get_ownership!( $ty $(; < $($T $(: $T1 $(+ $T2)*)?),* > )? $( [ $(const $N : $size),* ] )? $( where $($U $(: $U1 $(+ $U2)*)?),* )? ); $crate::func::args::impl_from_arg!( $ty $(; < $($T $(: $T1 $(+ $T2)*)?),* > )? $( [ $(const $N : $size),* ] )? $( where $($U $(: $U1 $(+ $U2)*)?),* )? ); $crate::func::impl_into_return!( $ty $(; < $($T $(: $T1 $(+ $T2)*)?),* > )? $( [ $(const $N : $size),* ] )? $( where $($U $(: $U1 $(+ $U2)*)?),* )? ); }; } pub(crate) use impl_function_traits; /// Helper macro that returns the number of tokens it receives. /// /// See [here] for details. /// /// [here]: https://veykril.github.io/tlborm/decl-macros/building-blocks/counting.html#bit-twiddling macro_rules! count_tokens { () => { 0 }; ($odd:tt $($a:tt $b:tt)*) => { ($crate::func::macros::count_tokens!($($a)*) << 1) | 1 }; ($($a:tt $even:tt)*) => { $crate::func::macros::count_tokens!($($a)*) << 1 }; } pub(crate) use count_tokens;
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/registry.rs
crates/bevy_reflect/src/func/registry.rs
use alloc::borrow::Cow; use bevy_platform::{ collections::HashMap, sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard}, }; use core::fmt::Debug; use crate::func::{ ArgList, DynamicFunction, FunctionRegistrationError, FunctionResult, IntoFunction, }; /// A registry of [reflected functions]. /// /// This is the function-equivalent to the [`TypeRegistry`]. /// /// All functions must be `'static` as they are stored as [`DynamicFunction<'static>`]. /// /// [reflected functions]: crate::func /// [`TypeRegistry`]: crate::TypeRegistry #[derive(Default)] pub struct FunctionRegistry { /// Maps function [names] to their respective [`DynamicFunctions`]. /// /// [names]: DynamicFunction::name /// [`DynamicFunctions`]: DynamicFunction functions: HashMap<Cow<'static, str>, DynamicFunction<'static>>, } impl FunctionRegistry { /// Attempts to register the given function. /// /// This function accepts both functions that satisfy [`IntoFunction`] /// and direct [`DynamicFunction`] instances. /// The given function will internally be stored as a [`DynamicFunction<'static>`] /// and mapped according to its [name]. /// /// Because the function must have a name, /// anonymous functions (e.g. `|a: i32, b: i32| { a + b }`) and closures must instead /// be registered using [`register_with_name`] or manually converted to a [`DynamicFunction`] /// and named using [`DynamicFunction::with_name`]. /// Failure to do so will result in an error being returned. /// /// If a registered function with the same name already exists, /// it will not be registered again and an error will be returned. /// To register the function anyway, overwriting any existing registration, /// use [`overwrite_registration`] instead. /// /// # Examples /// /// ``` /// # use bevy_reflect::func::{FunctionRegistrationError, FunctionRegistry}; /// fn add(a: i32, b: i32) -> i32 { /// a + b /// } /// /// # fn main() -> Result<(), FunctionRegistrationError> { /// let mut registry = FunctionRegistry::default(); /// registry.register(add)?; /// # Ok(()) /// # } /// ``` /// /// Functions cannot be registered more than once. /// /// ``` /// # use bevy_reflect::func::{FunctionRegistrationError, FunctionRegistry, IntoFunction}; /// fn add(a: i32, b: i32) -> i32 { /// a + b /// } /// /// let mut registry = FunctionRegistry::default(); /// registry.register(add).unwrap(); /// /// let result = registry.register(add); /// assert!(matches!(result, Err(FunctionRegistrationError::DuplicateName(_)))); /// /// // Note that this simply relies on the name of the function to determine uniqueness. /// // You can rename the function to register a separate instance of it. /// let result = registry.register(add.into_function().with_name("add2")); /// assert!(result.is_ok()); /// ``` /// /// Anonymous functions and closures should be registered using [`register_with_name`] or given a name using [`DynamicFunction::with_name`]. /// /// ``` /// # use bevy_reflect::func::{FunctionRegistrationError, FunctionRegistry, IntoFunction}; /// /// let anonymous = || -> i32 { 123 }; /// /// let mut registry = FunctionRegistry::default(); /// /// let result = registry.register(|a: i32, b: i32| a + b); /// assert!(matches!(result, Err(FunctionRegistrationError::MissingName))); /// /// let result = registry.register_with_name("my_crate::add", |a: i32, b: i32| a + b); /// assert!(result.is_ok()); /// /// let result = registry.register((|a: i32, b: i32| a * b).into_function().with_name("my_crate::mul")); /// assert!(result.is_ok()); /// ``` /// /// [name]: DynamicFunction::name /// [`register_with_name`]: Self::register_with_name /// [`overwrite_registration`]: Self::overwrite_registration pub fn register<F, Marker>( &mut self, function: F, ) -> Result<&mut Self, FunctionRegistrationError> where F: IntoFunction<'static, Marker> + 'static, { let function = function.into_function(); let name = function .name() .ok_or(FunctionRegistrationError::MissingName)? .clone(); self.functions .try_insert(name, function.into_function()) .map_err(|err| FunctionRegistrationError::DuplicateName(err.entry.key().clone()))?; Ok(self) } /// Attempts to register the given function with the given name. /// /// This function accepts both functions that satisfy [`IntoFunction`] /// and direct [`DynamicFunction`] instances. /// The given function will internally be stored as a [`DynamicFunction<'static>`] /// with its [name] set to the given name. /// /// For named functions (e.g. `fn add(a: i32, b: i32) -> i32 { a + b }`) where a custom name is not needed, /// it's recommended to use [`register`] instead as the generated name is guaranteed to be unique. /// /// If a registered function with the same name already exists, /// it will not be registered again and an error will be returned. /// To register the function anyway, overwriting any existing registration, /// use [`overwrite_registration_with_name`] instead. /// /// To avoid conflicts, it's recommended to use a unique name for the function. /// This can be achieved by "namespacing" the function with a unique identifier, /// such as the name of your crate. /// /// For example, to register a function, `add`, from a crate, `my_crate`, /// you could use the name, `"my_crate::add"`. /// /// Another approach could be to use the [type name] of the function, /// however, it should be noted that anonymous functions and closures /// are not guaranteed to have unique type names. /// /// This method is a convenience around calling [`IntoFunction::into_function`] and [`DynamicFunction::with_name`] /// on the function and inserting it into the registry using the [`register`] method. /// /// # Examples /// /// ``` /// # use bevy_reflect::func::{FunctionRegistrationError, FunctionRegistry}; /// # fn main() -> Result<(), FunctionRegistrationError> { /// fn mul(a: i32, b: i32) -> i32 { /// a * b /// } /// /// let div = |a: i32, b: i32| a / b; /// /// let mut registry = FunctionRegistry::default(); /// registry /// // Registering an anonymous function with a unique name /// .register_with_name("my_crate::add", |a: i32, b: i32| { /// a + b /// })? /// // Registering an existing function with its type name /// .register_with_name(core::any::type_name_of_val(&mul), mul)? /// // Registering an existing function with a custom name /// .register_with_name("my_crate::mul", mul)?; /// /// // Be careful not to register anonymous functions with their type name. /// // This code works but registers the function with a non-unique name like `foo::bar::{{closure}}` /// registry.register_with_name(core::any::type_name_of_val(&div), div)?; /// # Ok(()) /// # } /// ``` /// /// Names must be unique. /// /// ```should_panic /// # use bevy_reflect::func::FunctionRegistry; /// fn one() {} /// fn two() {} /// /// let mut registry = FunctionRegistry::default(); /// registry.register_with_name("my_function", one).unwrap(); /// /// // Panic! A function has already been registered with the name "my_function" /// registry.register_with_name("my_function", two).unwrap(); /// ``` /// /// [name]: DynamicFunction::name /// [`register`]: Self::register /// [`overwrite_registration_with_name`]: Self::overwrite_registration_with_name /// [type name]: core::any::type_name pub fn register_with_name<F, Marker>( &mut self, name: impl Into<Cow<'static, str>>, function: F, ) -> Result<&mut Self, FunctionRegistrationError> where F: IntoFunction<'static, Marker> + 'static, { let function = function.into_function().with_name(name); self.register(function) } /// Registers the given function, overwriting any existing registration. /// /// This function accepts both functions that satisfy [`IntoFunction`] /// and direct [`DynamicFunction`] instances. /// The given function will internally be stored as a [`DynamicFunction<'static>`] /// and mapped according to its [name]. /// /// Because the function must have a name, /// anonymous functions (e.g. `|a: i32, b: i32| { a + b }`) and closures must instead /// be registered using [`overwrite_registration_with_name`] or manually converted to a [`DynamicFunction`] /// and named using [`DynamicFunction::with_name`]. /// Failure to do so will result in an error being returned. /// /// To avoid overwriting existing registrations, /// it's recommended to use the [`register`] method instead. /// /// Returns the previous function with the same name, if any. /// /// [name]: DynamicFunction::name /// [`overwrite_registration_with_name`]: Self::overwrite_registration_with_name /// [`register`]: Self::register pub fn overwrite_registration<F, Marker>( &mut self, function: F, ) -> Result<Option<DynamicFunction<'static>>, FunctionRegistrationError> where F: IntoFunction<'static, Marker> + 'static, { let function = function.into_function(); let name = function .name() .ok_or(FunctionRegistrationError::MissingName)? .clone(); Ok(self.functions.insert(name, function)) } /// Registers the given function, overwriting any existing registration. /// /// This function accepts both functions that satisfy [`IntoFunction`] /// and direct [`DynamicFunction`] instances. /// The given function will internally be stored as a [`DynamicFunction<'static>`] /// with its [name] set to the given name. /// /// Functions are mapped according to their name. /// To avoid overwriting existing registrations, /// it's recommended to use the [`register_with_name`] method instead. /// /// This method is a convenience around calling [`IntoFunction::into_function`] and [`DynamicFunction::with_name`] /// on the function and inserting it into the registry using the [`overwrite_registration`] method. /// /// Returns the previous function with the same name, if any. /// /// [name]: DynamicFunction::name /// [`register_with_name`]: Self::register_with_name /// [`overwrite_registration`]: Self::overwrite_registration pub fn overwrite_registration_with_name<F, Marker>( &mut self, name: impl Into<Cow<'static, str>>, function: F, ) -> Option<DynamicFunction<'static>> where F: IntoFunction<'static, Marker> + 'static, { let function = function.into_function().with_name(name); match self.overwrite_registration(function) { Ok(existing) => existing, Err(FunctionRegistrationError::MissingName) => { unreachable!("the function should have a name") } Err(FunctionRegistrationError::DuplicateName(_)) => { unreachable!("should overwrite functions with the same name") } } } /// Calls the function with the given [name] and [args]. /// /// Returns `None` if no function with the given name is registered. /// Otherwise, returns the result of the function call. /// /// [name]: DynamicFunction::name /// [args]: ArgList pub fn call<'a>(&self, name: &str, args: ArgList<'a>) -> Option<FunctionResult<'a>> { let func = self.get(name)?; Some(func.call(args)) } /// Get a reference to a registered function by [name]. /// /// [name]: DynamicFunction::name pub fn get(&self, name: &str) -> Option<&DynamicFunction<'static>> { self.functions.get(name) } /// Returns `true` if a function with the given [name] is registered. /// /// [name]: DynamicFunction::name pub fn contains(&self, name: &str) -> bool { self.functions.contains_key(name) } /// Returns an iterator over all registered functions. pub fn iter(&self) -> impl ExactSizeIterator<Item = &DynamicFunction<'static>> { self.functions.values() } /// Returns the number of registered functions. pub fn len(&self) -> usize { self.functions.len() } /// Returns `true` if no functions are registered. pub fn is_empty(&self) -> bool { self.functions.is_empty() } } impl Debug for FunctionRegistry { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_set().entries(self.functions.values()).finish() } } /// A synchronized wrapper around a [`FunctionRegistry`]. #[derive(Clone, Default, Debug)] pub struct FunctionRegistryArc { /// The wrapped [`FunctionRegistry`]. pub internal: Arc<RwLock<FunctionRegistry>>, } impl FunctionRegistryArc { /// Takes a read lock on the underlying [`FunctionRegistry`]. pub fn read(&self) -> RwLockReadGuard<'_, FunctionRegistry> { self.internal.read().unwrap_or_else(PoisonError::into_inner) } /// Takes a write lock on the underlying [`FunctionRegistry`]. pub fn write(&self) -> RwLockWriteGuard<'_, FunctionRegistry> { self.internal .write() .unwrap_or_else(PoisonError::into_inner) } } #[cfg(test)] mod tests { use super::*; use crate::func::{ArgList, IntoFunction}; use alloc::format; #[test] fn should_register_function() { fn foo() -> i32 { 123 } let mut registry = FunctionRegistry::default(); registry.register(foo).unwrap(); let function = registry.get(core::any::type_name_of_val(&foo)).unwrap(); let value = function.call(ArgList::new()).unwrap().unwrap_owned(); assert_eq!(value.try_downcast_ref::<i32>(), Some(&123)); } #[test] fn should_register_anonymous_function() { let mut registry = FunctionRegistry::default(); registry.register_with_name("foo", || 123_i32).unwrap(); let function = registry.get("foo").unwrap(); let value = function.call(ArgList::new()).unwrap().unwrap_owned(); assert_eq!(value.try_downcast_ref::<i32>(), Some(&123)); } #[test] fn should_register_closure() { let value = 123; let foo = move || -> i32 { value }; let mut registry = FunctionRegistry::default(); registry.register_with_name("foo", foo).unwrap(); let function = registry.get("foo").unwrap(); let value = function.call(ArgList::new()).unwrap().unwrap_owned(); assert_eq!(value.try_downcast_ref::<i32>(), Some(&123)); } #[test] fn should_register_dynamic_function() { fn foo() -> i32 { 123 } let function = foo.into_function().with_name("custom_name"); let mut registry = FunctionRegistry::default(); registry.register(function).unwrap(); let function = registry.get("custom_name").unwrap(); let value = function.call(ArgList::new()).unwrap().unwrap_owned(); assert_eq!(value.try_downcast_ref::<i32>(), Some(&123)); } #[test] fn should_register_dynamic_closure() { let value = 123; let foo = move || -> i32 { value }; let function = foo.into_function().with_name("custom_name"); let mut registry = FunctionRegistry::default(); registry.register(function).unwrap(); let function = registry.get("custom_name").unwrap(); let value = function.call(ArgList::new()).unwrap().unwrap_owned(); assert_eq!(value.try_downcast_ref::<i32>(), Some(&123)); } #[test] fn should_only_register_function_once() { fn foo() -> i32 { 123 } fn bar() -> i32 { 321 } let name = core::any::type_name_of_val(&foo); let mut registry = FunctionRegistry::default(); registry.register(foo).unwrap(); let result = registry.register(bar.into_function().with_name(name)); assert!(matches!( result, Err(FunctionRegistrationError::DuplicateName(_)) )); assert_eq!(registry.len(), 1); let function = registry.get(name).unwrap(); let value = function.call(ArgList::new()).unwrap().unwrap_owned(); assert_eq!(value.try_downcast_ref::<i32>(), Some(&123)); } #[test] fn should_allow_overwriting_registration() { fn foo() -> i32 { 123 } fn bar() -> i32 { 321 } let name = core::any::type_name_of_val(&foo); let mut registry = FunctionRegistry::default(); registry.register(foo).unwrap(); registry .overwrite_registration(bar.into_function().with_name(name)) .unwrap(); assert_eq!(registry.len(), 1); let function = registry.get(name).unwrap(); let value = function.call(ArgList::new()).unwrap().unwrap_owned(); assert_eq!(value.try_downcast_ref::<i32>(), Some(&321)); } #[test] fn should_call_function_via_registry() { fn add(a: i32, b: i32) -> i32 { a + b } let mut registry = FunctionRegistry::default(); registry.register(add).unwrap(); let args = ArgList::new().with_owned(25_i32).with_owned(75_i32); let result = registry .call(core::any::type_name_of_val(&add), args) .unwrap(); let value = result.unwrap().unwrap_owned(); assert_eq!(value.try_downcast_ref::<i32>(), Some(&100)); } #[test] fn should_error_on_missing_name() { let foo = || -> i32 { 123 }; let function = foo.into_function(); let mut registry = FunctionRegistry::default(); let result = registry.register(function); assert!(matches!( result, Err(FunctionRegistrationError::MissingName) )); } #[test] fn should_debug_function_registry() { fn foo() -> i32 { 123 } let mut registry = FunctionRegistry::default(); registry.register_with_name("foo", foo).unwrap(); let debug = format!("{registry:?}"); assert_eq!(debug, "{DynamicFunction(fn foo() -> i32)}"); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/mod.rs
crates/bevy_reflect/src/func/mod.rs
//! Reflection-based dynamic functions. //! //! This module provides a way to pass around and call functions dynamically //! using the [`DynamicFunction`] and [`DynamicFunctionMut`] types. //! //! Many simple functions and closures can be automatically converted to these types //! using the [`IntoFunction`] and [`IntoFunctionMut`] traits, respectively. //! //! Once this dynamic representation is created, it can be called with a set of arguments provided //! via an [`ArgList`]. //! //! This returns a [`FunctionResult`] containing the [`Return`] value, //! which can be used to extract a [`PartialReflect`] trait object. //! //! # Example //! //! ``` //! # use bevy_reflect::PartialReflect; //! # use bevy_reflect::func::args::ArgList; //! # use bevy_reflect::func::{DynamicFunction, FunctionResult, IntoFunction, Return}; //! fn add(a: i32, b: i32) -> i32 { //! a + b //! } //! //! let mut func: DynamicFunction = add.into_function(); //! let args: ArgList = ArgList::default() //! // Pushing a known type with owned ownership //! .with_owned(25_i32) //! // Pushing a reflected type with owned ownership //! .with_boxed(Box::new(75_i32) as Box<dyn PartialReflect>); //! let result: FunctionResult = func.call(args); //! let value: Return = result.unwrap(); //! assert_eq!(value.unwrap_owned().try_downcast_ref::<i32>(), Some(&100)); //! ``` //! //! # Types of Functions //! //! For simplicity, this module uses the umbrella term "function" to refer to any Rust callable: //! code that can be invoked with a set of arguments to perform some action. //! //! In Rust, there are two main categories of callables: functions and closures. //! //! A "function" is a callable that does not capture its environment. //! These are typically defined with the `fn` keyword, which are referred to as _named_ functions. //! But there are also _anonymous_ functions, which are unnamed and defined with anonymous function syntax. //! //! ```rust //! // This is a named function: //! fn add(a: i32, b: i32) -> i32 { //! a + b //! } //! //! // This is an anonymous function: //! let add = |a: i32, b: i32| a + b; //! ``` //! //! Closures, on the other hand, are special functions that do capture their environment. //! These are always defined with anonymous function syntax. //! //! ``` //! // A closure that captures an immutable reference to a variable //! let c = 123; //! let add = |a: i32, b: i32| a + b + c; //! //! // A closure that captures a mutable reference to a variable //! let mut total = 0; //! let add = |a: i32, b: i32| total += a + b; //! //! // A closure that takes ownership of its captured variables by moving them //! let c = 123; //! let add = move |a: i32, b: i32| a + b + c; //! ``` //! //! # Valid Signatures //! //! Many of the traits in this module have default blanket implementations over a specific set of function signatures. //! //! These signatures are: //! - `(...) -> R` //! - `for<'a> (&'a arg, ...) -> &'a R` //! - `for<'a> (&'a mut arg, ...) -> &'a R` //! - `for<'a> (&'a mut arg, ...) -> &'a mut R` //! //! Where `...` represents 0 to 15 arguments (inclusive) of the form `T`, `&T`, or `&mut T`. //! The lifetime of any reference to the return type `R`, must be tied to a "receiver" argument //! (i.e. the first argument in the signature, normally `self`). //! //! Each trait will also have its own requirements for what traits are required for both arguments and return types, //! but a good rule-of-thumb is that all types should derive [`Reflect`]. //! //! The reason for such a small subset of valid signatures is due to limitations in Rust— //! namely the [lack of variadic generics] and certain [coherence issues]. //! //! For other functions that don't conform to one of the above signatures, //! [`DynamicFunction`] and [`DynamicFunctionMut`] can instead be created manually. //! //! # Generic Functions //! //! In Rust, generic functions are [monomorphized] by the compiler, //! which means that a separate copy of the function is generated for each concrete set of type parameters. //! //! When converting a generic function to a [`DynamicFunction`] or [`DynamicFunctionMut`], //! the function must be manually monomorphized with concrete types. //! In other words, you cannot write `add<T>.into_function()`. //! Instead, you will need to write `add::<i32>.into_function()`. //! //! This means that reflected functions cannot be generic themselves. //! To get around this limitation, you can consider [overloading] your function with multiple concrete types. //! //! # Overloading Functions //! //! Both [`DynamicFunction`] and [`DynamicFunctionMut`] support [function overloading]. //! //! Function overloading allows one function to handle multiple types of arguments. //! This is useful for simulating generic functions by having an overload for each known concrete type. //! Additionally, it can also simulate [variadic functions]: functions that can be called with a variable number of arguments. //! //! Internally, this works by storing multiple functions in a map, //! where each function is associated with a specific argument signature. //! //! To learn more, see the docs on [`DynamicFunction::with_overload`]. //! //! # Function Registration //! //! This module also provides a [`FunctionRegistry`] that can be used to register functions and closures //! by name so that they may be retrieved and called dynamically. //! //! ``` //! # use bevy_reflect::func::{ArgList, FunctionRegistry}; //! fn add(a: i32, b: i32) -> i32 { //! a + b //! } //! //! let mut registry = FunctionRegistry::default(); //! //! // You can register functions and methods by their `core::any::type_name`: //! registry.register(add).unwrap(); //! //! // Or you can register them by a custom name: //! registry.register_with_name("mul", |a: i32, b: i32| a * b).unwrap(); //! //! // You can then retrieve and call these functions by name: //! let reflect_add = registry.get(core::any::type_name_of_val(&add)).unwrap(); //! let value = reflect_add.call(ArgList::default().with_owned(10_i32).with_owned(5_i32)).unwrap(); //! assert_eq!(value.unwrap_owned().try_downcast_ref::<i32>(), Some(&15)); //! //! let reflect_mul = registry.get("mul").unwrap(); //! let value = reflect_mul.call(ArgList::default().with_owned(10_i32).with_owned(5_i32)).unwrap(); //! assert_eq!(value.unwrap_owned().try_downcast_ref::<i32>(), Some(&50)); //! ``` //! //! [`PartialReflect`]: crate::PartialReflect //! [`Reflect`]: crate::Reflect //! [lack of variadic generics]: https://poignardazur.github.io/2024/05/25/report-on-rustnl-variadics/ //! [coherence issues]: https://doc.rust-lang.org/rustc/lints/listing/warn-by-default.html#coherence-leak-check //! [monomorphized]: https://en.wikipedia.org/wiki/Monomorphization //! [overloading]: #overloading-functions //! [function overloading]: https://en.wikipedia.org/wiki/Function_overloading //! [variadic functions]: https://en.wikipedia.org/wiki/Variadic_function pub use args::{ArgError, ArgList, ArgValue}; pub use dynamic_function::*; pub use dynamic_function_mut::*; pub use error::*; pub use function::*; pub use info::*; pub use into_function::*; pub use into_function_mut::*; pub use reflect_fn::*; pub use reflect_fn_mut::*; pub use registry::*; pub use return_type::*; pub mod args; mod dynamic_function; mod dynamic_function_internal; mod dynamic_function_mut; mod error; mod function; mod info; mod into_function; mod into_function_mut; pub(crate) mod macros; mod reflect_fn; mod reflect_fn_mut; mod registry; mod return_type; pub mod signature; #[cfg(test)] mod tests { use alloc::borrow::Cow; use super::*; use crate::func::args::ArgCount; use crate::{ func::args::{ArgError, ArgList, Ownership}, TypePath, }; #[test] fn should_error_on_missing_args() { fn foo(_: i32) {} let func = foo.into_function(); let args = ArgList::new(); let result = func.call(args); assert_eq!( result.unwrap_err(), FunctionError::ArgCountMismatch { expected: ArgCount::new(1).unwrap(), received: 0 } ); } #[test] fn should_error_on_too_many_args() { fn foo() {} let func = foo.into_function(); let args = ArgList::new().with_owned(123_i32); let result = func.call(args); assert_eq!( result.unwrap_err(), FunctionError::ArgCountMismatch { expected: ArgCount::new(0).unwrap(), received: 1 } ); } #[test] fn should_error_on_invalid_arg_type() { fn foo(_: i32) {} let func = foo.into_function(); let args = ArgList::new().with_owned(123_u32); let result = func.call(args); assert_eq!( result.unwrap_err(), FunctionError::ArgError(ArgError::UnexpectedType { index: 0, expected: Cow::Borrowed(i32::type_path()), received: Cow::Borrowed(u32::type_path()) }) ); } #[test] fn should_error_on_invalid_arg_ownership() { fn foo(_: &i32) {} let func = foo.into_function(); let args = ArgList::new().with_owned(123_i32); let result = func.call(args); assert_eq!( result.unwrap_err(), FunctionError::ArgError(ArgError::InvalidOwnership { index: 0, expected: Ownership::Ref, received: Ownership::Owned }) ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false