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_reflect/src/path/access.rs | crates/bevy_reflect/src/path/access.rs | //! Representation for individual element accesses within a path.
use alloc::borrow::Cow;
use core::fmt;
use super::error::AccessErrorKind;
use crate::{AccessError, PartialReflect, ReflectKind, ReflectMut, ReflectRef, VariantType};
type InnerResult<T> = Result<T, AccessErrorKind>;
/// A singular element access within a path.
/// Multiple accesses can be combined into a [`ParsedPath`](super::ParsedPath).
///
/// Can be applied to a [`dyn Reflect`](crate::Reflect) to get a reference to the targeted element.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Access<'a> {
/// A name-based field access on a struct.
Field(Cow<'a, str>),
/// A index-based field access on a struct.
FieldIndex(usize),
/// An index-based access on a tuple.
TupleIndex(usize),
/// An index-based access on a list.
ListIndex(usize),
}
impl fmt::Display for Access<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Access::Field(field) => write!(f, ".{field}"),
Access::FieldIndex(index) => write!(f, "#{index}"),
Access::TupleIndex(index) => write!(f, ".{index}"),
Access::ListIndex(index) => write!(f, "[{index}]"),
}
}
}
impl<'a> Access<'a> {
/// Converts this into an "owned" value.
///
/// If the [`Access`] is of variant [`Field`](Access::Field),
/// the field's [`Cow<str>`] will be converted to its owned
/// counterpart, which doesn't require a reference.
pub fn into_owned(self) -> Access<'static> {
match self {
Self::Field(value) => Access::Field(Cow::Owned(value.into_owned())),
Self::FieldIndex(value) => Access::FieldIndex(value),
Self::TupleIndex(value) => Access::TupleIndex(value),
Self::ListIndex(value) => Access::ListIndex(value),
}
}
pub(super) fn element<'r>(
&self,
base: &'r dyn PartialReflect,
offset: Option<usize>,
) -> Result<&'r dyn PartialReflect, AccessError<'a>> {
self.element_inner(base)
.and_then(|opt| opt.ok_or(AccessErrorKind::MissingField(base.reflect_kind())))
.map_err(|err| err.with_access(self.clone(), offset))
}
fn element_inner<'r>(
&self,
base: &'r dyn PartialReflect,
) -> InnerResult<Option<&'r dyn PartialReflect>> {
use ReflectRef::*;
let invalid_variant =
|expected, actual| AccessErrorKind::IncompatibleEnumVariantTypes { expected, actual };
match (self, base.reflect_ref()) {
(Self::Field(field), Struct(struct_ref)) => Ok(struct_ref.field(field.as_ref())),
(Self::Field(field), Enum(enum_ref)) => match enum_ref.variant_type() {
VariantType::Struct => Ok(enum_ref.field(field.as_ref())),
actual => Err(invalid_variant(VariantType::Struct, actual)),
},
(&Self::FieldIndex(index), Struct(struct_ref)) => Ok(struct_ref.field_at(index)),
(&Self::FieldIndex(index), Enum(enum_ref)) => match enum_ref.variant_type() {
VariantType::Struct => Ok(enum_ref.field_at(index)),
actual => Err(invalid_variant(VariantType::Struct, actual)),
},
(Self::Field(_) | Self::FieldIndex(_), actual) => {
Err(AccessErrorKind::IncompatibleTypes {
expected: ReflectKind::Struct,
actual: actual.into(),
})
}
(&Self::TupleIndex(index), TupleStruct(tuple)) => Ok(tuple.field(index)),
(&Self::TupleIndex(index), Tuple(tuple)) => Ok(tuple.field(index)),
(&Self::TupleIndex(index), Enum(enum_ref)) => match enum_ref.variant_type() {
VariantType::Tuple => Ok(enum_ref.field_at(index)),
actual => Err(invalid_variant(VariantType::Tuple, actual)),
},
(Self::TupleIndex(_), actual) => Err(AccessErrorKind::IncompatibleTypes {
expected: ReflectKind::Tuple,
actual: actual.into(),
}),
(&Self::ListIndex(index), List(list)) => Ok(list.get(index)),
(&Self::ListIndex(index), Array(list)) => Ok(list.get(index)),
(Self::ListIndex(_), actual) => Err(AccessErrorKind::IncompatibleTypes {
expected: ReflectKind::List,
actual: actual.into(),
}),
}
}
pub(super) fn element_mut<'r>(
&self,
base: &'r mut dyn PartialReflect,
offset: Option<usize>,
) -> Result<&'r mut dyn PartialReflect, AccessError<'a>> {
let kind = base.reflect_kind();
self.element_inner_mut(base)
.and_then(|maybe| maybe.ok_or(AccessErrorKind::MissingField(kind)))
.map_err(|err| err.with_access(self.clone(), offset))
}
fn element_inner_mut<'r>(
&self,
base: &'r mut dyn PartialReflect,
) -> InnerResult<Option<&'r mut dyn PartialReflect>> {
use ReflectMut::*;
let invalid_variant =
|expected, actual| AccessErrorKind::IncompatibleEnumVariantTypes { expected, actual };
match (self, base.reflect_mut()) {
(Self::Field(field), Struct(struct_mut)) => Ok(struct_mut.field_mut(field.as_ref())),
(Self::Field(field), Enum(enum_mut)) => match enum_mut.variant_type() {
VariantType::Struct => Ok(enum_mut.field_mut(field.as_ref())),
actual => Err(invalid_variant(VariantType::Struct, actual)),
},
(&Self::FieldIndex(index), Struct(struct_mut)) => Ok(struct_mut.field_at_mut(index)),
(&Self::FieldIndex(index), Enum(enum_mut)) => match enum_mut.variant_type() {
VariantType::Struct => Ok(enum_mut.field_at_mut(index)),
actual => Err(invalid_variant(VariantType::Struct, actual)),
},
(Self::Field(_) | Self::FieldIndex(_), actual) => {
Err(AccessErrorKind::IncompatibleTypes {
expected: ReflectKind::Struct,
actual: actual.into(),
})
}
(&Self::TupleIndex(index), TupleStruct(tuple)) => Ok(tuple.field_mut(index)),
(&Self::TupleIndex(index), Tuple(tuple)) => Ok(tuple.field_mut(index)),
(&Self::TupleIndex(index), Enum(enum_mut)) => match enum_mut.variant_type() {
VariantType::Tuple => Ok(enum_mut.field_at_mut(index)),
actual => Err(invalid_variant(VariantType::Tuple, actual)),
},
(Self::TupleIndex(_), actual) => Err(AccessErrorKind::IncompatibleTypes {
expected: ReflectKind::Tuple,
actual: actual.into(),
}),
(&Self::ListIndex(index), List(list)) => Ok(list.get_mut(index)),
(&Self::ListIndex(index), Array(list)) => Ok(list.get_mut(index)),
(Self::ListIndex(_), actual) => Err(AccessErrorKind::IncompatibleTypes {
expected: ReflectKind::List,
actual: actual.into(),
}),
}
}
/// Returns a reference to this [`Access`]'s inner value as a [`&dyn Display`](fmt::Display).
pub fn display_value(&self) -> &dyn fmt::Display {
match self {
Self::Field(value) => value,
Self::FieldIndex(value) | Self::TupleIndex(value) | Self::ListIndex(value) => value,
}
}
pub(super) fn kind(&self) -> &'static str {
match self {
Self::Field(_) => "field",
Self::FieldIndex(_) => "field index",
Self::TupleIndex(_) | Self::ListIndex(_) => "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/path/mod.rs | crates/bevy_reflect/src/path/mod.rs | pub mod access;
pub use access::*;
mod error;
pub use error::*;
mod parse;
pub use parse::ParseError;
use parse::PathParser;
use crate::{PartialReflect, Reflect};
use alloc::vec::Vec;
use core::fmt;
use derive_more::derive::From;
use thiserror::Error;
type PathResult<'a, T> = Result<T, ReflectPathError<'a>>;
/// An error returned from a failed path string query.
#[derive(Error, Debug, PartialEq, Eq)]
pub enum ReflectPathError<'a> {
/// An error caused by trying to access a path that's not able to be accessed,
/// see [`AccessError`] for details.
#[error(transparent)]
InvalidAccess(AccessError<'a>),
/// An error that occurs when a type cannot downcast to a given type.
#[error("Can't downcast result of access to the given type")]
InvalidDowncast,
/// An error caused by an invalid path string that couldn't be parsed.
#[error("Encountered an error at offset {offset} while parsing `{path}`: {error}")]
ParseError {
/// Position in `path`.
offset: usize,
/// The path that the error occurred in.
path: &'a str,
/// The underlying error.
error: ParseError<'a>,
},
}
impl<'a> From<AccessError<'a>> for ReflectPathError<'a> {
fn from(value: AccessError<'a>) -> Self {
ReflectPathError::InvalidAccess(value)
}
}
/// Something that can be interpreted as a reflection path in [`GetPath`].
pub trait ReflectPath<'a>: Sized {
/// Gets a reference to the specified element on the given [`Reflect`] object.
///
/// See [`GetPath::reflect_path`] for more details,
/// see [`element`](Self::element) if you want a typed return value.
fn reflect_element(self, root: &dyn PartialReflect) -> PathResult<'a, &dyn PartialReflect>;
/// Gets a mutable reference to the specified element on the given [`Reflect`] object.
///
/// See [`GetPath::reflect_path_mut`] for more details.
fn reflect_element_mut(
self,
root: &mut dyn PartialReflect,
) -> PathResult<'a, &mut dyn PartialReflect>;
/// Gets a `&T` to the specified element on the given [`Reflect`] object.
///
/// See [`GetPath::path`] for more details.
fn element<T: Reflect>(self, root: &dyn PartialReflect) -> PathResult<'a, &T> {
self.reflect_element(root).and_then(|p| {
p.try_downcast_ref::<T>()
.ok_or(ReflectPathError::InvalidDowncast)
})
}
/// Gets a `&mut T` to the specified element on the given [`Reflect`] object.
///
/// See [`GetPath::path_mut`] for more details.
fn element_mut<T: Reflect>(self, root: &mut dyn PartialReflect) -> PathResult<'a, &mut T> {
self.reflect_element_mut(root).and_then(|p| {
p.try_downcast_mut::<T>()
.ok_or(ReflectPathError::InvalidDowncast)
})
}
}
impl<'a> ReflectPath<'a> for &'a str {
fn reflect_element(self, mut root: &dyn PartialReflect) -> PathResult<'a, &dyn PartialReflect> {
for (access, offset) in PathParser::new(self) {
let a = access?;
root = a.element(root, Some(offset))?;
}
Ok(root)
}
fn reflect_element_mut(
self,
mut root: &mut dyn PartialReflect,
) -> PathResult<'a, &mut dyn PartialReflect> {
for (access, offset) in PathParser::new(self) {
root = access?.element_mut(root, Some(offset))?;
}
Ok(root)
}
}
/// A trait which allows nested [`Reflect`] values to be retrieved with path strings.
///
/// Using these functions repeatedly with the same string requires parsing the string every time.
/// To avoid this cost, it's recommended to construct a [`ParsedPath`] instead.
///
/// # Syntax
///
/// ## Structs
///
/// Field paths for [`Struct`] elements use the standard Rust field access syntax of
/// dot and field name: `.field_name`.
///
/// Additionally, struct fields may be accessed by their index within the struct's definition.
/// This is accomplished by using the hash symbol (`#`) in place of the standard dot: `#0`.
///
/// Accessing a struct's field by index can speed up fetches at runtime due to the removed
/// need for string matching.
/// And while this can be more performant, it's best to keep in mind the tradeoffs when
/// utilizing such optimizations.
/// For example, this can result in fairly fragile code as the string paths will need to be
/// kept in sync with the struct definitions since the order of fields could be easily changed.
/// Because of this, storing these kinds of paths in persistent storage (i.e. game assets)
/// is strongly discouraged.
///
/// Note that a leading dot (`.`) or hash (`#`) token is implied for the first item in a path,
/// and may therefore be omitted.
///
/// Additionally, an empty path may be used to get the struct itself.
///
/// ### Example
/// ```
/// # use bevy_reflect::{GetPath, Reflect};
/// #[derive(Reflect, PartialEq, Debug)]
/// struct MyStruct {
/// value: u32
/// }
///
/// let my_struct = MyStruct { value: 123 };
/// // Access via field name
/// assert_eq!(my_struct.path::<u32>(".value").unwrap(), &123);
/// // Access via field index
/// assert_eq!(my_struct.path::<u32>("#0").unwrap(), &123);
/// // Access self
/// assert_eq!(*my_struct.path::<MyStruct>("").unwrap(), my_struct);
/// ```
///
/// ## Tuples and Tuple Structs
///
/// [`Tuple`] and [`TupleStruct`] elements also follow a conventional Rust syntax.
/// Fields are accessed with a dot and the field index: `.0`.
///
/// Note that a leading dot (`.`) token is implied for the first item in a path,
/// and may therefore be omitted.
///
/// ### Example
/// ```
/// # use bevy_reflect::{GetPath, Reflect};
/// #[derive(Reflect)]
/// struct MyTupleStruct(u32);
///
/// let my_tuple_struct = MyTupleStruct(123);
/// assert_eq!(my_tuple_struct.path::<u32>(".0").unwrap(), &123);
/// ```
///
/// ## Lists and Arrays
///
/// [`List`] and [`Array`] elements are accessed with brackets: `[0]`.
///
/// ### Example
/// ```
/// # use bevy_reflect::{GetPath};
/// let my_list: Vec<u32> = vec![1, 2, 3];
/// assert_eq!(my_list.path::<u32>("[2]").unwrap(), &3);
/// ```
///
/// ## Enums
///
/// Pathing for [`Enum`] elements works a bit differently than in normal Rust.
/// Usually, you would need to pattern match an enum, branching off on the desired variants.
/// Paths used by this trait do not have any pattern matching capabilities;
/// instead, they assume the variant is already known ahead of time.
///
/// The syntax used, therefore, depends on the variant being accessed:
/// - Struct variants use the struct syntax (outlined above)
/// - Tuple variants use the tuple syntax (outlined above)
/// - Unit variants have no fields to access
///
/// If the variant cannot be known ahead of time, the path will need to be split up
/// and proper enum pattern matching will need to be handled manually.
///
/// ### Example
/// ```
/// # use bevy_reflect::{GetPath, Reflect};
/// #[derive(Reflect)]
/// enum MyEnum {
/// Unit,
/// Tuple(bool),
/// Struct {
/// value: u32
/// }
/// }
///
/// let tuple_variant = MyEnum::Tuple(true);
/// assert_eq!(tuple_variant.path::<bool>(".0").unwrap(), &true);
///
/// let struct_variant = MyEnum::Struct { value: 123 };
/// // Access via field name
/// assert_eq!(struct_variant.path::<u32>(".value").unwrap(), &123);
/// // Access via field index
/// assert_eq!(struct_variant.path::<u32>("#0").unwrap(), &123);
///
/// // Error: Expected struct variant
/// assert!(matches!(tuple_variant.path::<u32>(".value"), Err(_)));
/// ```
///
/// # Chaining
///
/// Using the aforementioned syntax, path items may be chained one after another
/// to create a full path to a nested element.
///
/// ## Example
/// ```
/// # use bevy_reflect::{GetPath, Reflect};
/// #[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,
/// );
/// ```
///
/// [`Struct`]: crate::Struct
/// [`Tuple`]: crate::Tuple
/// [`TupleStruct`]: crate::TupleStruct
/// [`List`]: crate::List
/// [`Array`]: crate::Array
/// [`Enum`]: crate::Enum
#[diagnostic::on_unimplemented(
message = "`{Self}` does not implement `GetPath` so cannot be accessed by reflection path",
note = "consider annotating `{Self}` with `#[derive(Reflect)]`"
)]
pub trait GetPath: PartialReflect {
/// Returns a reference to the value specified by `path`.
///
/// To retrieve a statically typed reference, use
/// [`path`][GetPath::path].
fn reflect_path<'p>(&self, path: impl ReflectPath<'p>) -> PathResult<'p, &dyn PartialReflect> {
path.reflect_element(self.as_partial_reflect())
}
/// Returns a mutable reference to the value specified by `path`.
///
/// To retrieve a statically typed mutable reference, use
/// [`path_mut`][GetPath::path_mut].
fn reflect_path_mut<'p>(
&mut self,
path: impl ReflectPath<'p>,
) -> PathResult<'p, &mut dyn PartialReflect> {
path.reflect_element_mut(self.as_partial_reflect_mut())
}
/// Returns a statically typed reference to the value specified by `path`.
///
/// This will automatically handle downcasting to type `T`.
/// The downcast will fail if this value is not of type `T`
/// (which may be the case when using dynamic types like [`DynamicStruct`]).
///
/// [`DynamicStruct`]: crate::DynamicStruct
fn path<'p, T: Reflect>(&self, path: impl ReflectPath<'p>) -> PathResult<'p, &T> {
path.element(self.as_partial_reflect())
}
/// Returns a statically typed mutable reference to the value specified by `path`.
///
/// This will automatically handle downcasting to type `T`.
/// The downcast will fail if this value is not of type `T`
/// (which may be the case when using dynamic types like [`DynamicStruct`]).
///
/// [`DynamicStruct`]: crate::DynamicStruct
fn path_mut<'p, T: Reflect>(&mut self, path: impl ReflectPath<'p>) -> PathResult<'p, &mut T> {
path.element_mut(self.as_partial_reflect_mut())
}
}
// Implement `GetPath` for `dyn Reflect`
impl<T: Reflect + ?Sized> GetPath for T {}
/// An [`Access`] combined with an `offset` for more helpful error reporting.
#[derive(Clone, Debug, PartialEq, PartialOrd, Ord, Eq, Hash)]
pub struct OffsetAccess {
/// The [`Access`] itself.
pub access: Access<'static>,
/// A character offset in the string the path was parsed from.
pub offset: Option<usize>,
}
impl From<Access<'static>> for OffsetAccess {
fn from(access: Access<'static>) -> Self {
OffsetAccess {
access,
offset: None,
}
}
}
/// A pre-parsed path to an element within a type.
///
/// This struct can be constructed manually from its [`Access`]es or with
/// the [parse](ParsedPath::parse) method.
///
/// This struct may be used like [`GetPath`] but removes the cost of parsing the path
/// string at each element access.
///
/// It's recommended to use this in place of [`GetPath`] when the path string is
/// unlikely to be changed and will be accessed repeatedly.
///
/// ## Examples
///
/// Parsing a [`&'static str`](str):
/// ```
/// # use bevy_reflect::ParsedPath;
/// let my_static_string: &'static str = "bar#0.1[2].0";
/// // Breakdown:
/// // "bar" - Access struct field named "bar"
/// // "#0" - Access struct field at index 0
/// // ".1" - Access tuple struct field at index 1
/// // "[2]" - Access list element at index 2
/// // ".0" - Access tuple variant field at index 0
/// let my_path = ParsedPath::parse_static(my_static_string);
/// ```
/// Parsing a non-static [`&str`](str):
/// ```
/// # use bevy_reflect::ParsedPath;
/// let my_string = String::from("bar#0.1[2].0");
/// // Breakdown:
/// // "bar" - Access struct field named "bar"
/// // "#0" - Access struct field at index 0
/// // ".1" - Access tuple struct field at index 1
/// // "[2]" - Access list element at index 2
/// // ".0" - Access tuple variant field at index 0
/// let my_path = ParsedPath::parse(&my_string);
/// ```
/// Manually constructing a [`ParsedPath`]:
/// ```
/// # use std::borrow::Cow;
/// # use bevy_reflect::access::Access;
/// # use bevy_reflect::ParsedPath;
/// let path_elements = [
/// Access::Field(Cow::Borrowed("bar")),
/// Access::FieldIndex(0),
/// Access::TupleIndex(1),
/// Access::ListIndex(2),
/// Access::TupleIndex(1),
/// ];
/// let my_path = ParsedPath::from(path_elements);
/// ```
#[derive(Clone, Debug, PartialEq, PartialOrd, Ord, Eq, Hash, From)]
pub struct ParsedPath(
/// This is a vector of pre-parsed [`OffsetAccess`]es.
pub Vec<OffsetAccess>,
);
impl ParsedPath {
/// Parses a [`ParsedPath`] from a string.
///
/// Returns an error if the string does not represent a valid path to an element.
///
/// The exact format for path strings can be found in the documentation for [`GetPath`].
/// In short, though, a path consists of one or more chained accessor strings.
/// These are:
/// - Named field access (`.field`)
/// - Unnamed field access (`.1`)
/// - Field index access (`#0`)
/// - Sequence access (`[2]`)
///
/// # Example
/// ```
/// # use bevy_reflect::{ParsedPath, Reflect, ReflectPath};
/// #[derive(Reflect)]
/// struct Foo {
/// bar: Bar,
/// }
///
/// #[derive(Reflect)]
/// struct Bar {
/// baz: Baz,
/// }
///
/// #[derive(Reflect)]
/// struct Baz(f32, Vec<Option<u32>>);
///
/// let foo = Foo {
/// bar: Bar {
/// baz: Baz(3.14, vec![None, None, Some(123)])
/// },
/// };
///
/// let parsed_path = ParsedPath::parse("bar#0.1[2].0").unwrap();
/// // Breakdown:
/// // "bar" - Access struct field named "bar"
/// // "#0" - Access struct field at index 0
/// // ".1" - Access tuple struct field at index 1
/// // "[2]" - Access list element at index 2
/// // ".0" - Access tuple variant field at index 0
///
/// assert_eq!(parsed_path.element::<u32>(&foo).unwrap(), &123);
/// ```
pub fn parse(string: &str) -> PathResult<'_, Self> {
let mut parts = Vec::new();
for (access, offset) in PathParser::new(string) {
parts.push(OffsetAccess {
access: access?.into_owned(),
offset: Some(offset),
});
}
Ok(Self(parts))
}
/// Similar to [`Self::parse`] but only works on `&'static str`
/// and does not allocate per named field.
pub fn parse_static(string: &'static str) -> PathResult<'static, Self> {
let mut parts = Vec::new();
for (access, offset) in PathParser::new(string) {
parts.push(OffsetAccess {
access: access?,
offset: Some(offset),
});
}
Ok(Self(parts))
}
}
impl<'a> ReflectPath<'a> for &'a ParsedPath {
fn reflect_element(self, mut root: &dyn PartialReflect) -> PathResult<'a, &dyn PartialReflect> {
for OffsetAccess { access, offset } in &self.0 {
root = access.element(root, *offset)?;
}
Ok(root)
}
fn reflect_element_mut(
self,
mut root: &mut dyn PartialReflect,
) -> PathResult<'a, &mut dyn PartialReflect> {
for OffsetAccess { access, offset } in &self.0 {
root = access.element_mut(root, *offset)?;
}
Ok(root)
}
}
impl<const N: usize> From<[OffsetAccess; N]> for ParsedPath {
fn from(value: [OffsetAccess; N]) -> Self {
ParsedPath(value.to_vec())
}
}
impl From<Vec<Access<'static>>> for ParsedPath {
fn from(value: Vec<Access<'static>>) -> Self {
ParsedPath(
value
.into_iter()
.map(|access| OffsetAccess {
access,
offset: None,
})
.collect(),
)
}
}
impl<const N: usize> From<[Access<'static>; N]> for ParsedPath {
fn from(value: [Access<'static>; N]) -> Self {
value.to_vec().into()
}
}
impl<'a> TryFrom<&'a str> for ParsedPath {
type Error = ReflectPathError<'a>;
fn try_from(value: &'a str) -> Result<Self, Self::Error> {
ParsedPath::parse(value)
}
}
impl fmt::Display for ParsedPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for OffsetAccess { access, .. } in &self.0 {
write!(f, "{access}")?;
}
Ok(())
}
}
impl core::ops::Index<usize> for ParsedPath {
type Output = OffsetAccess;
fn index(&self, index: usize) -> &Self::Output {
&self.0[index]
}
}
impl core::ops::IndexMut<usize> for ParsedPath {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.0[index]
}
}
#[cfg(test)]
#[expect(
clippy::approx_constant,
reason = "We don't need the exact value of Pi here."
)]
mod tests {
use super::*;
use crate::*;
use alloc::vec;
#[derive(Reflect, PartialEq, Debug)]
struct A {
w: usize,
x: B,
y: Vec<C>,
z: D,
unit_variant: F,
tuple_variant: F,
struct_variant: F,
array: [i32; 3],
tuple: (bool, f32),
}
#[derive(Reflect, PartialEq, Debug)]
struct B {
foo: usize,
łørđ: C,
}
#[derive(Reflect, PartialEq, Debug)]
struct C {
mосква: f32,
}
#[derive(Reflect, PartialEq, Debug)]
struct D(E);
#[derive(Reflect, PartialEq, Debug)]
struct E(f32, usize);
#[derive(Reflect, PartialEq, Debug)]
enum F {
Unit,
Tuple(u32, u32),
Şķràźÿ { 東京: char },
}
fn a_sample() -> A {
A {
w: 1,
x: B {
foo: 10,
łørđ: C { mосква: 3.14 },
},
y: vec![C { mосква: 1.0 }, C { mосква: 2.0 }],
z: D(E(10.0, 42)),
unit_variant: F::Unit,
tuple_variant: F::Tuple(123, 321),
struct_variant: F::Şķràźÿ { 東京: 'm' },
array: [86, 75, 309],
tuple: (true, 1.23),
}
}
fn offset(access: Access<'static>, offset: usize) -> OffsetAccess {
OffsetAccess {
access,
offset: Some(offset),
}
}
fn access_field(field: &'static str) -> Access<'static> {
Access::Field(field.into())
}
type StaticError = ReflectPathError<'static>;
fn invalid_access(
offset: usize,
actual: ReflectKind,
expected: ReflectKind,
access: &'static str,
) -> StaticError {
ReflectPathError::InvalidAccess(AccessError {
kind: AccessErrorKind::IncompatibleTypes { actual, expected },
access: ParsedPath::parse_static(access).unwrap()[1].access.clone(),
offset: Some(offset),
})
}
#[test]
fn try_from() {
assert_eq!(
ParsedPath::try_from("w").unwrap().0,
&[offset(access_field("w"), 1)]
);
let r = ParsedPath::try_from("w[");
let matches = matches!(r, Err(ReflectPathError::ParseError { .. }));
assert!(
matches,
"ParsedPath::try_from did not return a ParseError for \"w[\""
);
}
#[test]
fn parsed_path_parse() {
assert_eq!(
ParsedPath::parse("w").unwrap().0,
&[offset(access_field("w"), 1)]
);
assert_eq!(
ParsedPath::parse("x.foo").unwrap().0,
&[offset(access_field("x"), 1), offset(access_field("foo"), 2)]
);
assert_eq!(
ParsedPath::parse("x.łørđ.mосква").unwrap().0,
&[
offset(access_field("x"), 1),
offset(access_field("łørđ"), 2),
offset(access_field("mосква"), 10)
]
);
assert_eq!(
ParsedPath::parse("y[1].mосква").unwrap().0,
&[
offset(access_field("y"), 1),
offset(Access::ListIndex(1), 2),
offset(access_field("mосква"), 5)
]
);
assert_eq!(
ParsedPath::parse("z.0.1").unwrap().0,
&[
offset(access_field("z"), 1),
offset(Access::TupleIndex(0), 2),
offset(Access::TupleIndex(1), 4),
]
);
assert_eq!(
ParsedPath::parse("x#0").unwrap().0,
&[
offset(access_field("x"), 1),
offset(Access::FieldIndex(0), 2)
]
);
assert_eq!(
ParsedPath::parse("x#0#1").unwrap().0,
&[
offset(access_field("x"), 1),
offset(Access::FieldIndex(0), 2),
offset(Access::FieldIndex(1), 4)
]
);
}
#[test]
fn parsed_path_get_field() {
let a = a_sample();
let b = ParsedPath::parse("w").unwrap();
let c = ParsedPath::parse("x.foo").unwrap();
let d = ParsedPath::parse("x.łørđ.mосква").unwrap();
let e = ParsedPath::parse("y[1].mосква").unwrap();
let f = ParsedPath::parse("z.0.1").unwrap();
let g = ParsedPath::parse("x#0").unwrap();
let h = ParsedPath::parse("x#1#0").unwrap();
let i = ParsedPath::parse("unit_variant").unwrap();
let j = ParsedPath::parse("tuple_variant.1").unwrap();
let k = ParsedPath::parse("struct_variant.東京").unwrap();
let l = ParsedPath::parse("struct_variant#0").unwrap();
let m = ParsedPath::parse("array[2]").unwrap();
let n = ParsedPath::parse("tuple.1").unwrap();
for _ in 0..30 {
assert_eq!(*b.element::<usize>(&a).unwrap(), 1);
assert_eq!(*c.element::<usize>(&a).unwrap(), 10);
assert_eq!(*d.element::<f32>(&a).unwrap(), 3.14);
assert_eq!(*e.element::<f32>(&a).unwrap(), 2.0);
assert_eq!(*f.element::<usize>(&a).unwrap(), 42);
assert_eq!(*g.element::<usize>(&a).unwrap(), 10);
assert_eq!(*h.element::<f32>(&a).unwrap(), 3.14);
assert_eq!(*i.element::<F>(&a).unwrap(), F::Unit);
assert_eq!(*j.element::<u32>(&a).unwrap(), 321);
assert_eq!(*k.element::<char>(&a).unwrap(), 'm');
assert_eq!(*l.element::<char>(&a).unwrap(), 'm');
assert_eq!(*m.element::<i32>(&a).unwrap(), 309);
assert_eq!(*n.element::<f32>(&a).unwrap(), 1.23);
}
}
#[test]
fn reflect_array_behaves_like_list() {
#[derive(Reflect)]
struct A {
list: Vec<u8>,
array: [u8; 10],
}
let a = A {
list: vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
};
assert_eq!(*a.path::<u8>("list[5]").unwrap(), 5);
assert_eq!(*a.path::<u8>("array[5]").unwrap(), 5);
assert_eq!(*a.path::<u8>("list[0]").unwrap(), 0);
assert_eq!(*a.path::<u8>("array[0]").unwrap(), 0);
}
#[test]
fn reflect_array_behaves_like_list_mut() {
#[derive(Reflect)]
struct A {
list: Vec<u8>,
array: [u8; 10],
}
let mut a = A {
list: vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
};
assert_eq!(*a.path_mut::<u8>("list[5]").unwrap(), 5);
assert_eq!(*a.path_mut::<u8>("array[5]").unwrap(), 5);
*a.path_mut::<u8>("list[5]").unwrap() = 10;
*a.path_mut::<u8>("array[5]").unwrap() = 10;
assert_eq!(*a.path_mut::<u8>("list[5]").unwrap(), 10);
assert_eq!(*a.path_mut::<u8>("array[5]").unwrap(), 10);
}
#[test]
fn reflect_path() {
let mut a = a_sample();
assert_eq!(*a.path::<A>("").unwrap(), a);
assert_eq!(*a.path::<usize>("w").unwrap(), 1);
assert_eq!(*a.path::<usize>("x.foo").unwrap(), 10);
assert_eq!(*a.path::<f32>("x.łørđ.mосква").unwrap(), 3.14);
assert_eq!(*a.path::<f32>("y[1].mосква").unwrap(), 2.0);
assert_eq!(*a.path::<usize>("z.0.1").unwrap(), 42);
assert_eq!(*a.path::<usize>("x#0").unwrap(), 10);
assert_eq!(*a.path::<f32>("x#1#0").unwrap(), 3.14);
assert_eq!(*a.path::<F>("unit_variant").unwrap(), F::Unit);
assert_eq!(*a.path::<u32>("tuple_variant.1").unwrap(), 321);
assert_eq!(*a.path::<char>("struct_variant.東京").unwrap(), 'm');
assert_eq!(*a.path::<char>("struct_variant#0").unwrap(), 'm');
assert_eq!(*a.path::<i32>("array[2]").unwrap(), 309);
assert_eq!(*a.path::<f32>("tuple.1").unwrap(), 1.23);
*a.path_mut::<f32>("tuple.1").unwrap() = 3.21;
assert_eq!(*a.path::<f32>("tuple.1").unwrap(), 3.21);
*a.path_mut::<f32>("y[1].mосква").unwrap() = 3.0;
assert_eq!(a.y[1].mосква, 3.0);
*a.path_mut::<u32>("tuple_variant.0").unwrap() = 1337;
assert_eq!(a.tuple_variant, F::Tuple(1337, 321));
assert_eq!(
a.reflect_path("x.notreal").err().unwrap(),
ReflectPathError::InvalidAccess(AccessError {
kind: AccessErrorKind::MissingField(ReflectKind::Struct),
access: access_field("notreal"),
offset: Some(2),
})
);
assert_eq!(
a.reflect_path("unit_variant.0").err().unwrap(),
ReflectPathError::InvalidAccess(AccessError {
kind: AccessErrorKind::IncompatibleEnumVariantTypes {
actual: VariantType::Unit,
expected: VariantType::Tuple,
},
access: ParsedPath::parse_static("unit_variant.0").unwrap()[1]
.access
.clone(),
offset: Some(13),
})
);
assert_eq!(
a.reflect_path("x[0]").err().unwrap(),
invalid_access(2, ReflectKind::Struct, ReflectKind::List, "x[0]")
);
assert_eq!(
a.reflect_path("y.x").err().unwrap(),
invalid_access(2, ReflectKind::List, ReflectKind::Struct, "y.x")
);
}
#[test]
fn accept_leading_tokens() {
assert_eq!(
ParsedPath::parse(".w").unwrap().0,
&[offset(access_field("w"), 1)]
);
assert_eq!(
ParsedPath::parse("#0.foo").unwrap().0,
&[
offset(Access::FieldIndex(0), 1),
offset(access_field("foo"), 3)
]
);
assert_eq!(
ParsedPath::parse(".5").unwrap().0,
&[offset(Access::TupleIndex(5), 1)]
);
assert_eq!(
ParsedPath::parse("[0].łørđ").unwrap().0,
&[
offset(Access::ListIndex(0), 1),
offset(access_field("łørđ"), 4)
]
);
}
}
| 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/enums/helpers.rs | crates/bevy_reflect/src/enums/helpers.rs | use crate::{utility::reflect_hasher, Enum, PartialReflect, ReflectRef, VariantType};
use core::{
fmt::Debug,
hash::{Hash, Hasher},
};
/// Returns the `u64` hash of the given [enum](Enum).
#[inline]
pub fn enum_hash<TEnum: Enum>(value: &TEnum) -> Option<u64> {
let mut hasher = reflect_hasher();
core::any::Any::type_id(value).hash(&mut hasher);
value.variant_name().hash(&mut hasher);
value.variant_type().hash(&mut hasher);
for field in value.iter_fields() {
hasher.write_u64(field.value().reflect_hash()?);
}
Some(hasher.finish())
}
/// Compares an [`Enum`] with a [`PartialReflect`] value.
///
/// Returns true if and only if all of the following are true:
/// - `b` is an enum;
/// - `b` is the same variant as `a`;
/// - 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.
#[inline]
pub fn enum_partial_eq<TEnum: Enum + ?Sized>(a: &TEnum, b: &dyn PartialReflect) -> Option<bool> {
// Both enums?
let ReflectRef::Enum(b) = b.reflect_ref() else {
return Some(false);
};
// Same variant name?
if a.variant_name() != b.variant_name() {
return Some(false);
}
// Same variant type?
if !a.is_variant(b.variant_type()) {
return Some(false);
}
match a.variant_type() {
VariantType::Struct => {
// Same struct fields?
for field in a.iter_fields() {
let field_name = field.name().unwrap();
if let Some(field_value) = b.field(field_name) {
if let Some(false) | None = field_value.reflect_partial_eq(field.value()) {
// Fields failed comparison
return Some(false);
}
} else {
// Field does not exist
return Some(false);
}
}
Some(true)
}
VariantType::Tuple => {
// Same tuple fields?
for (i, field) in a.iter_fields().enumerate() {
if let Some(field_value) = b.field_at(i) {
if let Some(false) | None = field_value.reflect_partial_eq(field.value()) {
// Fields failed comparison
return Some(false);
}
} else {
// Field does not exist
return Some(false);
}
}
Some(true)
}
_ => Some(true),
}
}
/// The default debug formatter for [`Enum`] types.
///
/// # Example
/// ```
/// use bevy_reflect::Reflect;
/// #[derive(Reflect)]
/// enum MyEnum {
/// A,
/// B (usize),
/// C {value: i32}
/// }
///
/// let my_enum: &dyn Reflect = &MyEnum::B(123);
/// println!("{:#?}", my_enum);
///
/// // Output:
///
/// // B (
/// // 123,
/// // )
/// ```
#[inline]
pub fn enum_debug(dyn_enum: &dyn Enum, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match dyn_enum.variant_type() {
VariantType::Unit => f.write_str(dyn_enum.variant_name()),
VariantType::Tuple => {
let mut debug = f.debug_tuple(dyn_enum.variant_name());
for field in dyn_enum.iter_fields() {
debug.field(&field.value() as &dyn Debug);
}
debug.finish()
}
VariantType::Struct => {
let mut debug = f.debug_struct(dyn_enum.variant_name());
for field in dyn_enum.iter_fields() {
debug.field(field.name().unwrap(), &field.value() as &dyn Debug);
}
debug.finish()
}
}
}
| 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/enums/variants.rs | crates/bevy_reflect/src/enums/variants.rs | use crate::{
attributes::{impl_custom_attribute_methods, CustomAttributes},
NamedField, UnnamedField,
};
use alloc::boxed::Box;
use bevy_platform::collections::HashMap;
use bevy_platform::sync::Arc;
use core::slice::Iter;
use thiserror::Error;
/// Describes the form of an enum variant.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum VariantType {
/// Struct enums take the form:
///
/// ```
/// enum MyEnum {
/// A {
/// foo: usize
/// }
/// }
/// ```
Struct,
/// Tuple enums take the form:
///
/// ```
/// enum MyEnum {
/// A(usize)
/// }
/// ```
Tuple,
/// Unit enums take the form:
///
/// ```
/// enum MyEnum {
/// A
/// }
/// ```
Unit,
}
/// A [`VariantInfo`]-specific error.
#[derive(Debug, Error)]
pub enum VariantInfoError {
/// Caused when a variant was expected to be of a certain [type], but was not.
///
/// [type]: VariantType
#[error("variant type mismatch: expected {expected:?}, received {received:?}")]
TypeMismatch {
/// Expected variant type.
expected: VariantType,
/// Received variant type.
received: VariantType,
},
}
/// A container for compile-time enum variant info.
#[derive(Clone, Debug)]
pub enum VariantInfo {
/// Struct enums take the form:
///
/// ```
/// enum MyEnum {
/// A {
/// foo: usize
/// }
/// }
/// ```
Struct(StructVariantInfo),
/// Tuple enums take the form:
///
/// ```
/// enum MyEnum {
/// A(usize)
/// }
/// ```
Tuple(TupleVariantInfo),
/// Unit enums take the form:
///
/// ```
/// enum MyEnum {
/// A
/// }
/// ```
Unit(UnitVariantInfo),
}
impl VariantInfo {
/// The name of the enum variant.
pub fn name(&self) -> &'static str {
match self {
Self::Struct(info) => info.name(),
Self::Tuple(info) => info.name(),
Self::Unit(info) => info.name(),
}
}
/// The docstring of the underlying variant, if any.
#[cfg(feature = "reflect_documentation")]
pub fn docs(&self) -> Option<&str> {
match self {
Self::Struct(info) => info.docs(),
Self::Tuple(info) => info.docs(),
Self::Unit(info) => info.docs(),
}
}
/// Returns the [type] of this variant.
///
/// [type]: VariantType
pub fn variant_type(&self) -> VariantType {
match self {
Self::Struct(_) => VariantType::Struct,
Self::Tuple(_) => VariantType::Tuple,
Self::Unit(_) => VariantType::Unit,
}
}
impl_custom_attribute_methods!(
self,
match self {
Self::Struct(info) => info.custom_attributes(),
Self::Tuple(info) => info.custom_attributes(),
Self::Unit(info) => info.custom_attributes(),
},
"variant"
);
}
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 [`VariantInfo::", stringify!($kind), "`].")]
pub fn $name(&self) -> Result<&$info, VariantInfoError> {
match self {
Self::$kind(info) => Ok(info),
_ => Err(VariantInfoError::TypeMismatch {
expected: VariantType::$kind,
received: self.variant_type(),
}),
}
}
};
}
/// Conversion convenience methods for [`VariantInfo`].
impl VariantInfo {
impl_cast_method!(as_struct_variant: Struct => StructVariantInfo);
impl_cast_method!(as_tuple_variant: Tuple => TupleVariantInfo);
impl_cast_method!(as_unit_variant: Unit => UnitVariantInfo);
}
/// Type info for struct variants.
#[derive(Clone, Debug)]
pub struct StructVariantInfo {
name: &'static str,
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 StructVariantInfo {
/// Create a new [`StructVariantInfo`].
pub fn new(name: &'static str, fields: &[NamedField]) -> Self {
let field_indices = Self::collect_field_indices(fields);
let field_names = fields.iter().map(NamedField::name).collect();
Self {
name,
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 variant.
#[cfg(feature = "reflect_documentation")]
pub fn with_docs(self, docs: Option<&'static str>) -> Self {
Self { docs, ..self }
}
/// Sets the custom attributes for this variant.
pub fn with_custom_attributes(self, custom_attributes: CustomAttributes) -> Self {
Self {
custom_attributes: Arc::new(custom_attributes),
..self
}
}
/// The name of this variant.
pub fn name(&self) -> &'static str {
self.name
}
/// 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 variant.
pub fn iter(&self) -> Iter<'_, NamedField> {
self.fields.iter()
}
/// The total number of fields in this variant.
pub fn field_len(&self) -> usize {
self.fields.len()
}
fn collect_field_indices(fields: &[NamedField]) -> HashMap<&'static str, usize> {
fields
.iter()
.enumerate()
.map(|(index, field)| (field.name(), index))
.collect()
}
/// The docstring of this variant, if any.
#[cfg(feature = "reflect_documentation")]
pub fn docs(&self) -> Option<&'static str> {
self.docs
}
impl_custom_attribute_methods!(self.custom_attributes, "variant");
}
/// Type info for tuple variants.
#[derive(Clone, Debug)]
pub struct TupleVariantInfo {
name: &'static str,
fields: Box<[UnnamedField]>,
custom_attributes: Arc<CustomAttributes>,
#[cfg(feature = "reflect_documentation")]
docs: Option<&'static str>,
}
impl TupleVariantInfo {
/// Create a new [`TupleVariantInfo`].
pub fn new(name: &'static str, fields: &[UnnamedField]) -> Self {
Self {
name,
fields: fields.to_vec().into_boxed_slice(),
custom_attributes: Arc::new(CustomAttributes::default()),
#[cfg(feature = "reflect_documentation")]
docs: None,
}
}
/// Sets the docstring for this variant.
#[cfg(feature = "reflect_documentation")]
pub fn with_docs(self, docs: Option<&'static str>) -> Self {
Self { docs, ..self }
}
/// Sets the custom attributes for this variant.
pub fn with_custom_attributes(self, custom_attributes: CustomAttributes) -> Self {
Self {
custom_attributes: Arc::new(custom_attributes),
..self
}
}
/// The name of this variant.
pub fn name(&self) -> &'static str {
self.name
}
/// 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 variant.
pub fn iter(&self) -> Iter<'_, UnnamedField> {
self.fields.iter()
}
/// The total number of fields in this variant.
pub fn field_len(&self) -> usize {
self.fields.len()
}
/// The docstring of this variant, if any.
#[cfg(feature = "reflect_documentation")]
pub fn docs(&self) -> Option<&'static str> {
self.docs
}
impl_custom_attribute_methods!(self.custom_attributes, "variant");
}
/// Type info for unit variants.
#[derive(Clone, Debug)]
pub struct UnitVariantInfo {
name: &'static str,
custom_attributes: Arc<CustomAttributes>,
#[cfg(feature = "reflect_documentation")]
docs: Option<&'static str>,
}
impl UnitVariantInfo {
/// Create a new [`UnitVariantInfo`].
pub fn new(name: &'static str) -> Self {
Self {
name,
custom_attributes: Arc::new(CustomAttributes::default()),
#[cfg(feature = "reflect_documentation")]
docs: None,
}
}
/// Sets the docstring for this variant.
#[cfg(feature = "reflect_documentation")]
pub fn with_docs(self, docs: Option<&'static str>) -> Self {
Self { docs, ..self }
}
/// Sets the custom attributes for this variant.
pub fn with_custom_attributes(self, custom_attributes: CustomAttributes) -> Self {
Self {
custom_attributes: Arc::new(custom_attributes),
..self
}
}
/// The name of this variant.
pub fn name(&self) -> &'static str {
self.name
}
/// The docstring of this variant, if any.
#[cfg(feature = "reflect_documentation")]
pub fn docs(&self) -> Option<&'static str> {
self.docs
}
impl_custom_attribute_methods!(self.custom_attributes, "variant");
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Reflect, Typed};
#[test]
fn should_return_error_on_invalid_cast() {
#[derive(Reflect)]
enum Foo {
Bar,
}
let info = Foo::type_info().as_enum().unwrap();
let variant = info.variant_at(0).unwrap();
assert!(matches!(
variant.as_tuple_variant(),
Err(VariantInfoError::TypeMismatch {
expected: VariantType::Tuple,
received: VariantType::Unit
})
));
}
}
| 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/enums/mod.rs | crates/bevy_reflect/src/enums/mod.rs | mod dynamic_enum;
mod enum_trait;
mod helpers;
mod variants;
pub use dynamic_enum::*;
pub use enum_trait::*;
pub use helpers::*;
pub use variants::*;
#[cfg(test)]
mod tests {
use crate::*;
use alloc::boxed::Box;
#[derive(Reflect, Debug, PartialEq)]
enum MyEnum {
A,
B(usize, i32),
C { foo: f32, bar: bool },
}
#[test]
fn should_get_enum_type_info() {
let info = MyEnum::type_info();
if let TypeInfo::Enum(info) = info {
assert!(info.is::<MyEnum>(), "expected type to be `MyEnum`");
assert_eq!(MyEnum::type_path(), info.type_path());
assert_eq!(MyEnum::type_path(), info.type_path_table().path());
assert_eq!(MyEnum::type_ident(), info.type_path_table().ident());
assert_eq!(MyEnum::module_path(), info.type_path_table().module_path());
assert_eq!(MyEnum::crate_name(), info.type_path_table().crate_name());
assert_eq!(
MyEnum::short_type_path(),
info.type_path_table().short_path()
);
// === MyEnum::A === //
assert_eq!("A", info.variant_at(0).unwrap().name());
assert_eq!("A", info.variant("A").unwrap().name());
if let VariantInfo::Unit(variant) = info.variant("A").unwrap() {
assert_eq!("A", variant.name());
} else {
panic!("Expected `VariantInfo::Unit`");
}
// === MyEnum::B === //
assert_eq!("B", info.variant_at(1).unwrap().name());
assert_eq!("B", info.variant("B").unwrap().name());
if let VariantInfo::Tuple(variant) = info.variant("B").unwrap() {
assert!(variant.field_at(0).unwrap().is::<usize>());
assert!(variant.field_at(1).unwrap().is::<i32>());
assert!(variant
.field_at(0)
.unwrap()
.type_info()
.unwrap()
.is::<usize>());
assert!(variant
.field_at(1)
.unwrap()
.type_info()
.unwrap()
.is::<i32>());
} else {
panic!("Expected `VariantInfo::Tuple`");
}
// === MyEnum::C === //
assert_eq!("C", info.variant_at(2).unwrap().name());
assert_eq!("C", info.variant("C").unwrap().name());
if let VariantInfo::Struct(variant) = info.variant("C").unwrap() {
assert!(variant.field_at(0).unwrap().is::<f32>());
assert!(variant.field("foo").unwrap().is::<f32>());
assert!(variant
.field("foo")
.unwrap()
.type_info()
.unwrap()
.is::<f32>());
} else {
panic!("Expected `VariantInfo::Struct`");
}
} else {
panic!("Expected `TypeInfo::Enum`");
}
}
#[test]
fn dynamic_enum_should_set_variant_fields() {
// === Unit === //
let mut value = MyEnum::A;
let dyn_enum = DynamicEnum::from(MyEnum::A);
value.apply(&dyn_enum);
assert_eq!(MyEnum::A, value);
// === Tuple === //
let mut value = MyEnum::B(0, 0);
let dyn_enum = DynamicEnum::from(MyEnum::B(123, 321));
value.apply(&dyn_enum);
assert_eq!(MyEnum::B(123, 321), value);
// === Struct === //
let mut value = MyEnum::C {
foo: 0.0,
bar: false,
};
let dyn_enum = DynamicEnum::from(MyEnum::C {
foo: 1.23,
bar: true,
});
value.apply(&dyn_enum);
assert_eq!(
MyEnum::C {
foo: 1.23,
bar: true,
},
value
);
}
#[test]
fn partial_dynamic_enum_should_set_variant_fields() {
// === Tuple === //
let mut value = MyEnum::B(0, 0);
let mut data = DynamicTuple::default();
data.insert(123usize);
let mut dyn_enum = DynamicEnum::default();
dyn_enum.set_variant("B", data);
value.apply(&dyn_enum);
assert_eq!(MyEnum::B(123, 0), value);
// === Struct === //
let mut value = MyEnum::C {
foo: 1.23,
bar: false,
};
let mut data = DynamicStruct::default();
data.insert("bar", true);
let mut dyn_enum = DynamicEnum::default();
dyn_enum.set_variant("C", data);
value.apply(&dyn_enum);
assert_eq!(
MyEnum::C {
foo: 1.23,
bar: true,
},
value
);
}
#[test]
fn dynamic_enum_should_apply_dynamic_enum() {
let mut a = DynamicEnum::from(MyEnum::B(123, 321));
let b = DynamicEnum::from(MyEnum::B(123, 321));
// Sanity check that equality check works
assert!(
a.reflect_partial_eq(&b).unwrap_or_default(),
"dynamic enums should be equal"
);
a.set_variant("A", ());
assert!(
!a.reflect_partial_eq(&b).unwrap_or_default(),
"dynamic enums should not be equal"
);
a.apply(&b);
assert!(a.reflect_partial_eq(&b).unwrap_or_default());
}
#[test]
fn dynamic_enum_should_change_variant() {
let mut value = MyEnum::A;
// === MyEnum::A -> MyEnum::B === //
let mut dyn_enum = DynamicEnum::from(MyEnum::B(123, 321));
value.apply(&dyn_enum);
assert_eq!(MyEnum::B(123, 321), value);
// === MyEnum::B -> MyEnum::C === //
let mut data = DynamicStruct::default();
data.insert("foo", 1.23_f32);
data.insert("bar", true);
dyn_enum.set_variant("C", data);
value.apply(&dyn_enum);
assert_eq!(
MyEnum::C {
foo: 1.23,
bar: true
},
value
);
// === MyEnum::C -> MyEnum::B === //
let mut data = DynamicTuple::default();
data.insert(123_usize);
data.insert(321_i32);
dyn_enum.set_variant("B", data);
value.apply(&dyn_enum);
assert_eq!(MyEnum::B(123, 321), value);
// === MyEnum::B -> MyEnum::A === //
dyn_enum.set_variant("A", ());
value.apply(&dyn_enum);
assert_eq!(MyEnum::A, value);
}
#[test]
fn dynamic_enum_should_return_is_dynamic() {
let dyn_enum = DynamicEnum::from(MyEnum::B(123, 321));
assert!(dyn_enum.is_dynamic());
}
#[test]
fn enum_should_iterate_fields() {
// === Unit === //
let value: &dyn Enum = &MyEnum::A;
assert_eq!(0, value.field_len());
let mut iter = value.iter_fields();
assert!(iter.next().is_none());
// === Tuple === //
let value: &dyn Enum = &MyEnum::B(123, 321);
assert_eq!(2, value.field_len());
let mut iter = value.iter_fields();
assert!(iter
.next()
.and_then(|field| field.value().reflect_partial_eq(&123_usize))
.unwrap_or_default());
assert!(iter
.next()
.and_then(|field| field.value().reflect_partial_eq(&321_i32))
.unwrap_or_default());
// === Struct === //
let value: &dyn Enum = &MyEnum::C {
foo: 1.23,
bar: true,
};
assert_eq!(2, value.field_len());
let mut iter = value.iter_fields();
assert!(iter
.next()
.and_then(|field| field
.value()
.reflect_partial_eq(&1.23_f32)
.and(field.name().map(|name| name == "foo")))
.unwrap_or_default());
assert!(iter
.next()
.and_then(|field| field
.value()
.reflect_partial_eq(&true)
.and(field.name().map(|name| name == "bar")))
.unwrap_or_default());
}
#[test]
fn enum_should_return_correct_variant_type() {
// === Unit === //
let value = MyEnum::A;
assert_eq!(VariantType::Unit, value.variant_type());
// === Tuple === //
let value = MyEnum::B(0, 0);
assert_eq!(VariantType::Tuple, value.variant_type());
// === Struct === //
let value = MyEnum::C {
foo: 1.23,
bar: true,
};
assert_eq!(VariantType::Struct, value.variant_type());
}
#[test]
fn enum_should_return_correct_variant_path() {
// === Unit === //
let value = MyEnum::A;
assert_eq!(
"bevy_reflect::enums::tests::MyEnum::A",
value.variant_path()
);
// === Tuple === //
let value = MyEnum::B(0, 0);
assert_eq!(
"bevy_reflect::enums::tests::MyEnum::B",
value.variant_path()
);
// === Struct === //
let value = MyEnum::C {
foo: 1.23,
bar: true,
};
assert_eq!(
"bevy_reflect::enums::tests::MyEnum::C",
value.variant_path()
);
}
#[test]
#[should_panic(
expected = "called `Result::unwrap()` on an `Err` value: MismatchedKinds { from_kind: Tuple, to_kind: Enum }"
)]
fn applying_non_enum_should_panic() {
let mut value = MyEnum::B(0, 0);
let mut dyn_tuple = DynamicTuple::default();
dyn_tuple.insert((123_usize, 321_i32));
value.apply(&dyn_tuple);
}
#[test]
fn enum_try_apply_should_detect_type_mismatch() {
#[derive(Reflect, Debug, PartialEq)]
enum MyEnumAnalogue {
A(u32),
B(usize, usize),
C { foo: f32, bar: u8 },
}
let mut target = MyEnumAnalogue::A(0);
// === Tuple === //
let result = target.try_apply(&MyEnum::B(0, 1));
assert!(
matches!(result, Err(ApplyError::MismatchedTypes { .. })),
"`result` was {result:?}"
);
// === Struct === //
target = MyEnumAnalogue::C { foo: 0.0, bar: 1 };
let result = target.try_apply(&MyEnum::C {
foo: 1.0,
bar: true,
});
assert!(
matches!(result, Err(ApplyError::MismatchedTypes { .. })),
"`result` was {result:?}"
);
// Type mismatch should occur after partial application.
assert_eq!(target, MyEnumAnalogue::C { foo: 1.0, bar: 1 });
}
#[test]
fn should_skip_ignored_fields() {
#[derive(Reflect, Debug, PartialEq)]
enum TestEnum {
A,
B,
C {
#[reflect(ignore)]
foo: f32,
bar: bool,
},
}
if let TypeInfo::Enum(info) = TestEnum::type_info() {
assert_eq!(3, info.variant_len());
if let VariantInfo::Struct(variant) = info.variant("C").unwrap() {
assert_eq!(
1,
variant.field_len(),
"expected one of the fields to be ignored"
);
assert!(variant.field_at(0).unwrap().is::<bool>());
} else {
panic!("expected `VariantInfo::Struct`");
}
} else {
panic!("expected `TypeInfo::Enum`");
}
}
#[test]
fn enum_should_allow_generics() {
#[derive(Reflect, Debug, PartialEq)]
enum TestEnum<T: FromReflect> {
A,
B(T),
C { value: T },
}
if let TypeInfo::Enum(info) = TestEnum::<f32>::type_info() {
if let VariantInfo::Tuple(variant) = info.variant("B").unwrap() {
assert!(variant.field_at(0).unwrap().is::<f32>());
} else {
panic!("expected `VariantInfo::Struct`");
}
if let VariantInfo::Struct(variant) = info.variant("C").unwrap() {
assert!(variant.field("value").unwrap().is::<f32>());
} else {
panic!("expected `VariantInfo::Struct`");
}
} else {
panic!("expected `TypeInfo::Enum`");
}
let mut value = TestEnum::<f32>::A;
// === Tuple === //
let mut data = DynamicTuple::default();
data.insert(1.23_f32);
let dyn_enum = DynamicEnum::new("B", data);
value.apply(&dyn_enum);
assert_eq!(TestEnum::B(1.23), value);
// === Struct === //
let mut data = DynamicStruct::default();
data.insert("value", 1.23_f32);
let dyn_enum = DynamicEnum::new("C", data);
value.apply(&dyn_enum);
assert_eq!(TestEnum::C { value: 1.23 }, value);
}
#[test]
fn enum_should_allow_struct_fields() {
#[derive(Reflect, Debug, PartialEq)]
enum TestEnum {
A,
B(TestStruct),
C { value: TestStruct },
}
#[derive(Reflect, Debug, PartialEq)]
struct TestStruct(usize);
let mut value = TestEnum::A;
// === Tuple === //
let mut data = DynamicTuple::default();
data.insert(TestStruct(123));
let dyn_enum = DynamicEnum::new("B", data);
value.apply(&dyn_enum);
assert_eq!(TestEnum::B(TestStruct(123)), value);
// === Struct === //
let mut data = DynamicStruct::default();
data.insert("value", TestStruct(123));
let dyn_enum = DynamicEnum::new("C", data);
value.apply(&dyn_enum);
assert_eq!(
TestEnum::C {
value: TestStruct(123)
},
value
);
}
#[test]
fn enum_should_allow_nesting_enums() {
#[derive(Reflect, Debug, PartialEq)]
enum TestEnum {
A,
B(OtherEnum),
C { value: OtherEnum },
}
#[derive(Reflect, Debug, PartialEq)]
enum OtherEnum {
A,
B(usize),
C { value: f32 },
}
let mut value = TestEnum::A;
// === Tuple === //
let mut data = DynamicTuple::default();
data.insert(OtherEnum::B(123));
let dyn_enum = DynamicEnum::new("B", data);
value.apply(&dyn_enum);
assert_eq!(TestEnum::B(OtherEnum::B(123)), value);
// === Struct === //
let mut data = DynamicStruct::default();
data.insert("value", OtherEnum::C { value: 1.23 });
let dyn_enum = DynamicEnum::new("C", data);
value.apply(&dyn_enum);
assert_eq!(
TestEnum::C {
value: OtherEnum::C { value: 1.23 }
},
value
);
}
#[test]
fn enum_should_apply() {
let mut value: Box<dyn Reflect> = Box::new(MyEnum::A);
// === MyEnum::A -> MyEnum::A === //
value.apply(&MyEnum::A);
assert!(value.reflect_partial_eq(&MyEnum::A).unwrap_or_default());
// === MyEnum::A -> MyEnum::B === //
value.apply(&MyEnum::B(123, 321));
assert!(value
.reflect_partial_eq(&MyEnum::B(123, 321))
.unwrap_or_default());
// === MyEnum::B -> MyEnum::B === //
value.apply(&MyEnum::B(321, 123));
assert!(value
.reflect_partial_eq(&MyEnum::B(321, 123))
.unwrap_or_default());
// === MyEnum::B -> MyEnum::C === //
value.apply(&MyEnum::C {
foo: 1.23,
bar: true,
});
assert!(value
.reflect_partial_eq(&MyEnum::C {
foo: 1.23,
bar: true
})
.unwrap_or_default());
// === MyEnum::C -> MyEnum::C === //
value.apply(&MyEnum::C {
foo: 3.21,
bar: false,
});
assert!(value
.reflect_partial_eq(&MyEnum::C {
foo: 3.21,
bar: false
})
.unwrap_or_default());
// === MyEnum::C -> MyEnum::B === //
value.apply(&MyEnum::B(123, 321));
assert!(value
.reflect_partial_eq(&MyEnum::B(123, 321))
.unwrap_or_default());
// === MyEnum::B -> MyEnum::A === //
value.apply(&MyEnum::A);
assert!(value.reflect_partial_eq(&MyEnum::A).unwrap_or_default());
}
#[test]
fn enum_should_set() {
let mut value: Box<dyn Reflect> = Box::new(MyEnum::A);
// === MyEnum::A -> MyEnum::A === //
value.set(Box::new(MyEnum::A)).unwrap();
assert!(value.reflect_partial_eq(&MyEnum::A).unwrap_or_default());
// === MyEnum::A -> MyEnum::B === //
value.set(Box::new(MyEnum::B(123, 321))).unwrap();
assert!(value
.reflect_partial_eq(&MyEnum::B(123, 321))
.unwrap_or_default());
// === MyEnum::B -> MyEnum::B === //
value.set(Box::new(MyEnum::B(321, 123))).unwrap();
assert!(value
.reflect_partial_eq(&MyEnum::B(321, 123))
.unwrap_or_default());
// === MyEnum::B -> MyEnum::C === //
value
.set(Box::new(MyEnum::C {
foo: 1.23,
bar: true,
}))
.unwrap();
assert!(value
.reflect_partial_eq(&MyEnum::C {
foo: 1.23,
bar: true
})
.unwrap_or_default());
// === MyEnum::C -> MyEnum::C === //
value
.set(Box::new(MyEnum::C {
foo: 3.21,
bar: false,
}))
.unwrap();
assert!(value
.reflect_partial_eq(&MyEnum::C {
foo: 3.21,
bar: false
})
.unwrap_or_default());
// === MyEnum::C -> MyEnum::B === //
value.set(Box::new(MyEnum::B(123, 321))).unwrap();
assert!(value
.reflect_partial_eq(&MyEnum::B(123, 321))
.unwrap_or_default());
// === MyEnum::B -> MyEnum::A === //
value.set(Box::new(MyEnum::A)).unwrap();
assert!(value.reflect_partial_eq(&MyEnum::A).unwrap_or_default());
}
#[test]
fn enum_should_partial_eq() {
#[derive(Reflect)]
enum TestEnum {
A,
A1,
B(usize),
B1(usize),
B2(usize, usize),
C { value: i32 },
C1 { value: i32 },
C2 { value: f32 },
}
let a: &dyn PartialReflect = &TestEnum::A;
let b: &dyn PartialReflect = &TestEnum::A;
assert!(
a.reflect_partial_eq(b).unwrap_or_default(),
"expected TestEnum::A == TestEnum::A"
);
let a: &dyn PartialReflect = &TestEnum::A;
let b: &dyn PartialReflect = &TestEnum::A1;
assert!(
!a.reflect_partial_eq(b).unwrap_or_default(),
"expected TestEnum::A != TestEnum::A1"
);
let a: &dyn PartialReflect = &TestEnum::B(123);
let b: &dyn PartialReflect = &TestEnum::B(123);
assert!(
a.reflect_partial_eq(b).unwrap_or_default(),
"expected TestEnum::B(123) == TestEnum::B(123)"
);
let a: &dyn PartialReflect = &TestEnum::B(123);
let b: &dyn PartialReflect = &TestEnum::B(321);
assert!(
!a.reflect_partial_eq(b).unwrap_or_default(),
"expected TestEnum::B(123) != TestEnum::B(321)"
);
let a: &dyn PartialReflect = &TestEnum::B(123);
let b: &dyn PartialReflect = &TestEnum::B1(123);
assert!(
!a.reflect_partial_eq(b).unwrap_or_default(),
"expected TestEnum::B(123) != TestEnum::B1(123)"
);
let a: &dyn PartialReflect = &TestEnum::B(123);
let b: &dyn PartialReflect = &TestEnum::B2(123, 123);
assert!(
!a.reflect_partial_eq(b).unwrap_or_default(),
"expected TestEnum::B(123) != TestEnum::B2(123, 123)"
);
let a: &dyn PartialReflect = &TestEnum::C { value: 123 };
let b: &dyn PartialReflect = &TestEnum::C { value: 123 };
assert!(
a.reflect_partial_eq(b).unwrap_or_default(),
"expected TestEnum::C{{value: 123}} == TestEnum::C{{value: 123}}"
);
let a: &dyn PartialReflect = &TestEnum::C { value: 123 };
let b: &dyn PartialReflect = &TestEnum::C { value: 321 };
assert!(
!a.reflect_partial_eq(b).unwrap_or_default(),
"expected TestEnum::C{{value: 123}} != TestEnum::C{{value: 321}}"
);
let a: &dyn PartialReflect = &TestEnum::C { value: 123 };
let b: &dyn PartialReflect = &TestEnum::C1 { value: 123 };
assert!(
!a.reflect_partial_eq(b).unwrap_or_default(),
"expected TestEnum::C{{value: 123}} != TestEnum::C1{{value: 123}}"
);
let a: &dyn PartialReflect = &TestEnum::C { value: 123 };
let b: &dyn PartialReflect = &TestEnum::C2 { value: 1.23 };
assert!(
!a.reflect_partial_eq(b).unwrap_or_default(),
"expected TestEnum::C{{value: 123}} != TestEnum::C2{{value: 1.23}}"
);
}
}
| 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/enums/enum_trait.rs | crates/bevy_reflect/src/enums/enum_trait.rs | use crate::generics::impl_generic_info_methods;
use crate::{
attributes::{impl_custom_attribute_methods, CustomAttributes},
type_info::impl_type_methods,
DynamicEnum, Generics, PartialReflect, Type, TypePath, VariantInfo, VariantType,
};
use alloc::{boxed::Box, format, string::String};
use bevy_platform::collections::HashMap;
use bevy_platform::sync::Arc;
use core::slice::Iter;
/// A trait used to power [enum-like] operations via [reflection].
///
/// This allows enums to be processed and modified dynamically at runtime without
/// necessarily knowing the actual type.
/// Enums are much more complex than their struct counterparts.
/// As a result, users will need to be mindful of conventions, considerations,
/// and complications when working with this trait.
///
/// # Variants
///
/// An enum is a set of choices called _variants_.
/// An instance of an enum can only exist as one of these choices at any given time.
/// Consider Rust's [`Option<T>`]. It's an enum with two variants: [`None`] and [`Some`].
/// If you're `None`, you can't be `Some` and vice versa.
///
/// > ⚠️ __This is very important:__
/// > The [`Enum`] trait represents an enum _as one of its variants_.
/// > It does not represent the entire enum since that's not true to how enums work.
///
/// Variants come in a few [flavors](VariantType):
///
/// | Variant Type | Syntax |
/// | ------------ | ------------------------------ |
/// | Unit | `MyEnum::Foo` |
/// | Tuple | `MyEnum::Foo( i32, i32 )` |
/// | Struct | `MyEnum::Foo{ value: String }` |
///
/// As you can see, a unit variant contains no fields, while tuple and struct variants
/// can contain one or more fields.
/// The fields in a tuple variant is defined by their _order_ within the variant.
/// Index `0` represents the first field in the variant and so on.
/// Fields in struct variants (excluding tuple structs), on the other hand, are
/// represented by a _name_.
///
/// # Implementation
///
/// > 💡 This trait can be automatically implemented using [`#[derive(Reflect)]`](derive@crate::Reflect)
/// > on an enum definition.
///
/// Despite the fact that enums can represent multiple states, traits only exist in one state
/// and must be applied to the entire enum rather than a particular variant.
/// Because of this limitation, the [`Enum`] trait must not only _represent_ any of the
/// three variant types, but also define the _methods_ for all three as well.
///
/// What does this mean? It means that even though a unit variant contains no fields, a
/// representation of that variant using the [`Enum`] trait will still contain methods for
/// accessing fields!
/// Again, this is to account for _all three_ variant types.
///
/// We recommend using the built-in [`#[derive(Reflect)]`](derive@crate::Reflect) macro to automatically handle all the
/// implementation details for you.
/// However, if you _must_ implement this trait manually, there are a few things to keep in mind...
///
/// ## Field Order
///
/// While tuple variants identify their fields by the order in which they are defined, struct
/// variants identify fields by their name.
/// However, both should allow access to fields by their defined order.
///
/// The reason all fields, regardless of variant type, need to be accessible by their order is
/// due to field iteration.
/// We need a way to iterate through each field in a variant, and the easiest way of achieving
/// that is through the use of field order.
///
/// The derive macro adds proper struct variant handling for [`Enum::index_of`], [`Enum::name_at`]
/// and [`Enum::field_at[_mut]`](Enum::field_at) methods.
/// The first two methods are __required__ for all struct variant types.
/// By convention, implementors should also handle the last method as well, but this is not
/// a strict requirement.
///
/// ## Field Names
///
/// Implementors may choose to handle [`Enum::index_of`], [`Enum::name_at`], and
/// [`Enum::field[_mut]`](Enum::field) for tuple variants by considering stringified `usize`s to be
/// valid names (such as `"3"`).
/// This isn't wrong to do, but the convention set by the derive macro is that it isn't supported.
/// It's preferred that these strings be converted to their proper `usize` representations and
/// the [`Enum::field_at[_mut]`](Enum::field_at) methods be used instead.
///
/// [enum-like]: https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html
/// [reflection]: crate
/// [`None`]: Option<T>::None
/// [`Some`]: Option<T>::Some
/// [`Reflect`]: bevy_reflect_derive::Reflect
pub trait Enum: PartialReflect {
/// Returns a reference to the value of the field (in the current variant) with the given name.
///
/// For non-[`VariantType::Struct`] variants, this should return `None`.
fn field(&self, name: &str) -> Option<&dyn PartialReflect>;
/// Returns a reference to the value of the field (in the current variant) at the given index.
fn field_at(&self, index: usize) -> Option<&dyn PartialReflect>;
/// Returns a mutable reference to the value of the field (in the current variant) with the given name.
///
/// For non-[`VariantType::Struct`] variants, this should return `None`.
fn field_mut(&mut self, name: &str) -> Option<&mut dyn PartialReflect>;
/// Returns a mutable reference to the value of the field (in the current variant) at the given index.
fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>;
/// Returns the index of the field (in the current variant) with the given name.
///
/// For non-[`VariantType::Struct`] variants, this should return `None`.
fn index_of(&self, name: &str) -> Option<usize>;
/// Returns the name of the field (in the current variant) with the given index.
///
/// For non-[`VariantType::Struct`] variants, this should return `None`.
fn name_at(&self, index: usize) -> Option<&str>;
/// Returns an iterator over the values of the current variant's fields.
fn iter_fields(&self) -> VariantFieldIter<'_>;
/// Returns the number of fields in the current variant.
fn field_len(&self) -> usize;
/// The name of the current variant.
fn variant_name(&self) -> &str;
/// The index of the current variant.
fn variant_index(&self) -> usize;
/// The type of the current variant.
fn variant_type(&self) -> VariantType;
/// Creates a new [`DynamicEnum`] from this enum.
fn to_dynamic_enum(&self) -> DynamicEnum {
DynamicEnum::from_ref(self)
}
/// Returns true if the current variant's type matches the given one.
fn is_variant(&self, variant_type: VariantType) -> bool {
self.variant_type() == variant_type
}
/// Returns the full path to the current variant.
fn variant_path(&self) -> String {
format!("{}::{}", self.reflect_type_path(), self.variant_name())
}
/// Will return `None` if [`TypeInfo`] is not available.
///
/// [`TypeInfo`]: crate::TypeInfo
fn get_represented_enum_info(&self) -> Option<&'static EnumInfo> {
self.get_represented_type_info()?.as_enum().ok()
}
}
/// A container for compile-time enum info, used by [`TypeInfo`](crate::TypeInfo).
#[derive(Clone, Debug)]
pub struct EnumInfo {
ty: Type,
generics: Generics,
variants: Box<[VariantInfo]>,
variant_names: Box<[&'static str]>,
variant_indices: HashMap<&'static str, usize>,
custom_attributes: Arc<CustomAttributes>,
#[cfg(feature = "reflect_documentation")]
docs: Option<&'static str>,
}
impl EnumInfo {
/// Create a new [`EnumInfo`].
///
/// # Arguments
///
/// * `variants`: The variants of this enum in the order they are defined
pub fn new<TEnum: Enum + TypePath>(variants: &[VariantInfo]) -> Self {
let variant_indices = variants
.iter()
.enumerate()
.map(|(index, variant)| (variant.name(), index))
.collect::<HashMap<_, _>>();
let variant_names = variants.iter().map(VariantInfo::name).collect();
Self {
ty: Type::of::<TEnum>(),
generics: Generics::new(),
variants: variants.to_vec().into_boxed_slice(),
variant_names,
variant_indices,
custom_attributes: Arc::new(CustomAttributes::default()),
#[cfg(feature = "reflect_documentation")]
docs: None,
}
}
/// Sets the docstring for this enum.
#[cfg(feature = "reflect_documentation")]
pub fn with_docs(self, docs: Option<&'static str>) -> Self {
Self { docs, ..self }
}
/// Sets the custom attributes for this enum.
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 variants in order.
pub fn variant_names(&self) -> &[&'static str] {
&self.variant_names
}
/// Get a variant with the given name.
pub fn variant(&self, name: &str) -> Option<&VariantInfo> {
self.variant_indices
.get(name)
.map(|index| &self.variants[*index])
}
/// Get a variant at the given index.
pub fn variant_at(&self, index: usize) -> Option<&VariantInfo> {
self.variants.get(index)
}
/// Get the index of the variant with the given name.
pub fn index_of(&self, name: &str) -> Option<usize> {
self.variant_indices.get(name).copied()
}
/// Returns the full path to the given variant.
///
/// This does _not_ check if the given variant exists.
pub fn variant_path(&self, name: &str) -> String {
format!("{}::{name}", self.type_path())
}
/// Checks if a variant with the given name exists within this enum.
pub fn contains_variant(&self, name: &str) -> bool {
self.variant_indices.contains_key(name)
}
/// Iterate over the variants of this enum.
pub fn iter(&self) -> Iter<'_, VariantInfo> {
self.variants.iter()
}
/// The number of variants in this enum.
pub fn variant_len(&self) -> usize {
self.variants.len()
}
impl_type_methods!(ty);
/// The docstring of this enum, if any.
#[cfg(feature = "reflect_documentation")]
pub fn docs(&self) -> Option<&'static str> {
self.docs
}
impl_custom_attribute_methods!(self.custom_attributes, "enum");
impl_generic_info_methods!(generics);
}
/// An iterator over the fields in the current enum variant.
pub struct VariantFieldIter<'a> {
container: &'a dyn Enum,
index: usize,
}
impl<'a> VariantFieldIter<'a> {
/// Creates a new [`VariantFieldIter`].
pub fn new(container: &'a dyn Enum) -> Self {
Self {
container,
index: 0,
}
}
}
impl<'a> Iterator for VariantFieldIter<'a> {
type Item = VariantField<'a>;
fn next(&mut self) -> Option<Self::Item> {
let value = match self.container.variant_type() {
VariantType::Unit => None,
VariantType::Tuple => Some(VariantField::Tuple(self.container.field_at(self.index)?)),
VariantType::Struct => {
let name = self.container.name_at(self.index)?;
Some(VariantField::Struct(name, self.container.field(name)?))
}
};
self.index += value.is_some() as usize;
value
}
fn size_hint(&self) -> (usize, Option<usize>) {
let size = self.container.field_len();
(size, Some(size))
}
}
impl<'a> ExactSizeIterator for VariantFieldIter<'a> {}
/// A field in the current enum variant.
pub enum VariantField<'a> {
/// The name and value of a field in a struct variant.
Struct(&'a str, &'a dyn PartialReflect),
/// The value of a field in a tuple variant.
Tuple(&'a dyn PartialReflect),
}
impl<'a> VariantField<'a> {
/// Returns the name of a struct variant field, or [`None`] for a tuple variant field.
pub fn name(&self) -> Option<&'a str> {
if let Self::Struct(name, ..) = self {
Some(*name)
} else {
None
}
}
/// Gets a reference to the value of this field.
pub fn value(&self) -> &'a dyn PartialReflect {
match *self {
Self::Struct(_, value) | Self::Tuple(value) => value,
}
}
}
// Tests that need access to internal fields have to go here rather than in mod.rs
#[cfg(test)]
mod tests {
use crate::*;
#[derive(Reflect, Debug, PartialEq)]
enum MyEnum {
A,
B(usize, i32),
C { foo: f32, bar: bool },
}
#[test]
fn next_index_increment() {
// unit enums always return none, so index should stay at 0
let unit_enum = MyEnum::A;
let mut iter = unit_enum.iter_fields();
let size = iter.len();
for _ in 0..2 {
assert!(iter.next().is_none());
assert_eq!(size, iter.index);
}
// tuple enums we iter over each value (unnamed fields), stop after that
let tuple_enum = MyEnum::B(0, 1);
let mut iter = tuple_enum.iter_fields();
let size = iter.len();
for _ in 0..2 {
let prev_index = iter.index;
assert!(iter.next().is_some());
assert_eq!(prev_index, iter.index - 1);
}
for _ in 0..2 {
assert!(iter.next().is_none());
assert_eq!(size, iter.index);
}
// struct enums, we iterate over each field in the struct
let struct_enum = MyEnum::C {
foo: 0.,
bar: false,
};
let mut iter = struct_enum.iter_fields();
let size = iter.len();
for _ in 0..2 {
let prev_index = iter.index;
assert!(iter.next().is_some());
assert_eq!(prev_index, iter.index - 1);
}
for _ in 0..2 {
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/enums/dynamic_enum.rs | crates/bevy_reflect/src/enums/dynamic_enum.rs | use bevy_reflect_derive::impl_type_path;
use crate::{
enum_debug, enum_hash, enum_partial_eq, ApplyError, DynamicStruct, DynamicTuple, Enum,
PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Struct, Tuple,
TypeInfo, VariantFieldIter, VariantType,
};
use alloc::{boxed::Box, string::String};
use core::fmt::Formatter;
use derive_more::derive::From;
/// A dynamic representation of an enum variant.
#[derive(Debug, Default, From)]
pub enum DynamicVariant {
/// A unit variant.
#[default]
Unit,
/// A tuple variant.
Tuple(DynamicTuple),
/// A struct variant.
Struct(DynamicStruct),
}
impl Clone for DynamicVariant {
fn clone(&self) -> Self {
match self {
DynamicVariant::Unit => DynamicVariant::Unit,
DynamicVariant::Tuple(data) => DynamicVariant::Tuple(data.to_dynamic_tuple()),
DynamicVariant::Struct(data) => DynamicVariant::Struct(data.to_dynamic_struct()),
}
}
}
impl From<()> for DynamicVariant {
fn from(_: ()) -> Self {
Self::Unit
}
}
/// A dynamic representation of an enum.
///
/// This allows for enums to be configured at runtime.
///
/// # Example
///
/// ```
/// # use bevy_reflect::{DynamicEnum, DynamicVariant, Reflect, PartialReflect};
///
/// // The original enum value
/// let mut value: Option<usize> = Some(123);
///
/// // Create a DynamicEnum to represent the new value
/// let mut dyn_enum = DynamicEnum::new(
/// "None",
/// DynamicVariant::Unit
/// );
///
/// // Apply the DynamicEnum as a patch to the original value
/// value.apply(dyn_enum.as_partial_reflect());
///
/// // Tada!
/// assert_eq!(None, value);
/// ```
#[derive(Default, Debug)]
pub struct DynamicEnum {
represented_type: Option<&'static TypeInfo>,
variant_name: String,
variant_index: usize,
variant: DynamicVariant,
}
impl DynamicEnum {
/// Create a new [`DynamicEnum`] to represent an enum at runtime.
///
/// # Arguments
///
/// * `variant_name`: The name of the variant to set
/// * `variant`: The variant data
pub fn new<I: Into<String>, V: Into<DynamicVariant>>(variant_name: I, variant: V) -> Self {
Self {
represented_type: None,
variant_index: 0,
variant_name: variant_name.into(),
variant: variant.into(),
}
}
/// Create a new [`DynamicEnum`] with a variant index to represent an enum at runtime.
///
/// # Arguments
///
/// * `variant_index`: The index of the variant to set
/// * `variant_name`: The name of the variant to set
/// * `variant`: The variant data
pub fn new_with_index<I: Into<String>, V: Into<DynamicVariant>>(
variant_index: usize,
variant_name: I,
variant: V,
) -> Self {
Self {
represented_type: None,
variant_index,
variant_name: variant_name.into(),
variant: variant.into(),
}
}
/// Sets the [type] to be represented by this `DynamicEnum`.
///
/// # Panics
///
/// Panics if the given [type] is not a [`TypeInfo::Enum`].
///
/// [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::Enum(_)),
"expected TypeInfo::Enum but received: {represented_type:?}",
);
}
self.represented_type = represented_type;
}
/// Set the current enum variant represented by this struct.
pub fn set_variant<I: Into<String>, V: Into<DynamicVariant>>(&mut self, name: I, variant: V) {
self.variant_name = name.into();
self.variant = variant.into();
}
/// Set the current enum variant represented by this struct along with its variant index.
pub fn set_variant_with_index<I: Into<String>, V: Into<DynamicVariant>>(
&mut self,
variant_index: usize,
variant_name: I,
variant: V,
) {
self.variant_index = variant_index;
self.variant_name = variant_name.into();
self.variant = variant.into();
}
/// Get a reference to the [`DynamicVariant`] contained in `self`.
pub fn variant(&self) -> &DynamicVariant {
&self.variant
}
/// Get a mutable reference to the [`DynamicVariant`] contained in `self`.
///
/// Using the mut reference to switch to a different variant will ___not___ update the
/// internal tracking of the variant name and index.
///
/// If you want to switch variants, prefer one of the setters:
/// [`DynamicEnum::set_variant`] or [`DynamicEnum::set_variant_with_index`].
pub fn variant_mut(&mut self) -> &mut DynamicVariant {
&mut self.variant
}
/// Create a [`DynamicEnum`] from an existing one.
///
/// This is functionally the same as [`DynamicEnum::from_ref`] except it takes an owned value.
pub fn from<TEnum: Enum>(value: TEnum) -> Self {
Self::from_ref(&value)
}
/// Create a [`DynamicEnum`] from an existing one.
///
/// This is functionally the same as [`DynamicEnum::from`] except it takes a reference.
pub fn from_ref<TEnum: Enum + ?Sized>(value: &TEnum) -> Self {
let type_info = value.get_represented_type_info();
let mut dyn_enum = match value.variant_type() {
VariantType::Unit => DynamicEnum::new_with_index(
value.variant_index(),
value.variant_name(),
DynamicVariant::Unit,
),
VariantType::Tuple => {
let mut data = DynamicTuple::default();
for field in value.iter_fields() {
data.insert_boxed(field.value().to_dynamic());
}
DynamicEnum::new_with_index(
value.variant_index(),
value.variant_name(),
DynamicVariant::Tuple(data),
)
}
VariantType::Struct => {
let mut data = DynamicStruct::default();
for field in value.iter_fields() {
let name = field.name().unwrap();
data.insert_boxed(name, field.value().to_dynamic());
}
DynamicEnum::new_with_index(
value.variant_index(),
value.variant_name(),
DynamicVariant::Struct(data),
)
}
};
dyn_enum.set_represented_type(type_info);
dyn_enum
}
}
impl Enum for DynamicEnum {
fn field(&self, name: &str) -> Option<&dyn PartialReflect> {
if let DynamicVariant::Struct(data) = &self.variant {
data.field(name)
} else {
None
}
}
fn field_at(&self, index: usize) -> Option<&dyn PartialReflect> {
match &self.variant {
DynamicVariant::Tuple(data) => data.field(index),
DynamicVariant::Struct(data) => data.field_at(index),
DynamicVariant::Unit => None,
}
}
fn field_mut(&mut self, name: &str) -> Option<&mut dyn PartialReflect> {
if let DynamicVariant::Struct(data) = &mut self.variant {
data.field_mut(name)
} else {
None
}
}
fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> {
match &mut self.variant {
DynamicVariant::Tuple(data) => data.field_mut(index),
DynamicVariant::Struct(data) => data.field_at_mut(index),
DynamicVariant::Unit => None,
}
}
fn index_of(&self, name: &str) -> Option<usize> {
if let DynamicVariant::Struct(data) = &self.variant {
data.index_of(name)
} else {
None
}
}
fn name_at(&self, index: usize) -> Option<&str> {
if let DynamicVariant::Struct(data) = &self.variant {
data.name_at(index)
} else {
None
}
}
fn iter_fields(&self) -> VariantFieldIter<'_> {
VariantFieldIter::new(self)
}
fn field_len(&self) -> usize {
match &self.variant {
DynamicVariant::Unit => 0,
DynamicVariant::Tuple(data) => data.field_len(),
DynamicVariant::Struct(data) => data.field_len(),
}
}
fn variant_name(&self) -> &str {
&self.variant_name
}
fn variant_index(&self) -> usize {
self.variant_index
}
fn variant_type(&self) -> VariantType {
match &self.variant {
DynamicVariant::Unit => VariantType::Unit,
DynamicVariant::Tuple(..) => VariantType::Tuple,
DynamicVariant::Struct(..) => VariantType::Struct,
}
}
}
impl PartialReflect for DynamicEnum {
#[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
}
#[inline]
fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
let value = value.reflect_ref().as_enum()?;
if Enum::variant_name(self) == value.variant_name() {
// Same variant -> just update fields
match value.variant_type() {
VariantType::Struct => {
for field in value.iter_fields() {
let name = field.name().unwrap();
if let Some(v) = Enum::field_mut(self, name) {
v.try_apply(field.value())?;
}
}
}
VariantType::Tuple => {
for (index, field) in value.iter_fields().enumerate() {
if let Some(v) = Enum::field_at_mut(self, index) {
v.try_apply(field.value())?;
}
}
}
_ => {}
}
} else {
// New variant -> perform a switch
let dyn_variant = match value.variant_type() {
VariantType::Unit => DynamicVariant::Unit,
VariantType::Tuple => {
let mut dyn_tuple = DynamicTuple::default();
for field in value.iter_fields() {
dyn_tuple.insert_boxed(field.value().to_dynamic());
}
DynamicVariant::Tuple(dyn_tuple)
}
VariantType::Struct => {
let mut dyn_struct = DynamicStruct::default();
for field in value.iter_fields() {
dyn_struct.insert_boxed(field.name().unwrap(), field.value().to_dynamic());
}
DynamicVariant::Struct(dyn_struct)
}
};
self.set_variant(value.variant_name(), dyn_variant);
}
Ok(())
}
#[inline]
fn reflect_kind(&self) -> ReflectKind {
ReflectKind::Enum
}
#[inline]
fn reflect_ref(&self) -> ReflectRef<'_> {
ReflectRef::Enum(self)
}
#[inline]
fn reflect_mut(&mut self) -> ReflectMut<'_> {
ReflectMut::Enum(self)
}
#[inline]
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
ReflectOwned::Enum(self)
}
#[inline]
fn reflect_hash(&self) -> Option<u64> {
enum_hash(self)
}
#[inline]
fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
enum_partial_eq(self, value)
}
#[inline]
fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "DynamicEnum(")?;
enum_debug(self, f)?;
write!(f, ")")
}
#[inline]
fn is_dynamic(&self) -> bool {
true
}
}
impl_type_path!((in bevy_reflect) DynamicEnum);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/examples/reflect_docs.rs | crates/bevy_reflect/examples/reflect_docs.rs | //! This example illustrates how you can reflect doc comments.
//!
//! There may be cases where you may want to collect a reflected item's documentation.
//! For example, you may want to generate schemas or other external documentation for scripting.
//! Or perhaps you want your custom editor to display tooltips for certain properties that match the documentation.
//!
//! These scenarios can readily be achieved by using `bevy_reflect` with the `reflect_documentation` feature.
#![expect(clippy::print_stdout, reason = "Allowed in examples.")]
use bevy_reflect::{Reflect, TypeInfo, Typed};
fn main() {
//! This function will simply demonstrate how you can access a type's documentation.
//!
//! Please note that the code below uses a standard struct with named fields; however, this isn't
//! exclusive to them. It can work for all kinds of data types including tuple structs and enums too!
/// The struct that defines our player.
///
/// # Example
///
/// ```
/// let player = Player::new("Urist McPlayer");
/// ```
#[derive(Reflect)]
struct Player {
/// The player's name.
name: String,
/// The player's current health points.
hp: u8,
// Some regular comment (i.e. not a doc comment)
max_hp: u8,
}
// Using `TypeInfo` we can access all of the doc comments on the `Player` struct above:
let player_info = <Player as Typed>::type_info();
// From here, we already have access to the struct's docs:
let player_docs = player_info.docs().unwrap();
assert_eq!(" The struct that defines our player.\n\n # Example\n\n ```\n let player = Player::new(\"Urist McPlayer\");\n ```", player_docs);
println!("=====[ Player ]=====\n{player_docs}");
// We can then iterate through our struct's fields to get their documentation as well:
if let TypeInfo::Struct(struct_info) = player_info {
for field in struct_info.iter() {
let field_name = field.name();
let field_docs = field.docs().unwrap_or("<NO_DOCUMENTATION>");
println!("-----[ Player::{field_name} ]-----\n{field_docs}");
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/documentation.rs | crates/bevy_reflect/derive/src/documentation.rs | //! Contains code related to documentation reflection (requires the `documentation` feature).
use bevy_macro_utils::fq_std::FQOption;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{Attribute, Expr, ExprLit, Lit, Meta};
/// A struct used to represent a type's documentation, if any.
///
/// When converted to a [`TokenStream`], this will output an `Option<String>`
/// containing the collection of doc comments.
#[derive(Default, Clone)]
pub(crate) struct Documentation {
docs: Vec<String>,
}
impl Documentation {
/// Create a new [`Documentation`] from a type's attributes.
///
/// This will collect all `#[doc = "..."]` attributes, including the ones generated via `///` and `//!`.
pub fn from_attributes<'a>(attributes: impl IntoIterator<Item = &'a Attribute>) -> Self {
let docs = attributes
.into_iter()
.filter_map(|attr| match &attr.meta {
Meta::NameValue(pair) if pair.path.is_ident("doc") => {
if let Expr::Lit(ExprLit {
lit: Lit::Str(lit), ..
}) = &pair.value
{
Some(lit.value())
} else {
None
}
}
_ => None,
})
.collect();
Self { docs }
}
/// The full docstring, if any.
pub fn doc_string(&self) -> Option<String> {
if self.docs.is_empty() {
return None;
}
let len = self.docs.len();
Some(
self.docs
.iter()
.enumerate()
.map(|(index, doc)| {
if index < len - 1 {
format!("{doc}\n")
} else {
doc.to_owned()
}
})
.collect(),
)
}
/// Is the collection empty?
pub fn is_empty(&self) -> bool {
self.docs.is_empty()
}
/// Push a new docstring to the collection
pub fn push(&mut self, doc: String) {
self.docs.push(doc);
}
}
impl ToTokens for Documentation {
fn to_tokens(&self, tokens: &mut TokenStream) {
if let Some(doc) = self.doc_string() {
quote!(#FQOption::Some(#doc)).to_tokens(tokens);
} else {
quote!(#FQOption::None).to_tokens(tokens);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/trait_reflection.rs | crates/bevy_reflect/derive/src/trait_reflection.rs | use bevy_macro_utils::fq_std::{FQClone, FQOption, FQResult};
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse::Parse, parse_macro_input, Attribute, ItemTrait, Token};
pub(crate) struct TraitInfo {
item_trait: ItemTrait,
}
impl Parse for TraitInfo {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let attrs = input.call(Attribute::parse_outer)?;
let lookahead = input.lookahead1();
if lookahead.peek(Token![pub]) || lookahead.peek(Token![trait]) {
let mut item_trait: ItemTrait = input.parse()?;
item_trait.attrs = attrs;
Ok(TraitInfo { item_trait })
} else {
Err(lookahead.error())
}
}
}
/// A trait attribute macro that allows a reflected type to be downcast to a trait object.
///
/// This generates a struct that takes the form `ReflectMyTrait`. An instance of this struct can then be
/// used to perform the conversion.
pub(crate) fn reflect_trait(_args: &TokenStream, input: TokenStream) -> TokenStream {
let trait_info = parse_macro_input!(input as TraitInfo);
let item_trait = &trait_info.item_trait;
let trait_ident = &item_trait.ident;
let trait_vis = &item_trait.vis;
let reflect_trait_ident = crate::ident::get_reflect_ident(&item_trait.ident.to_string());
let bevy_reflect_path = crate::meta::get_bevy_reflect_path();
let struct_doc = format!(
" A type generated by the #[reflect_trait] macro for the `{trait_ident}` trait.\n\n This allows casting from `dyn Reflect` to `dyn {trait_ident}`.",
);
let get_doc = format!(
" Downcast a `&dyn Reflect` type to `&dyn {trait_ident}`.\n\n If the type cannot be downcast, `None` is returned.",
);
let get_mut_doc = format!(
" Downcast a `&mut dyn Reflect` type to `&mut dyn {trait_ident}`.\n\n If the type cannot be downcast, `None` is returned.",
);
let get_box_doc = format!(
" Downcast a `Box<dyn Reflect>` type to `Box<dyn {trait_ident}>`.\n\n If the type cannot be downcast, this will return `Err(Box<dyn Reflect>)`.",
);
TokenStream::from(quote! {
#item_trait
#[doc = #struct_doc]
#[derive(#FQClone)]
#trait_vis struct #reflect_trait_ident {
get_func: fn(&dyn #bevy_reflect_path::Reflect) -> #FQOption<&dyn #trait_ident>,
get_mut_func: fn(&mut dyn #bevy_reflect_path::Reflect) -> #FQOption<&mut dyn #trait_ident>,
get_boxed_func: fn(#bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #bevy_reflect_path::Reflect>) -> #FQResult<#bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #trait_ident>, #bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #bevy_reflect_path::Reflect>>,
}
impl #reflect_trait_ident {
#[doc = #get_doc]
pub fn get<'a>(&self, reflect_value: &'a dyn #bevy_reflect_path::Reflect) -> #FQOption<&'a dyn #trait_ident> {
(self.get_func)(reflect_value)
}
#[doc = #get_mut_doc]
pub fn get_mut<'a>(&self, reflect_value: &'a mut dyn #bevy_reflect_path::Reflect) -> #FQOption<&'a mut dyn #trait_ident> {
(self.get_mut_func)(reflect_value)
}
#[doc = #get_box_doc]
pub fn get_boxed(&self, reflect_value: #bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #bevy_reflect_path::Reflect>) -> #FQResult<#bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #trait_ident>, #bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #bevy_reflect_path::Reflect>> {
(self.get_boxed_func)(reflect_value)
}
}
impl<T: #trait_ident + #bevy_reflect_path::Reflect> #bevy_reflect_path::FromType<T> for #reflect_trait_ident {
fn from_type() -> Self {
Self {
get_func: |reflect_value| {
<dyn #bevy_reflect_path::Reflect>::downcast_ref::<T>(reflect_value).map(|value| value as &dyn #trait_ident)
},
get_mut_func: |reflect_value| {
<dyn #bevy_reflect_path::Reflect>::downcast_mut::<T>(reflect_value).map(|value| value as &mut dyn #trait_ident)
},
get_boxed_func: |reflect_value| {
<dyn #bevy_reflect_path::Reflect>::downcast::<T>(reflect_value).map(|value| value as #bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #trait_ident>)
}
}
}
}
})
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/string_expr.rs | crates/bevy_reflect/derive/src/string_expr.rs | use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{spanned::Spanned, LitStr};
/// Contains tokens representing different kinds of string.
#[derive(Clone)]
pub(crate) enum StringExpr {
/// A string that is valid at compile time.
///
/// This is either a string literal like `"mystring"`,
/// or a string created by a macro like [`module_path`]
/// or [`concat`].
Const(TokenStream),
/// A [string slice](str) that is borrowed for a `'static` lifetime.
Borrowed(TokenStream),
/// An [owned string](String).
Owned(TokenStream),
}
impl<T: ToString + Spanned> From<T> for StringExpr {
fn from(value: T) -> Self {
Self::from_lit(&LitStr::new(&value.to_string(), value.span()))
}
}
impl StringExpr {
/// Creates a [constant] [`StringExpr`] from a [`struct@LitStr`].
///
/// [constant]: StringExpr::Const
pub fn from_lit(lit: &LitStr) -> Self {
Self::Const(lit.to_token_stream())
}
/// Creates a [constant] [`StringExpr`] by interpreting a [string slice][str] as a [`struct@LitStr`].
///
/// [constant]: StringExpr::Const
pub fn from_str(string: &str) -> Self {
Self::Const(string.into_token_stream())
}
/// Returns tokens for an [owned string](String).
///
/// The returned expression will allocate unless the [`StringExpr`] is [already owned].
///
/// [already owned]: StringExpr::Owned
pub fn into_owned(self) -> TokenStream {
let bevy_reflect_path = crate::meta::get_bevy_reflect_path();
match self {
Self::Const(tokens) | Self::Borrowed(tokens) => quote! {
#bevy_reflect_path::__macro_exports::alloc_utils::ToString::to_string(#tokens)
},
Self::Owned(owned) => owned,
}
}
/// Returns tokens for a statically borrowed [string slice](str).
pub fn into_borrowed(self) -> TokenStream {
match self {
Self::Const(tokens) | Self::Borrowed(tokens) => tokens,
Self::Owned(owned) => quote! {
&#owned
},
}
}
/// Appends a [`StringExpr`] to another.
///
/// If both expressions are [`StringExpr::Const`] this will use [`concat`] to merge them.
pub fn appended_by(mut self, other: StringExpr) -> Self {
if let Self::Const(tokens) = self {
if let Self::Const(more) = other {
return Self::Const(quote! {
::core::concat!(#tokens, #more)
});
}
self = Self::Const(tokens);
}
let owned = self.into_owned();
let borrowed = other.into_borrowed();
Self::Owned(quote! {
::core::ops::Add::<&str>::add(#owned, #borrowed)
})
}
}
impl Default for StringExpr {
fn default() -> Self {
StringExpr::from_str("")
}
}
impl FromIterator<StringExpr> for StringExpr {
fn from_iter<T: IntoIterator<Item = StringExpr>>(iter: T) -> Self {
let mut iter = iter.into_iter();
match iter.next() {
Some(mut expr) => {
for next in iter {
expr = expr.appended_by(next);
}
expr
}
None => 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_reflect/derive/src/type_path.rs | crates/bevy_reflect/derive/src/type_path.rs | use proc_macro2::Ident;
use syn::{
parenthesized,
parse::{Parse, ParseStream},
token::Paren,
Generics, Path, PathSegment, Token,
};
pub(crate) fn parse_path_no_leading_colon(input: ParseStream) -> syn::Result<Path> {
if input.peek(Token![::]) {
return Err(input.error("did not expect a leading double colon (`::`)"));
}
let path = Path::parse_mod_style(input)?;
if path.segments.is_empty() {
Err(input.error("expected a path"))
} else {
Ok(path)
}
}
/// An alias for a `TypePath`.
///
/// This is the parenthesized part of `(in my_crate::foo as MyType) SomeType`.
pub(crate) struct CustomPathDef {
path: Path,
name: Option<Ident>,
}
impl CustomPathDef {
pub fn into_path(mut self, default_name: &Ident) -> Path {
let name = PathSegment::from(self.name.unwrap_or_else(|| default_name.clone()));
self.path.segments.push(name);
self.path
}
pub fn parse_parenthesized(input: ParseStream) -> syn::Result<Option<Self>> {
if input.peek(Paren) {
let path;
parenthesized!(path in input);
Ok(Some(path.call(Self::parse)?))
} else {
Ok(None)
}
}
fn parse(input: ParseStream) -> syn::Result<Self> {
input.parse::<Token![in]>()?;
let custom_path = parse_path_no_leading_colon(input)?;
if !input.peek(Token![as]) {
return Ok(Self {
path: custom_path,
name: None,
});
}
input.parse::<Token![as]>()?;
let custom_name: Ident = input.parse()?;
Ok(Self {
path: custom_path,
name: Some(custom_name),
})
}
}
pub(crate) enum NamedTypePathDef {
External {
path: Path,
generics: Generics,
custom_path: Option<CustomPathDef>,
},
Primitive(Ident),
}
impl Parse for NamedTypePathDef {
fn parse(input: ParseStream) -> syn::Result<Self> {
let custom_path = CustomPathDef::parse_parenthesized(input)?;
let path = Path::parse_mod_style(input)?;
let mut generics = input.parse::<Generics>()?;
generics.where_clause = input.parse()?;
if path.leading_colon.is_none() && custom_path.is_none() {
if path.segments.len() == 1 {
let ident = path.segments.into_iter().next().unwrap().ident;
Ok(NamedTypePathDef::Primitive(ident))
} else {
Err(input.error("non-customized paths must start with a double colon (`::`)"))
}
} else {
Ok(NamedTypePathDef::External {
path,
generics,
custom_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/derive/src/reflect_opaque.rs | crates/bevy_reflect/derive/src/reflect_opaque.rs | use crate::{
container_attributes::ContainerAttributes, derive_data::ReflectTraitToImpl,
type_path::CustomPathDef,
};
use syn::{parenthesized, parse::ParseStream, token::Paren, Attribute, Generics, Path};
/// A struct used to define a simple reflection-opaque types (including primitives).
///
/// This takes the form:
///
/// ```ignore (Method expecting TokenStream is better represented with raw tokens)
/// // Standard
/// ::my_crate::foo::Bar(TraitA, TraitB)
///
/// // With generics
/// ::my_crate::foo::Bar<T1: Bar, T2>(TraitA, TraitB)
///
/// // With generics and where clause
/// ::my_crate::foo::Bar<T1, T2> where T1: Bar (TraitA, TraitB)
///
/// // With a custom path (not with impl_from_reflect_opaque)
/// (in my_crate::bar) Bar(TraitA, TraitB)
/// ```
pub(crate) struct ReflectOpaqueDef {
#[cfg_attr(
not(feature = "reflect_documentation"),
expect(
dead_code,
reason = "The is used when the `documentation` feature is enabled.",
)
)]
pub attrs: Vec<Attribute>,
pub type_path: Path,
pub generics: Generics,
pub traits: Option<ContainerAttributes>,
pub custom_path: Option<CustomPathDef>,
}
impl ReflectOpaqueDef {
pub fn parse_reflect(input: ParseStream) -> syn::Result<Self> {
Self::parse(input, ReflectTraitToImpl::Reflect)
}
pub fn parse_from_reflect(input: ParseStream) -> syn::Result<Self> {
Self::parse(input, ReflectTraitToImpl::FromReflect)
}
fn parse(input: ParseStream, trait_: ReflectTraitToImpl) -> syn::Result<Self> {
let attrs = input.call(Attribute::parse_outer)?;
let custom_path = CustomPathDef::parse_parenthesized(input)?;
let type_path = Path::parse_mod_style(input)?;
let mut generics = input.parse::<Generics>()?;
generics.where_clause = input.parse()?;
let mut traits = None;
if input.peek(Paren) {
let content;
parenthesized!(content in input);
traits = Some({
let mut attrs = ContainerAttributes::default();
attrs.parse_terminated(&content, trait_)?;
attrs
});
}
Ok(Self {
attrs,
type_path,
generics,
traits,
custom_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/derive/src/lib.rs | crates/bevy_reflect/derive/src/lib.rs | #![cfg_attr(docsrs, feature(doc_cfg))]
//! This crate contains macros used by Bevy's `Reflect` API.
//!
//! The main export of this crate is the derive macro for [`Reflect`]. This allows
//! types to easily implement `Reflect` along with other `bevy_reflect` traits,
//! such as `Struct`, `GetTypeRegistration`, and more— all with a single derive!
//!
//! Some other noteworthy exports include the derive macros for [`FromReflect`] and
//! [`TypePath`], as well as the [`reflect_trait`] attribute macro.
//!
//! [`Reflect`]: crate::derive_reflect
//! [`FromReflect`]: crate::derive_from_reflect
//! [`TypePath`]: crate::derive_type_path
//! [`reflect_trait`]: macro@reflect_trait
extern crate proc_macro;
mod container_attributes;
mod custom_attributes;
mod derive_data;
#[cfg(feature = "reflect_documentation")]
mod documentation;
mod enum_utility;
mod field_attributes;
mod from_reflect;
mod generics;
mod ident;
mod impls;
mod meta;
mod reflect_opaque;
mod registration;
mod remote;
mod serialization;
mod string_expr;
mod struct_utility;
mod trait_reflection;
mod type_path;
mod where_clause_options;
use std::{fs, io::Read, path::PathBuf};
use crate::derive_data::{ReflectDerive, ReflectMeta, ReflectStruct};
use container_attributes::ContainerAttributes;
use derive_data::{ReflectImplSource, ReflectProvenance, ReflectTraitToImpl, ReflectTypePath};
use proc_macro::TokenStream;
use quote::quote;
use reflect_opaque::ReflectOpaqueDef;
use syn::{parse_macro_input, DeriveInput};
use type_path::NamedTypePathDef;
pub(crate) static REFLECT_ATTRIBUTE_NAME: &str = "reflect";
pub(crate) static TYPE_PATH_ATTRIBUTE_NAME: &str = "type_path";
pub(crate) static TYPE_NAME_ATTRIBUTE_NAME: &str = "type_name";
/// Used both for [`impl_reflect`] and [`derive_reflect`].
///
/// [`impl_reflect`]: macro@impl_reflect
/// [`derive_reflect`]: derive_reflect()
fn match_reflect_impls(ast: DeriveInput, source: ReflectImplSource) -> TokenStream {
let derive_data = match ReflectDerive::from_input(
&ast,
ReflectProvenance {
source,
trait_: ReflectTraitToImpl::Reflect,
},
) {
Ok(data) => data,
Err(err) => return err.into_compile_error().into(),
};
let assertions = impls::impl_assertions(&derive_data);
let (reflect_impls, from_reflect_impl) = match derive_data {
ReflectDerive::Struct(struct_data) | ReflectDerive::UnitStruct(struct_data) => (
impls::impl_struct(&struct_data),
if struct_data.meta().from_reflect().should_auto_derive() {
Some(from_reflect::impl_struct(&struct_data))
} else {
None
},
),
ReflectDerive::TupleStruct(struct_data) => (
impls::impl_tuple_struct(&struct_data),
if struct_data.meta().from_reflect().should_auto_derive() {
Some(from_reflect::impl_tuple_struct(&struct_data))
} else {
None
},
),
ReflectDerive::Enum(enum_data) => (
impls::impl_enum(&enum_data),
if enum_data.meta().from_reflect().should_auto_derive() {
Some(from_reflect::impl_enum(&enum_data))
} else {
None
},
),
ReflectDerive::Opaque(meta) => (
impls::impl_opaque(&meta),
if meta.from_reflect().should_auto_derive() {
Some(from_reflect::impl_opaque(&meta))
} else {
None
},
),
};
TokenStream::from(quote! {
const _: () = {
#reflect_impls
#from_reflect_impl
#assertions
};
})
}
/// The main derive macro used by `bevy_reflect` for deriving its `Reflect` trait.
///
/// This macro can be used on all structs and enums (unions are not supported).
/// It will automatically generate implementations for `Reflect`, `Typed`, `GetTypeRegistration`, and `FromReflect`.
/// And, depending on the item's structure, will either implement `Struct`, `TupleStruct`, or `Enum`.
///
/// See the [`FromReflect`] derive macro for more information on how to customize the `FromReflect` implementation.
///
/// # Container Attributes
///
/// This macro comes with some helper attributes that can be added to the container item
/// in order to provide additional functionality or alter the generated implementations.
///
/// In addition to those listed, this macro can also use the attributes for [`TypePath`] derives.
///
/// ## `#[reflect(Ident)]`
///
/// The `#[reflect(Ident)]` attribute is used to add type data registrations to the `GetTypeRegistration`
/// implementation corresponding to the given identifier, prepended by `Reflect`.
///
/// For example, `#[reflect(Foo, Bar)]` would add two registrations:
/// one for `ReflectFoo` and another for `ReflectBar`.
/// This assumes these types are indeed in-scope wherever this macro is called.
///
/// This is often used with traits that have been marked by the [`#[reflect_trait]`](macro@reflect_trait)
/// macro in order to register the type's implementation of that trait.
///
/// ### Default Registrations
///
/// The following types are automatically registered when deriving `Reflect`:
///
/// * `ReflectFromReflect` (unless opting out of `FromReflect`)
/// * `SerializationData`
/// * `ReflectFromPtr`
///
/// ### Special Identifiers
///
/// There are a few "special" identifiers that work a bit differently:
///
/// * `#[reflect(Clone)]` will force the implementation of `Reflect::reflect_clone` to rely on
/// the type's [`Clone`] implementation.
/// A custom implementation may be provided using `#[reflect(Clone(my_clone_func))]` where
/// `my_clone_func` is the path to a function matching the signature:
/// `(&Self) -> Self`.
/// * `#[reflect(Debug)]` will force the implementation of `Reflect::reflect_debug` to rely on
/// the type's [`Debug`] implementation.
/// A custom implementation may be provided using `#[reflect(Debug(my_debug_func))]` where
/// `my_debug_func` is the path to a function matching the signature:
/// `(&Self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result`.
/// * `#[reflect(PartialEq)]` will force the implementation of `Reflect::reflect_partial_eq` to rely on
/// the type's [`PartialEq`] implementation.
/// A custom implementation may be provided using `#[reflect(PartialEq(my_partial_eq_func))]` where
/// `my_partial_eq_func` is the path to a function matching the signature:
/// `(&Self, value: &dyn #bevy_reflect_path::Reflect) -> bool`.
/// * `#[reflect(Hash)]` will force the implementation of `Reflect::reflect_hash` to rely on
/// the type's [`Hash`] implementation.
/// A custom implementation may be provided using `#[reflect(Hash(my_hash_func))]` where
/// `my_hash_func` is the path to a function matching the signature: `(&Self) -> u64`.
/// * `#[reflect(Default)]` will register the `ReflectDefault` type data as normal.
/// However, it will also affect how certain other operations are performed in order
/// to improve performance and/or robustness.
/// An example of where this is used is in the [`FromReflect`] derive macro,
/// where adding this attribute will cause the `FromReflect` implementation to create
/// a base value using its [`Default`] implementation avoiding issues with ignored fields
/// (for structs and tuple structs only).
///
/// ## `#[reflect(opaque)]`
///
/// The `#[reflect(opaque)]` attribute denotes that the item should implement `Reflect` as an opaque type,
/// hiding its structure and fields from the reflection API.
/// This means that it will forgo implementing `Struct`, `TupleStruct`, or `Enum`.
///
/// Furthermore, it requires that the type implements [`Clone`].
/// If planning to serialize this type using the reflection serializers,
/// then the `Serialize` and `Deserialize` traits will need to be implemented and registered as well.
///
/// ## `#[reflect(from_reflect = false)]`
///
/// This attribute will opt-out of the default `FromReflect` implementation.
///
/// This is useful for when a type can't or shouldn't implement `FromReflect`,
/// or if a manual implementation is desired.
///
/// Note that in the latter case, `ReflectFromReflect` will no longer be automatically registered.
///
/// ## `#[reflect(type_path = false)]`
///
/// This attribute will opt-out of the default `TypePath` implementation.
///
/// This is useful for when a type can't or shouldn't implement `TypePath`,
/// or if a manual implementation is desired.
///
/// ## `#[reflect(no_field_bounds)]`
///
/// This attribute will opt-out of the default trait bounds added to all field types
/// for the generated reflection trait impls.
///
/// Normally, all fields will have the bounds `TypePath`, and either `FromReflect` or `Reflect`
/// depending on if `#[reflect(from_reflect = false)]` is used.
/// However, this might not always be desirable, and so this attribute may be used to remove those bounds.
///
/// ### Example
///
/// If a type is recursive the default bounds will cause an overflow error when building:
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// #[derive(Reflect)] // ERROR: overflow evaluating the requirement `Foo: FromReflect`
/// struct Foo {
/// foo: Vec<Foo>,
/// }
///
/// // Generates a where clause like:
/// // impl bevy_reflect::Reflect for Foo
/// // where
/// // Foo: Any + Send + Sync,
/// // Vec<Foo>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
/// ```
///
/// In this case, `Foo` is given the bounds `Vec<Foo>: FromReflect + ...`,
/// which requires that `Foo` implements `FromReflect`,
/// which requires that `Vec<Foo>` implements `FromReflect`,
/// and so on, resulting in the error.
///
/// To fix this, we can add `#[reflect(no_field_bounds)]` to `Foo` to remove the bounds on `Vec<Foo>`:
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// #[derive(Reflect)]
/// #[reflect(no_field_bounds)]
/// struct Foo {
/// foo: Vec<Foo>,
/// }
///
/// // Generates a where clause like:
/// // impl bevy_reflect::Reflect for Foo
/// // where
/// // Self: Any + Send + Sync,
/// ```
///
/// ## `#[reflect(where T: Trait, U::Assoc: Trait, ...)]`
///
/// This attribute can be used to add additional bounds to the generated reflection trait impls.
///
/// This is useful for when a type needs certain bounds only applied to the reflection impls
/// that are not otherwise automatically added by the derive macro.
///
/// ### Example
///
/// In the example below, we want to enforce that `T::Assoc: List` is required in order for
/// `Foo<T>` to be reflectable, but we don't want it to prevent `Foo<T>` from being used
/// in places where `T::Assoc: List` is not required.
///
/// ```ignore
/// trait Trait {
/// type Assoc;
/// }
///
/// #[derive(Reflect)]
/// #[reflect(where T::Assoc: List)]
/// struct Foo<T: Trait> where T::Assoc: Default {
/// value: T::Assoc,
/// }
///
/// // Generates a where clause like:
/// //
/// // impl<T: Trait> bevy_reflect::Reflect for Foo<T>
/// // where
/// // Foo<T>: Any + Send + Sync,
/// // T::Assoc: Default,
/// // T: TypePath,
/// // T::Assoc: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
/// // T::Assoc: List,
/// // {/* ... */}
/// ```
///
/// ## `#[reflect(@...)]`
///
/// This attribute can be used to register custom attributes to the type's `TypeInfo`.
///
/// It accepts any expression after the `@` symbol that resolves to a value which implements `Reflect`.
///
/// Any number of custom attributes may be registered, however, each the type of each attribute must be unique.
/// If two attributes of the same type are registered, the last one will overwrite the first.
///
/// ### Example
///
/// ```ignore
/// #[derive(Reflect)]
/// struct Required;
///
/// #[derive(Reflect)]
/// struct EditorTooltip(String);
///
/// impl EditorTooltip {
/// fn new(text: &str) -> Self {
/// Self(text.to_string())
/// }
/// }
///
/// #[derive(Reflect)]
/// // Specify a "required" status and tooltip:
/// #[reflect(@Required, @EditorTooltip::new("An ID is required!"))]
/// struct Id(u8);
/// ```
/// ## `#[reflect(no_auto_register)]`
///
/// This attribute will opt-out of the automatic reflect type registration.
///
/// All non-generic types annotated with `#[derive(Reflect)]` are usually automatically registered on app startup.
/// If this behavior is not desired, this attribute may be used to disable it for the annotated type.
///
/// # Field Attributes
///
/// Along with the container attributes, this macro comes with some attributes that may be applied
/// to the contained fields themselves.
///
/// ## `#[reflect(ignore)]`
///
/// This attribute simply marks a field to be ignored by the reflection API.
///
/// This allows fields to completely opt-out of reflection,
/// which may be useful for maintaining invariants, keeping certain data private,
/// or allowing the use of types that do not implement `Reflect` within the container.
///
/// ## `#[reflect(skip_serializing)]`
///
/// This works similar to `#[reflect(ignore)]`, but rather than opting out of _all_ of reflection,
/// it simply opts the field out of both serialization and deserialization.
/// This can be useful when a field should be accessible via reflection, but may not make
/// sense in a serialized form, such as computed data.
///
/// What this does is register the `SerializationData` type within the `GetTypeRegistration` implementation,
/// which will be used by the reflection serializers to determine whether or not the field is serializable.
///
/// ## `#[reflect(clone)]`
///
/// This attribute affects the `Reflect::reflect_clone` implementation.
///
/// Without this attribute, the implementation will rely on the field's own `Reflect::reflect_clone` implementation.
/// When this attribute is present, the implementation will instead use the field's `Clone` implementation directly.
///
/// The attribute may also take the path to a custom function like `#[reflect(clone = "path::to::my_clone_func")]`,
/// where `my_clone_func` matches the signature `(&Self) -> Self`.
///
/// This attribute does nothing if the containing struct/enum has the `#[reflect(Clone)]` attribute.
///
/// ## `#[reflect(@...)]`
///
/// This attribute can be used to register custom attributes to the field's `TypeInfo`.
///
/// It accepts any expression after the `@` symbol that resolves to a value which implements `Reflect`.
///
/// Any number of custom attributes may be registered, however, each the type of each attribute must be unique.
/// If two attributes of the same type are registered, the last one will overwrite the first.
///
/// ### Example
///
/// ```ignore
/// #[derive(Reflect)]
/// struct EditorTooltip(String);
///
/// impl EditorTooltip {
/// fn new(text: &str) -> Self {
/// Self(text.to_string())
/// }
/// }
///
/// #[derive(Reflect)]
/// struct Slider {
/// // Specify a custom range and tooltip:
/// #[reflect(@0.0..=1.0, @EditorTooltip::new("Must be between 0 and 1"))]
/// value: f32,
/// }
/// ```
///
/// [`reflect_trait`]: macro@reflect_trait
#[proc_macro_derive(Reflect, attributes(reflect, type_path, type_name))]
pub fn derive_reflect(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
match_reflect_impls(ast, ReflectImplSource::DeriveLocalType)
}
/// Derives the `FromReflect` trait.
///
/// # Field Attributes
///
/// ## `#[reflect(ignore)]`
///
/// The `#[reflect(ignore)]` attribute is shared with the [`#[derive(Reflect)]`](Reflect) macro and has much of the same
/// functionality in that it denotes that a field will be ignored by the reflection API.
///
/// The only major difference is that using it with this derive requires that the field implements [`Default`].
/// Without this requirement, there would be no way for `FromReflect` to automatically construct missing fields
/// that have been ignored.
///
/// ## `#[reflect(default)]`
///
/// If a field cannot be read, this attribute specifies a default value to be used in its place.
///
/// By default, this attribute denotes that the field's type implements [`Default`].
/// However, it can also take in a path string to a user-defined function that will return the default value.
/// This takes the form: `#[reflect(default = "path::to::my_function")]` where `my_function` is a parameterless
/// function that must return some default value for the type.
///
/// Specifying a custom default can be used to give different fields their own specialized defaults,
/// or to remove the `Default` requirement on fields marked with `#[reflect(ignore)]`.
/// Additionally, either form of this attribute can be used to fill in fields that are simply missing,
/// such as when converting a partially-constructed dynamic type to a concrete one.
#[proc_macro_derive(FromReflect, attributes(reflect))]
pub fn derive_from_reflect(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let derive_data = match ReflectDerive::from_input(
&ast,
ReflectProvenance {
source: ReflectImplSource::DeriveLocalType,
trait_: ReflectTraitToImpl::FromReflect,
},
) {
Ok(data) => data,
Err(err) => return err.into_compile_error().into(),
};
let from_reflect_impl = match derive_data {
ReflectDerive::Struct(struct_data) | ReflectDerive::UnitStruct(struct_data) => {
from_reflect::impl_struct(&struct_data)
}
ReflectDerive::TupleStruct(struct_data) => from_reflect::impl_tuple_struct(&struct_data),
ReflectDerive::Enum(meta) => from_reflect::impl_enum(&meta),
ReflectDerive::Opaque(meta) => from_reflect::impl_opaque(&meta),
};
TokenStream::from(quote! {
const _: () = {
#from_reflect_impl
};
})
}
/// Derives the `TypePath` trait, providing a stable alternative to [`std::any::type_name`].
///
/// # Container Attributes
///
/// ## `#[type_path = "my_crate::foo"]`
///
/// Optionally specifies a custom module path to use instead of [`module_path`].
///
/// This path does not include the final identifier.
///
/// ## `#[type_name = "RenamedType"]`
///
/// Optionally specifies a new terminating identifier for `TypePath`.
///
/// To use this attribute, `#[type_path = "..."]` must also be specified.
#[proc_macro_derive(TypePath, attributes(type_path, type_name))]
pub fn derive_type_path(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let derive_data = match ReflectDerive::from_input(
&ast,
ReflectProvenance {
source: ReflectImplSource::DeriveLocalType,
trait_: ReflectTraitToImpl::TypePath,
},
) {
Ok(data) => data,
Err(err) => return err.into_compile_error().into(),
};
let type_path_impl = impls::impl_type_path(derive_data.meta());
TokenStream::from(quote! {
const _: () = {
#type_path_impl
};
})
}
/// A macro that automatically generates type data for traits, which their implementors can then register.
///
/// The output of this macro is a struct that takes reflected instances of the implementor's type
/// and returns the value as a trait object.
/// Because of this, **it can only be used on [object-safe] traits.**
///
/// For a trait named `MyTrait`, this will generate the struct `ReflectMyTrait`.
/// The generated struct can be created using `FromType` with any type that implements the trait.
/// The creation and registration of this generated struct as type data can be automatically handled
/// by [`#[derive(Reflect)]`](Reflect).
///
/// # Example
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// # use std::any::TypeId;
/// # use bevy_reflect_derive::{Reflect, reflect_trait};
/// #[reflect_trait] // Generates `ReflectMyTrait`
/// trait MyTrait {
/// fn print(&self) -> &str;
/// }
///
/// #[derive(Reflect)]
/// #[reflect(MyTrait)] // Automatically registers `ReflectMyTrait`
/// struct SomeStruct;
///
/// impl MyTrait for SomeStruct {
/// fn print(&self) -> &str {
/// "Hello, World!"
/// }
/// }
///
/// // We can create the type data manually if we wanted:
/// let my_trait: ReflectMyTrait = FromType::<SomeStruct>::from_type();
///
/// // Or we can simply get it from the registry:
/// let mut registry = TypeRegistry::default();
/// registry.register::<SomeStruct>();
/// let my_trait = registry
/// .get_type_data::<ReflectMyTrait>(TypeId::of::<SomeStruct>())
/// .unwrap();
///
/// // Then use it on reflected data
/// let reflected: Box<dyn Reflect> = Box::new(SomeStruct);
/// let reflected_my_trait: &dyn MyTrait = my_trait.get(&*reflected).unwrap();
/// assert_eq!("Hello, World!", reflected_my_trait.print());
/// ```
///
/// [object-safe]: https://doc.rust-lang.org/reference/items/traits.html#object-safety
#[proc_macro_attribute]
pub fn reflect_trait(args: TokenStream, input: TokenStream) -> TokenStream {
trait_reflection::reflect_trait(&args, input)
}
/// Generates a wrapper type that can be used to "derive `Reflect`" for remote types.
///
/// This works by wrapping the remote type in a generated wrapper that has the `#[repr(transparent)]` attribute.
/// This allows the two types to be safely [transmuted] back-and-forth.
///
/// # Defining the Wrapper
///
/// Before defining the wrapper type, please note that it is _required_ that all fields of the remote type are public.
/// The generated code will, at times, need to access or mutate them,
/// and we do not currently have a way to assign getters/setters to each field
/// (but this may change in the future).
///
/// The wrapper definition should match the remote type 1-to-1.
/// This includes the naming and ordering of the fields and variants.
///
/// Generics and lifetimes do _not_ need to have the same names, however, they _do_ need to follow the same order.
/// Additionally, whether generics are inlined or placed in a where clause should not matter.
///
/// Lastly, all macros and doc-comments should be placed __below__ this attribute.
/// If they are placed above, they will not be properly passed to the generated wrapper type.
///
/// # Example
///
/// Given a remote type, `RemoteType`:
///
/// ```
/// #[derive(Default)]
/// struct RemoteType<T>
/// where
/// T: Default + Clone,
/// {
/// pub foo: T,
/// pub bar: usize
/// }
/// ```
///
/// We would define our wrapper type as such:
///
/// ```ignore
/// use external_crate::RemoteType;
///
/// #[reflect_remote(RemoteType<T>)]
/// #[derive(Default)]
/// pub struct WrapperType<T: Default + Clone> {
/// pub foo: T,
/// pub bar: usize
/// }
/// ```
///
/// Apart from all the reflection trait implementations, this generates something like the following:
///
/// ```ignore
/// use external_crate::RemoteType;
///
/// #[derive(Default)]
/// #[repr(transparent)]
/// pub struct Wrapper<T: Default + Clone>(RemoteType<T>);
/// ```
///
/// # Usage as a Field
///
/// You can tell `Reflect` to use a remote type's wrapper internally on fields of a struct or enum.
/// This allows the real type to be used as usual while `Reflect` handles everything internally.
/// To do this, add the `#[reflect(remote = path::to::MyType)]` attribute to your field:
///
/// ```ignore
/// #[derive(Reflect)]
/// struct SomeStruct {
/// #[reflect(remote = RemoteTypeWrapper)]
/// data: RemoteType
/// }
/// ```
///
/// ## Safety
///
/// When using the `#[reflect(remote = path::to::MyType)]` field attribute, be sure you are defining the correct wrapper type.
/// Internally, this field will be unsafely [transmuted], and is only sound if using a wrapper generated for the remote type.
/// This also means keeping your wrapper definitions up-to-date with the remote types.
///
/// [transmuted]: std::mem::transmute
#[proc_macro_attribute]
pub fn reflect_remote(args: TokenStream, input: TokenStream) -> TokenStream {
remote::reflect_remote(args, input)
}
/// A macro used to generate reflection trait implementations for the given type.
///
/// This is functionally the same as [deriving `Reflect`] using the `#[reflect(opaque)]` container attribute.
///
/// The only reason for this macro's existence is so that `bevy_reflect` can easily implement the reflection traits
/// on primitives and other opaque types internally.
///
/// Since this macro also implements `TypePath`, the type path must be explicit.
/// See [`impl_type_path!`] for the exact syntax.
///
/// # Examples
///
/// Types can be passed with or without registering type data:
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// impl_reflect_opaque!(my_crate::Foo);
/// impl_reflect_opaque!(my_crate::Bar(Debug, Default, Serialize, Deserialize));
/// ```
///
/// Generic types can also specify their parameters and bounds:
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// impl_reflect_opaque!(my_crate::Foo<T1, T2: Baz> where T1: Bar (Default, Serialize, Deserialize));
/// ```
///
/// Custom type paths can be specified:
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// impl_reflect_opaque!((in not_my_crate as NotFoo) Foo(Debug, Default));
/// ```
///
/// [deriving `Reflect`]: Reflect
#[proc_macro]
pub fn impl_reflect_opaque(input: TokenStream) -> TokenStream {
let def = parse_macro_input!(input with ReflectOpaqueDef::parse_reflect);
let default_name = &def.type_path.segments.last().unwrap().ident;
let type_path = if def.type_path.leading_colon.is_none() && def.custom_path.is_none() {
ReflectTypePath::Primitive(default_name)
} else {
ReflectTypePath::External {
path: &def.type_path,
custom_path: def.custom_path.map(|path| path.into_path(default_name)),
generics: &def.generics,
}
};
let meta = ReflectMeta::new(type_path, def.traits.unwrap_or_default());
#[cfg(feature = "reflect_documentation")]
let meta = meta.with_docs(documentation::Documentation::from_attributes(&def.attrs));
let reflect_impls = impls::impl_opaque(&meta);
let from_reflect_impl = from_reflect::impl_opaque(&meta);
TokenStream::from(quote! {
const _: () = {
#reflect_impls
#from_reflect_impl
};
})
}
/// A replacement for `#[derive(Reflect)]` to be used with foreign types which
/// the definitions of cannot be altered.
///
/// This macro is an alternative to [`impl_reflect_opaque!`] and [`impl_from_reflect_opaque!`]
/// which implement foreign types as Opaque types. Note that there is no `impl_from_reflect`,
/// as this macro will do the job of both. This macro implements them using one of the reflect
/// variant traits (`bevy_reflect::{Struct, TupleStruct, Enum}`, etc.),
/// which have greater functionality. The type being reflected must be in scope, as you cannot
/// qualify it in the macro as e.g. `bevy::prelude::Vec3`.
///
/// It is necessary to add a `#[type_path = "my_crate::foo"]` attribute to all types.
///
/// It may be necessary to add `#[reflect(Default)]` for some types, specifically non-constructible
/// foreign types. Without `Default` reflected for such types, you will usually get an arcane
/// error message and fail to compile. If the type does not implement `Default`, it may not
/// be possible to reflect without extending the macro.
///
///
/// # Example
/// Implementing `Reflect` for `bevy::prelude::Vec3` as a struct type:
/// ```ignore (bevy_reflect is not accessible from this crate)
/// use bevy::prelude::Vec3;
///
/// impl_reflect!(
/// #[reflect(PartialEq, Serialize, Deserialize, Default)]
/// #[type_path = "bevy::prelude"]
/// struct Vec3 {
/// x: f32,
/// y: f32,
/// z: f32
/// }
/// );
/// ```
#[proc_macro]
pub fn impl_reflect(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
match_reflect_impls(ast, ReflectImplSource::ImplRemoteType)
}
/// A macro used to generate a `FromReflect` trait implementation for the given type.
///
/// This is functionally the same as [deriving `FromReflect`] on a type that [derives `Reflect`] using
/// the `#[reflect(opaque)]` container attribute.
///
/// The only reason this macro exists is so that `bevy_reflect` can easily implement `FromReflect` on
/// primitives and other opaque types internally.
///
/// Please note that this macro will not work with any type that [derives `Reflect`] normally
/// or makes use of the [`impl_reflect_opaque!`] macro, as those macros also implement `FromReflect`
/// by default.
///
/// # Examples
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// impl_from_reflect_opaque!(foo<T1, T2: Baz> where T1: Bar);
/// ```
///
/// [deriving `FromReflect`]: FromReflect
/// [derives `Reflect`]: Reflect
#[proc_macro]
pub fn impl_from_reflect_opaque(input: TokenStream) -> TokenStream {
let def = parse_macro_input!(input with ReflectOpaqueDef::parse_from_reflect);
let default_name = &def.type_path.segments.last().unwrap().ident;
let type_path = if def.type_path.leading_colon.is_none()
&& def.custom_path.is_none()
&& def.generics.params.is_empty()
{
ReflectTypePath::Primitive(default_name)
} else {
ReflectTypePath::External {
path: &def.type_path,
custom_path: def.custom_path.map(|alias| alias.into_path(default_name)),
generics: &def.generics,
}
};
let from_reflect_impl =
from_reflect::impl_opaque(&ReflectMeta::new(type_path, def.traits.unwrap_or_default()));
TokenStream::from(quote! {
const _: () = {
#from_reflect_impl
};
})
}
/// A replacement for [deriving `TypePath`] for use on foreign types.
///
/// Since (unlike the derive) this macro may be invoked in a different module to where the type is defined,
/// it requires an 'absolute' path definition.
///
/// Specifically, a leading `::` denoting a global path must be specified
/// or a preceding `(in my_crate::foo)` to specify the custom path must be used.
///
/// # Examples
///
/// Implementing `TypePath` on a foreign type:
/// ```ignore (bevy_reflect is not accessible from this crate)
/// impl_type_path!(::foreign_crate::foo::bar::Baz);
/// ```
///
/// On a generic type (this can also accept trait bounds):
/// ```ignore (bevy_reflect is not accessible from this crate)
/// impl_type_path!(::foreign_crate::Foo<T>);
/// impl_type_path!(::foreign_crate::Goo<T: ?Sized>);
/// ```
///
/// On a primitive (note this will not compile for a non-primitive type):
/// ```ignore (bevy_reflect is not accessible from this crate)
/// impl_type_path!(bool);
/// ```
///
/// With a custom type path:
/// ```ignore (bevy_reflect is not accessible from this crate)
/// impl_type_path!((in other_crate::foo::bar) Baz);
/// ```
///
/// With a custom type path and a custom type name:
/// ```ignore (bevy_reflect is not accessible from this crate)
/// impl_type_path!((in other_crate::foo as Baz) Bar);
/// ```
///
/// [deriving `TypePath`]: TypePath
#[proc_macro]
pub fn impl_type_path(input: TokenStream) -> TokenStream {
let def = parse_macro_input!(input as NamedTypePathDef);
let type_path = match def {
NamedTypePathDef::External {
ref path,
custom_path,
ref generics,
} => {
let default_name = &path.segments.last().unwrap().ident;
ReflectTypePath::External {
path,
custom_path: custom_path.map(|path| path.into_path(default_name)),
generics,
}
}
NamedTypePathDef::Primitive(ref ident) => ReflectTypePath::Primitive(ident),
};
let meta = ReflectMeta::new(type_path, ContainerAttributes::default());
let type_path_impl = impls::impl_type_path(&meta);
TokenStream::from(quote! {
const _: () = {
#type_path_impl
};
})
}
/// Collects and loads type registrations when using `auto_register_static` feature.
///
/// Correctly using this macro requires following:
/// 1. This macro must be called **last** during compilation. This can be achieved by putting your main function
/// in a separate crate or restructuring your project to be separated into `bin` and `lib`, and putting this macro in `bin`.
/// Any automatic type registrations using `#[derive(Reflect)]` within the same crate as this macro are not guaranteed to run.
/// 2. Your project must be compiled with `auto_register_static` feature **and** `BEVY_REFLECT_AUTO_REGISTER_STATIC=1` env variable.
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/serialization.rs | crates/bevy_reflect/derive/src/serialization.rs | use crate::{
derive_data::StructField,
field_attributes::{DefaultBehavior, ReflectIgnoreBehavior},
};
use bevy_macro_utils::fq_std::FQDefault;
use quote::quote;
use std::collections::HashMap;
use syn::{spanned::Spanned, Path};
type ReflectionIndex = usize;
/// Collected serialization data used to generate a `SerializationData` type.
pub(crate) struct SerializationDataDef {
/// Maps a field's _reflection_ index to its [`SkippedFieldDef`] if marked as `#[reflect(skip_serializing)]`.
skipped: HashMap<ReflectionIndex, SkippedFieldDef>,
}
impl SerializationDataDef {
/// Attempts to create a new `SerializationDataDef` from the given collection of fields.
///
/// Returns `Ok(Some(data))` if there are any fields needing to be skipped during serialization.
/// Otherwise, returns `Ok(None)`.
pub fn new(
fields: &[StructField<'_>],
bevy_reflect_path: &Path,
) -> Result<Option<Self>, syn::Error> {
let mut skipped = <HashMap<_, _>>::default();
for field in fields {
match field.attrs.ignore {
ReflectIgnoreBehavior::IgnoreSerialization => {
skipped.insert(
field.reflection_index.ok_or_else(|| {
syn::Error::new(
field.data.span(),
"internal error: field is missing a reflection index",
)
})?,
SkippedFieldDef::new(field, bevy_reflect_path)?,
);
}
_ => continue,
}
}
if skipped.is_empty() {
Ok(None)
} else {
Ok(Some(Self { skipped }))
}
}
/// Returns a `TokenStream` containing an initialized `SerializationData` type.
pub fn as_serialization_data(&self, bevy_reflect_path: &Path) -> proc_macro2::TokenStream {
let fields =
self.skipped
.iter()
.map(|(reflection_index, SkippedFieldDef { default_fn })| {
quote! {(
#reflection_index,
#bevy_reflect_path::serde::SkippedField::new(#default_fn)
)}
});
quote! {
#bevy_reflect_path::serde::SerializationData::new(
::core::iter::IntoIterator::into_iter([#(#fields),*])
)
}
}
}
/// Collected field data used to generate a `SkippedField` type.
pub(crate) struct SkippedFieldDef {
/// The default function for this field.
///
/// This is of type `fn() -> Box<dyn Reflect>`.
default_fn: proc_macro2::TokenStream,
}
impl SkippedFieldDef {
pub fn new(field: &StructField<'_>, bevy_reflect_path: &Path) -> Result<Self, syn::Error> {
let ty = &field.data.ty;
let default_fn = match &field.attrs.default {
DefaultBehavior::Func(func) => quote! {
|| { #bevy_reflect_path::__macro_exports::alloc_utils::Box::new(#func()) }
},
_ => quote! {
|| { #bevy_reflect_path::__macro_exports::alloc_utils::Box::new(<#ty as #FQDefault>::default()) }
},
};
Ok(Self { default_fn })
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/remote.rs | crates/bevy_reflect/derive/src/remote.rs | use crate::{
derive_data::{ReflectImplSource, ReflectProvenance, ReflectTraitToImpl},
from_reflect, impls,
impls::impl_assertions,
ReflectDerive, REFLECT_ATTRIBUTE_NAME,
};
use bevy_macro_utils::as_member;
use bevy_macro_utils::fq_std::FQOption;
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use quote::{format_ident, quote, quote_spanned};
use syn::{
parse::{Parse, ParseStream},
parse_macro_input,
spanned::Spanned,
token::PathSep,
DeriveInput, ExprPath, Generics, Member, PathArguments, Type, TypePath,
};
/// Generates the remote wrapper type and implements all the necessary traits.
pub(crate) fn reflect_remote(args: TokenStream, input: TokenStream) -> TokenStream {
let remote_args = match syn::parse::<RemoteArgs>(args) {
Ok(path) => path,
Err(err) => return err.to_compile_error().into(),
};
let remote_ty = remote_args.remote_ty;
let ast = parse_macro_input!(input as DeriveInput);
let wrapper_definition = generate_remote_wrapper(&ast, &remote_ty);
let mut derive_data = match ReflectDerive::from_input(
&ast,
ReflectProvenance {
source: ReflectImplSource::RemoteReflect,
trait_: ReflectTraitToImpl::Reflect,
},
) {
Ok(data) => data,
Err(err) => return err.into_compile_error().into(),
};
derive_data.set_remote(Some(RemoteType::new(&remote_ty)));
let assertions = impl_assertions(&derive_data);
let definition_assertions = generate_remote_definition_assertions(&derive_data);
let reflect_remote_impl = impl_reflect_remote(&derive_data, &remote_ty);
let (reflect_impls, from_reflect_impl) = match derive_data {
ReflectDerive::Struct(struct_data) | ReflectDerive::UnitStruct(struct_data) => (
impls::impl_struct(&struct_data),
if struct_data.meta().from_reflect().should_auto_derive() {
Some(from_reflect::impl_struct(&struct_data))
} else {
None
},
),
ReflectDerive::TupleStruct(struct_data) => (
impls::impl_tuple_struct(&struct_data),
if struct_data.meta().from_reflect().should_auto_derive() {
Some(from_reflect::impl_tuple_struct(&struct_data))
} else {
None
},
),
ReflectDerive::Enum(enum_data) => (
impls::impl_enum(&enum_data),
if enum_data.meta().from_reflect().should_auto_derive() {
Some(from_reflect::impl_enum(&enum_data))
} else {
None
},
),
ReflectDerive::Opaque(meta) => (
impls::impl_opaque(&meta),
if meta.from_reflect().should_auto_derive() {
Some(from_reflect::impl_opaque(&meta))
} else {
None
},
),
};
TokenStream::from(quote! {
#wrapper_definition
const _: () = {
#reflect_remote_impl
#reflect_impls
#from_reflect_impl
#definition_assertions
#assertions
};
})
}
/// Generates the remote wrapper type.
///
/// # Example
///
/// If the supplied remote type is `Bar<T>`, then the wrapper type— named `Foo<T>`— would look like:
///
/// ```
/// # struct Bar<T>(T);
///
/// #[repr(transparent)]
/// struct Foo<T>(Bar<T>);
/// ```
fn generate_remote_wrapper(input: &DeriveInput, remote_ty: &TypePath) -> proc_macro2::TokenStream {
let ident = &input.ident;
let vis = &input.vis;
let ty_generics = &input.generics;
let where_clause = &input.generics.where_clause;
let attrs = input
.attrs
.iter()
.filter(|attr| !attr.path().is_ident(REFLECT_ATTRIBUTE_NAME));
quote! {
#(#attrs)*
#[repr(transparent)]
#[doc(hidden)]
#vis struct #ident #ty_generics (pub #remote_ty) #where_clause;
}
}
/// Generates the implementation of the `ReflectRemote` trait for the given derive data and remote type.
///
/// # Note to Developers
///
/// The `ReflectRemote` trait could likely be made with default method implementations.
/// However, this makes it really easy for a user to accidentally implement this trait in an unsafe way.
/// To prevent this, we instead generate the implementation through a macro using this function.
fn impl_reflect_remote(input: &ReflectDerive, remote_ty: &TypePath) -> proc_macro2::TokenStream {
let bevy_reflect_path = input.meta().bevy_reflect_path();
let type_path = input.meta().type_path();
let (impl_generics, ty_generics, where_clause) =
input.meta().type_path().generics().split_for_impl();
let where_reflect_clause = input
.where_clause_options()
.extend_where_clause(where_clause);
quote! {
// SAFE: The generated wrapper type is guaranteed to be valid and repr(transparent) over the remote type.
impl #impl_generics #bevy_reflect_path::ReflectRemote for #type_path #ty_generics #where_reflect_clause {
type Remote = #remote_ty;
fn as_remote(&self) -> &Self::Remote {
&self.0
}
fn as_remote_mut(&mut self) -> &mut Self::Remote {
&mut self.0
}
fn into_remote(self) -> Self::Remote
{
// SAFE: The wrapper type should be repr(transparent) over the remote type
unsafe {
// Unfortunately, we have to use `transmute_copy` to avoid a compiler error:
// ```
// error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
// |
// | core::mem::transmute::<A, B>(a)
// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
// |
// = note: source type: `A` (this type does not have a fixed size)
// = note: target type: `B` (this type does not have a fixed size)
// ```
::core::mem::transmute_copy::<Self, Self::Remote>(
// `ManuallyDrop` is used to prevent double-dropping `self`
&::core::mem::ManuallyDrop::new(self)
)
}
}
fn as_wrapper(remote: &Self::Remote) -> &Self {
// SAFE: The wrapper type should be repr(transparent) over the remote type
unsafe { ::core::mem::transmute::<&Self::Remote, &Self>(remote) }
}
fn as_wrapper_mut(remote: &mut Self::Remote) -> &mut Self {
// SAFE: The wrapper type should be repr(transparent) over the remote type
unsafe { ::core::mem::transmute::<&mut Self::Remote, &mut Self>(remote) }
}
fn into_wrapper(remote: Self::Remote) -> Self
{
// SAFE: The wrapper type should be repr(transparent) over the remote type
unsafe {
// Unfortunately, we have to use `transmute_copy` to avoid a compiler error:
// ```
// error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
// |
// | core::mem::transmute::<A, B>(a)
// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
// |
// = note: source type: `A` (this type does not have a fixed size)
// = note: target type: `B` (this type does not have a fixed size)
// ```
::core::mem::transmute_copy::<Self::Remote, Self>(
// `ManuallyDrop` is used to prevent double-dropping `self`
&::core::mem::ManuallyDrop::new(remote)
)
}
}
}
}
}
/// Generates compile-time assertions for remote fields.
///
/// This prevents types from using an invalid remote type.
/// this works by generating a struct, `RemoteFieldAssertions`, with methods that
/// will result in compile-time failure if types are mismatched.
/// The output of this function is best placed within an anonymous context to maintain hygiene.
///
/// # Example
///
/// The following would fail to compile due to an incorrect `#[reflect(remote = ...)]` value.
///
/// ```ignore
/// 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 = MyBar)] // ERROR: expected type `TheirFoo` but found struct `TheirBar`
/// foo: external_crate::TheirFoo
/// }
/// ```
pub(crate) fn generate_remote_assertions(
derive_data: &ReflectDerive,
) -> Option<proc_macro2::TokenStream> {
struct RemoteAssertionData<'a> {
ident: Member,
variant: Option<&'a Ident>,
ty: &'a Type,
generics: &'a Generics,
remote_ty: &'a Type,
}
let bevy_reflect_path = derive_data.meta().bevy_reflect_path();
let fields: Box<dyn Iterator<Item = RemoteAssertionData>> = match derive_data {
ReflectDerive::Struct(data)
| ReflectDerive::TupleStruct(data)
| ReflectDerive::UnitStruct(data) => Box::new(data.active_fields().filter_map(|field| {
field
.attrs
.remote
.as_ref()
.map(|remote_ty| RemoteAssertionData {
ident: as_member(field.data.ident.as_ref(), field.declaration_index),
variant: None,
ty: &field.data.ty,
generics: data.meta().type_path().generics(),
remote_ty,
})
})),
ReflectDerive::Enum(data) => Box::new(data.variants().iter().flat_map(|variant| {
variant.active_fields().filter_map(|field| {
field
.attrs
.remote
.as_ref()
.map(|remote_ty| RemoteAssertionData {
ident: as_member(field.data.ident.as_ref(), field.declaration_index),
variant: Some(&variant.data.ident),
ty: &field.data.ty,
generics: data.meta().type_path().generics(),
remote_ty,
})
})
})),
_ => return None,
};
let assertions = fields
.map(move |field| {
let ident = if let Some(variant) = field.variant {
format_ident!("{}__{}", variant, field.ident)
} else {
match field.ident {
Member::Named(ident) => ident,
Member::Unnamed(index) => format_ident!("field_{}", index),
}
};
let (impl_generics, _, where_clause) = field.generics.split_for_impl();
let where_reflect_clause = derive_data
.where_clause_options()
.extend_where_clause(where_clause);
let ty = &field.ty;
let remote_ty = field.remote_ty;
let assertion_ident = format_ident!("assert__{}__is_valid_remote", ident);
let span = create_assertion_span(remote_ty.span());
quote_spanned! {span=>
#[allow(non_snake_case)]
#[allow(clippy::multiple_bound_locations)]
fn #assertion_ident #impl_generics () #where_reflect_clause {
let _: <#remote_ty as #bevy_reflect_path::ReflectRemote>::Remote = (|| -> #FQOption<#ty> {
None
})().unwrap();
}
}
})
.collect::<proc_macro2::TokenStream>();
if assertions.is_empty() {
None
} else {
Some(quote! {
struct RemoteFieldAssertions;
impl RemoteFieldAssertions {
#assertions
}
})
}
}
/// Generates compile-time assertions that ensure a remote wrapper definition matches up with the
/// remote type it's wrapping.
///
/// Note: This currently results in "backwards" error messages like:
///
/// ```ignore
/// expected: <WRAPPER_FIELD_TYPE>
/// found: <REMOTE_FIELD_TYPE>
/// ```
///
/// Ideally it would be the other way around, but there's no easy way of doing this without
/// generating a copy of the struct/enum definition and using that as the base instead of the remote type.
fn generate_remote_definition_assertions(derive_data: &ReflectDerive) -> proc_macro2::TokenStream {
let meta = derive_data.meta();
let self_ident = format_ident!("__remote__");
let self_ty = derive_data.remote_ty().unwrap().type_path();
let self_expr_path = derive_data.remote_ty().unwrap().as_expr_path().unwrap();
let (impl_generics, _, where_clause) = meta.type_path().generics().split_for_impl();
let where_reflect_clause = derive_data
.where_clause_options()
.extend_where_clause(where_clause);
let assertions = match derive_data {
ReflectDerive::Struct(data)
| ReflectDerive::TupleStruct(data)
| ReflectDerive::UnitStruct(data) => {
let mut output = proc_macro2::TokenStream::new();
for field in data.fields() {
let field_member = as_member(field.data.ident.as_ref(), field.declaration_index);
let field_ty = &field.data.ty;
let span = create_assertion_span(field_ty.span());
output.extend(quote_spanned! {span=>
#self_ident.#field_member = (|| -> #FQOption<#field_ty> {None})().unwrap();
});
}
output
}
ReflectDerive::Enum(data) => {
let variants = data.variants().iter().map(|variant| {
let ident = &variant.data.ident;
let mut output = proc_macro2::TokenStream::new();
if variant.fields().is_empty() {
return quote!(#self_expr_path::#ident => {});
}
for field in variant.fields() {
let field_member =
as_member(field.data.ident.as_ref(), field.declaration_index);
let field_ident = format_ident!("field_{}", field_member);
let field_ty = &field.data.ty;
let span = create_assertion_span(field_ty.span());
output.extend(quote_spanned! {span=>
#self_expr_path::#ident {#field_member: mut #field_ident, ..} => {
#field_ident = (|| -> #FQOption<#field_ty> {None})().unwrap();
}
});
}
output
});
quote! {
match #self_ident {
#(#variants)*
}
}
}
ReflectDerive::Opaque(_) => {
// No assertions needed since there are no fields to check
proc_macro2::TokenStream::new()
}
};
quote! {
const _: () = {
#[allow(non_snake_case)]
#[allow(unused_variables)]
#[allow(unused_assignments)]
#[allow(unreachable_patterns)]
#[allow(clippy::multiple_bound_locations)]
fn assert_wrapper_definition_matches_remote_type #impl_generics (mut #self_ident: #self_ty) #where_reflect_clause {
#assertions
}
};
}
}
/// Creates a span located around the given one, but resolves to the assertion's context.
///
/// This should allow the compiler to point back to the line and column in the user's code,
/// while still attributing the error to the macro.
fn create_assertion_span(span: Span) -> Span {
Span::call_site().located_at(span)
}
/// A reflected type's remote type.
///
/// This is a wrapper around [`TypePath`] that allows it to be paired with other remote-specific logic.
#[derive(Copy, Clone)]
pub(crate) struct RemoteType<'a> {
path: &'a TypePath,
}
impl<'a> RemoteType<'a> {
pub fn new(path: &'a TypePath) -> Self {
Self { path }
}
/// Returns the [type path](TypePath) of this remote type.
pub fn type_path(&self) -> &'a TypePath {
self.path
}
/// Attempts to convert the [type path](TypePath) of this remote type into an [expression path](ExprPath).
///
/// For example, this would convert `foo::Bar<T>` into `foo::Bar::<T>` to be used as part of an expression.
///
/// This will return an error for types that are parenthesized, such as in `Fn() -> Foo`.
pub fn as_expr_path(&self) -> Result<ExprPath, syn::Error> {
let mut expr_path = self.path.clone();
if let Some(segment) = expr_path.path.segments.last_mut() {
match &mut segment.arguments {
PathArguments::None => {}
PathArguments::AngleBracketed(arg) => {
arg.colon2_token = Some(PathSep::default());
}
PathArguments::Parenthesized(arg) => {
return Err(syn::Error::new(
arg.span(),
"cannot use parenthesized type as remote type",
))
}
}
}
Ok(ExprPath {
path: expr_path.path,
qself: expr_path.qself,
attrs: Vec::new(),
})
}
}
/// Metadata from the arguments defined in the `reflect_remote` attribute.
///
/// The syntax for the arguments is: `#[reflect_remote(REMOTE_TYPE_PATH)]`.
struct RemoteArgs {
remote_ty: TypePath,
}
impl Parse for RemoteArgs {
fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(Self {
remote_ty: input.parse()?,
})
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/generics.rs | crates/bevy_reflect/derive/src/generics.rs | use crate::derive_data::ReflectMeta;
use proc_macro2::TokenStream;
use quote::quote;
use syn::punctuated::Punctuated;
use syn::{GenericParam, Token};
/// Creates a `TokenStream` for generating an expression that creates a `Generics` instance.
///
/// Returns `None` if `Generics` cannot or should not be generated.
pub(crate) fn generate_generics(meta: &ReflectMeta) -> Option<TokenStream> {
if !meta.attrs().type_path_attrs().should_auto_derive() {
// Cannot verify that all generic parameters implement `TypePath`
return None;
}
let bevy_reflect_path = meta.bevy_reflect_path();
let generics = meta
.type_path()
.generics()
.params
.iter()
.filter_map(|param| match param {
GenericParam::Type(ty_param) => {
let ident = &ty_param.ident;
let name = ident.to_string();
let with_default = ty_param
.default
.as_ref()
.map(|default_ty| quote!(.with_default::<#default_ty>()));
Some(quote! {
#bevy_reflect_path::GenericInfo::Type(
#bevy_reflect_path::TypeParamInfo::new::<#ident>(
#bevy_reflect_path::__macro_exports::alloc_utils::Cow::Borrowed(#name),
)
#with_default
)
})
}
GenericParam::Const(const_param) => {
let ty = &const_param.ty;
let name = const_param.ident.to_string();
let with_default = const_param.default.as_ref().map(|default| {
// We add the `as #ty` to ensure that the correct type is inferred.
quote!(.with_default(#default as #ty))
});
Some(quote! {
#[allow(
clippy::unnecessary_cast,
reason = "reflection requires an explicit type hint for const generics"
)]
#bevy_reflect_path::GenericInfo::Const(
#bevy_reflect_path::ConstParamInfo::new::<#ty>(
#bevy_reflect_path::__macro_exports::alloc_utils::Cow::Borrowed(#name),
)
#with_default
)
})
}
GenericParam::Lifetime(_) => None,
})
.collect::<Punctuated<_, Token![,]>>();
if generics.is_empty() {
// No generics to generate
return None;
}
Some(quote!(#bevy_reflect_path::Generics::from_iter([ #generics ])))
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/struct_utility.rs | crates/bevy_reflect/derive/src/struct_utility.rs | use crate::ReflectStruct;
/// A helper struct for creating remote-aware field accessors.
///
/// These are "remote-aware" because when a field is a remote field, it uses a [`transmute`] internally
/// to access the field.
///
/// [`transmute`]: std::mem::transmute
pub(crate) struct FieldAccessors {
/// The referenced field accessors, such as `&self.foo`.
pub fields_ref: Vec<proc_macro2::TokenStream>,
/// The mutably referenced field accessors, such as `&mut self.foo`.
pub fields_mut: Vec<proc_macro2::TokenStream>,
/// The ordered set of field indices (basically just the range of [0, `field_count`).
pub field_indices: Vec<usize>,
/// The number of fields in the reflected struct.
pub field_count: usize,
}
impl FieldAccessors {
pub fn new(reflect_struct: &ReflectStruct) -> Self {
let (fields_ref, fields_mut): (Vec<_>, Vec<_>) = reflect_struct
.active_fields()
.map(|field| {
(
reflect_struct.access_for_field(field, false),
reflect_struct.access_for_field(field, true),
)
})
.unzip();
let field_count = fields_ref.len();
let field_indices = (0..field_count).collect();
Self {
fields_ref,
fields_mut,
field_indices,
field_count,
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/enum_utility.rs | crates/bevy_reflect/derive/src/enum_utility.rs | use crate::field_attributes::CloneBehavior;
use crate::{
derive_data::ReflectEnum, derive_data::StructField, field_attributes::DefaultBehavior,
};
use bevy_macro_utils::as_member;
use bevy_macro_utils::fq_std::{FQClone, FQDefault, FQOption, FQResult};
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote, ToTokens};
pub(crate) struct EnumVariantOutputData {
/// The names of each variant as a string.
///
/// For example, `Some` and `None` for the `Option` enum.
pub variant_names: Vec<String>,
/// The pattern matching portion of each variant.
///
/// For example, `Option::Some { 0: _0 }` and `Option::None {}` for the `Option` enum.
pub variant_patterns: Vec<TokenStream>,
/// The constructor portion of each variant.
///
/// For example, `Option::Some { 0: value }` and `Option::None {}` for the `Option` enum.
pub variant_constructors: Vec<TokenStream>,
}
#[derive(Copy, Clone)]
pub(crate) struct VariantField<'a, 'b> {
/// The alias for the field.
///
/// This should be used whenever the field needs to be referenced in a token stream.
pub alias: &'a Ident,
/// The name of the variant that contains the field.
pub variant_name: &'a str,
/// The field data.
pub field: &'a StructField<'b>,
}
/// Trait used to control how enum variants are built.
pub(crate) trait VariantBuilder: Sized {
/// Returns the enum data.
fn reflect_enum(&self) -> &ReflectEnum<'_>;
/// Returns a token stream that accesses a field of a variant as an `Option<dyn Reflect>`.
///
/// The default implementation of this method will return a token stream
/// which gets the field dynamically so as to support `dyn Enum`.
///
/// # Parameters
/// * `this`: The identifier of the enum
/// * `field`: The field to access
fn access_field(&self, this: &Ident, field: VariantField) -> TokenStream {
if let Some(field_ident) = &field.field.data.ident {
let name = field_ident.to_string();
quote!(#this.field(#name))
} else if let Some(field_index) = field.field.reflection_index {
quote!(#this.field_at(#field_index))
} else {
quote!(::core::compile_error!(
"internal bevy_reflect error: field should be active"
))
}
}
/// Returns a token stream that unwraps a field of a variant as a `&dyn Reflect`
/// (from an `Option<dyn Reflect>`).
///
/// # Parameters
/// * `field`: The field to access
fn unwrap_field(&self, field: VariantField) -> TokenStream;
/// Returns a token stream that constructs a field of a variant as a concrete type
/// (from a `&dyn Reflect`).
///
/// # Parameters
/// * `field`: The field to access
fn construct_field(&self, field: VariantField) -> TokenStream;
/// Returns a token stream that constructs an instance of an active field.
///
/// # Parameters
/// * `this`: The identifier of the enum
/// * `field`: The field to access
fn on_active_field(&self, this: &Ident, field: VariantField) -> TokenStream {
let bevy_reflect_path = self.reflect_enum().meta().bevy_reflect_path();
let field_accessor = self.access_field(this, field);
let alias = field.alias;
let field_ty = field.field.reflected_type();
let field_constructor = self.construct_field(field);
let construction = match &field.field.attrs.default {
DefaultBehavior::Func(path) => quote! {
if let #FQOption::Some(#alias) = #field_accessor {
#field_constructor
} else {
#path()
}
},
DefaultBehavior::Default => quote! {
if let #FQOption::Some(#alias) = #field_accessor {
#field_constructor
} else {
#FQDefault::default()
}
},
DefaultBehavior::Required => {
let field_unwrapper = self.unwrap_field(field);
quote! {{
// `#alias` is used by both the unwrapper and constructor
let #alias = #field_accessor;
let #alias = #field_unwrapper;
#field_constructor
}}
}
};
if field.field.attrs().remote.is_some() {
quote! {
<#field_ty as #bevy_reflect_path::ReflectRemote>::into_remote(#construction)
}
} else {
construction
}
}
/// Returns a token stream that constructs an instance of an ignored field.
///
/// # Parameters
/// * `field`: The field to access
fn on_ignored_field(&self, field: VariantField) -> TokenStream {
match &field.field.attrs.default {
DefaultBehavior::Func(path) => quote! { #path() },
_ => quote! { #FQDefault::default() },
}
}
/// Builds the enum variant output data.
fn build(&self, this: &Ident) -> EnumVariantOutputData {
let variants = self.reflect_enum().variants();
let mut variant_names = Vec::with_capacity(variants.len());
let mut variant_patterns = Vec::with_capacity(variants.len());
let mut variant_constructors = Vec::with_capacity(variants.len());
for variant in variants {
let variant_ident = &variant.data.ident;
let variant_name = variant_ident.to_string();
let variant_path = self.reflect_enum().get_unit(variant_ident);
let fields = variant.fields();
let mut field_patterns = Vec::with_capacity(fields.len());
let mut field_constructors = Vec::with_capacity(fields.len());
for field in fields {
let member = as_member(field.data.ident.as_ref(), field.declaration_index);
let alias = format_ident!("_{}", member);
let variant_field = VariantField {
alias: &alias,
variant_name: &variant_name,
field,
};
let value = if field.attrs.ignore.is_ignored() {
self.on_ignored_field(variant_field)
} else {
self.on_active_field(this, variant_field)
};
field_patterns.push(quote! {
#member: #alias
});
field_constructors.push(quote! {
#member: #value
});
}
let pattern = quote! {
#variant_path { #( #field_patterns ),* }
};
let constructor = quote! {
#variant_path {
#( #field_constructors ),*
}
};
variant_names.push(variant_name);
variant_patterns.push(pattern);
variant_constructors.push(constructor);
}
EnumVariantOutputData {
variant_names,
variant_patterns,
variant_constructors,
}
}
}
/// Generates the enum variant output data needed to build the `FromReflect::from_reflect` implementation.
pub(crate) struct FromReflectVariantBuilder<'a> {
reflect_enum: &'a ReflectEnum<'a>,
}
impl<'a> FromReflectVariantBuilder<'a> {
pub fn new(reflect_enum: &'a ReflectEnum) -> Self {
Self { reflect_enum }
}
}
impl<'a> VariantBuilder for FromReflectVariantBuilder<'a> {
fn reflect_enum(&self) -> &ReflectEnum<'_> {
self.reflect_enum
}
fn unwrap_field(&self, field: VariantField) -> TokenStream {
let alias = field.alias;
quote!(#alias?)
}
fn construct_field(&self, field: VariantField) -> TokenStream {
let bevy_reflect_path = self.reflect_enum.meta().bevy_reflect_path();
let field_ty = field.field.reflected_type();
let alias = field.alias;
quote! {
<#field_ty as #bevy_reflect_path::FromReflect>::from_reflect(#alias)?
}
}
}
/// Generates the enum variant output data needed to build the `PartialReflect::try_apply` implementation.
pub(crate) struct TryApplyVariantBuilder<'a> {
reflect_enum: &'a ReflectEnum<'a>,
}
impl<'a> TryApplyVariantBuilder<'a> {
pub fn new(reflect_enum: &'a ReflectEnum) -> Self {
Self { reflect_enum }
}
}
impl<'a> VariantBuilder for TryApplyVariantBuilder<'a> {
fn reflect_enum(&self) -> &ReflectEnum<'_> {
self.reflect_enum
}
fn unwrap_field(&self, field: VariantField) -> TokenStream {
let VariantField {
alias,
variant_name,
field,
..
} = field;
let bevy_reflect_path = self.reflect_enum.meta().bevy_reflect_path();
let field_name = match &field.data.ident {
Some(ident) => format!("{ident}"),
None => format!(".{}", field.declaration_index),
};
quote! {
#alias.ok_or(#bevy_reflect_path::ApplyError::MissingEnumField {
variant_name: ::core::convert::Into::into(#variant_name),
field_name: ::core::convert::Into::into(#field_name)
})?
}
}
fn construct_field(&self, field: VariantField) -> TokenStream {
let bevy_reflect_path = self.reflect_enum.meta().bevy_reflect_path();
let alias = field.alias;
let field_ty = field.field.reflected_type();
quote! {
<#field_ty as #bevy_reflect_path::FromReflect>::from_reflect(#alias)
.ok_or(#bevy_reflect_path::ApplyError::MismatchedTypes {
from_type: ::core::convert::Into::into(
#bevy_reflect_path::DynamicTypePath::reflect_type_path(#alias)
),
to_type: ::core::convert::Into::into(<#field_ty as #bevy_reflect_path::TypePath>::type_path())
})?
}
}
}
/// Generates the enum variant output data needed to build the `Reflect::reflect_clone` implementation.
pub(crate) struct ReflectCloneVariantBuilder<'a> {
reflect_enum: &'a ReflectEnum<'a>,
}
impl<'a> ReflectCloneVariantBuilder<'a> {
pub fn new(reflect_enum: &'a ReflectEnum) -> Self {
Self { reflect_enum }
}
}
impl<'a> VariantBuilder for ReflectCloneVariantBuilder<'a> {
fn reflect_enum(&self) -> &ReflectEnum<'_> {
self.reflect_enum
}
fn access_field(&self, _ident: &Ident, field: VariantField) -> TokenStream {
let alias = field.alias;
quote!(#FQOption::Some(#alias))
}
fn unwrap_field(&self, field: VariantField) -> TokenStream {
let alias = field.alias;
quote!(#alias.unwrap())
}
fn construct_field(&self, field: VariantField) -> TokenStream {
let bevy_reflect_path = self.reflect_enum.meta().bevy_reflect_path();
let field_ty = field.field.reflected_type();
let alias = field.alias;
let alias = match &field.field.attrs.remote {
Some(wrapper_ty) => {
quote! {
<#wrapper_ty as #bevy_reflect_path::ReflectRemote>::as_wrapper(#alias)
}
}
None => alias.to_token_stream(),
};
match &field.field.attrs.clone {
CloneBehavior::Default => {
quote! {
<#field_ty as #bevy_reflect_path::PartialReflect>::reflect_clone_and_take(#alias)?
}
}
CloneBehavior::Trait => {
quote! {
#FQClone::clone(#alias)
}
}
CloneBehavior::Func(clone_fn) => {
quote! {
#clone_fn(#alias)
}
}
}
}
fn on_active_field(&self, _this: &Ident, field: VariantField) -> TokenStream {
self.construct_field(field)
}
fn on_ignored_field(&self, field: VariantField) -> TokenStream {
let bevy_reflect_path = self.reflect_enum.meta().bevy_reflect_path();
let variant_name = field.variant_name;
let alias = field.alias;
match &field.field.attrs.clone {
CloneBehavior::Default => {
let field_id = field.field.field_id(bevy_reflect_path);
quote! {
return #FQResult::Err(
#bevy_reflect_path::ReflectCloneError::FieldNotCloneable {
field: #field_id,
variant: #FQOption::Some(#bevy_reflect_path::__macro_exports::alloc_utils::Cow::Borrowed(#variant_name)),
container_type_path: #bevy_reflect_path::__macro_exports::alloc_utils::Cow::Borrowed(<Self as #bevy_reflect_path::TypePath>::type_path())
}
)
}
}
CloneBehavior::Trait => quote! { #FQClone::clone(#alias) },
CloneBehavior::Func(clone_fn) => quote! { #clone_fn() },
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/ident.rs | crates/bevy_reflect/derive/src/ident.rs | use proc_macro2::{Ident, Span};
/// Returns the "reflected" ident for a given string.
///
/// # Example
///
/// ```
/// # use proc_macro2::Ident;
/// # // We can't import this method because of its visibility.
/// # fn get_reflect_ident(name: &str) -> Ident {
/// # let reflected = format!("Reflect{name}");
/// # Ident::new(&reflected, proc_macro2::Span::call_site())
/// # }
/// let reflected: Ident = get_reflect_ident("Hash");
/// assert_eq!("ReflectHash", reflected.to_string());
/// ```
pub(crate) fn get_reflect_ident(name: &str) -> Ident {
let reflected = format!("Reflect{name}");
Ident::new(&reflected, Span::call_site())
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/field_attributes.rs | crates/bevy_reflect/derive/src/field_attributes.rs | //! Contains code related to field attributes for reflected types.
//!
//! A field attribute is an attribute which applies to particular field or variant
//! as opposed to an entire struct or enum. An example of such an attribute is
//! the derive helper attribute for `Reflect`, which looks like: `#[reflect(ignore)]`.
use crate::{custom_attributes::CustomAttributes, REFLECT_ATTRIBUTE_NAME};
use bevy_macro_utils::terminated_parser;
use quote::ToTokens;
use syn::{parse::ParseStream, Attribute, LitStr, Meta, Token, Type};
mod kw {
syn::custom_keyword!(ignore);
syn::custom_keyword!(skip_serializing);
syn::custom_keyword!(clone);
syn::custom_keyword!(default);
syn::custom_keyword!(remote);
}
pub(crate) const IGNORE_SERIALIZATION_ATTR: &str = "skip_serializing";
pub(crate) const IGNORE_ALL_ATTR: &str = "ignore";
pub(crate) const DEFAULT_ATTR: &str = "default";
pub(crate) const CLONE_ATTR: &str = "clone";
/// Stores data about if the field should be visible via the Reflect and serialization interfaces
///
/// Note the relationship between serialization and reflection is such that a member must be reflected in order to be serialized.
/// In boolean logic this is described as: `is_serialized -> is_reflected`, this means we can reflect something without serializing it but not the other way round.
/// The `is_reflected` predicate is provided as `self.is_active()`
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ReflectIgnoreBehavior {
/// Don't ignore, appear to all systems
#[default]
None,
/// Ignore when serializing but not when reflecting
IgnoreSerialization,
/// Ignore both when serializing and reflecting
IgnoreAlways,
}
impl ReflectIgnoreBehavior {
/// Returns `true` if the ignoring behavior implies member is included in the reflection API, and false otherwise.
pub fn is_active(self) -> bool {
match self {
ReflectIgnoreBehavior::None | ReflectIgnoreBehavior::IgnoreSerialization => true,
ReflectIgnoreBehavior::IgnoreAlways => false,
}
}
/// The exact logical opposite of `self.is_active()` returns true iff this member is not part of the reflection API whatsoever (neither serialized nor reflected)
pub fn is_ignored(self) -> bool {
!self.is_active()
}
}
#[derive(Default, Clone)]
pub(crate) enum CloneBehavior {
#[default]
Default,
Trait,
Func(syn::ExprPath),
}
/// Controls how the default value is determined for a field.
#[derive(Default, Clone)]
pub(crate) enum DefaultBehavior {
/// Field is required.
#[default]
Required,
/// Field can be defaulted using `Default::default()`.
Default,
/// Field can be created using the given function name.
///
/// This assumes the function is in scope, is callable with zero arguments,
/// and returns the expected type.
Func(syn::ExprPath),
}
/// A container for attributes defined on a reflected type's field.
#[derive(Default, Clone)]
pub(crate) struct FieldAttributes {
/// Determines how this field should be ignored if at all.
pub ignore: ReflectIgnoreBehavior,
/// Sets the clone behavior of this field.
pub clone: CloneBehavior,
/// Sets the default behavior of this field.
pub default: DefaultBehavior,
/// Custom attributes created via `#[reflect(@...)]`.
pub custom_attributes: CustomAttributes,
/// For defining the remote wrapper type that should be used in place of the field for reflection logic.
pub remote: Option<Type>,
}
impl FieldAttributes {
/// Parse all field attributes marked "reflect" (such as `#[reflect(ignore)]`).
pub fn parse_attributes(attrs: &[Attribute]) -> syn::Result<Self> {
let mut args = FieldAttributes::default();
attrs
.iter()
.filter_map(|attr| {
if !attr.path().is_ident(REFLECT_ATTRIBUTE_NAME) {
// Not a reflect attribute -> skip
return None;
}
let Meta::List(meta) = &attr.meta else {
return Some(syn::Error::new_spanned(attr, "expected meta list"));
};
// Parse all attributes inside the list, collecting any errors
meta.parse_args_with(terminated_parser(Token![,], |stream| {
args.parse_field_attribute(stream)
}))
.err()
})
.reduce(|mut acc, err| {
acc.combine(err);
acc
})
.map_or(Ok(args), Err)
}
/// Parses a single field attribute.
fn parse_field_attribute(&mut self, input: ParseStream) -> syn::Result<()> {
let lookahead = input.lookahead1();
if lookahead.peek(Token![@]) {
self.parse_custom_attribute(input)
} else if lookahead.peek(kw::ignore) {
self.parse_ignore(input)
} else if lookahead.peek(kw::skip_serializing) {
self.parse_skip_serializing(input)
} else if lookahead.peek(kw::clone) {
self.parse_clone(input)
} else if lookahead.peek(kw::default) {
self.parse_default(input)
} else if lookahead.peek(kw::remote) {
self.parse_remote(input)
} else {
Err(lookahead.error())
}
}
/// Parse `ignore` attribute.
///
/// Examples:
/// - `#[reflect(ignore)]`
fn parse_ignore(&mut self, input: ParseStream) -> syn::Result<()> {
if self.ignore != ReflectIgnoreBehavior::None {
return Err(input.error(format!(
"only one of {:?} is allowed",
[IGNORE_ALL_ATTR, IGNORE_SERIALIZATION_ATTR]
)));
}
input.parse::<kw::ignore>()?;
self.ignore = ReflectIgnoreBehavior::IgnoreAlways;
Ok(())
}
/// Parse `skip_serializing` attribute.
///
/// Examples:
/// - `#[reflect(skip_serializing)]`
fn parse_skip_serializing(&mut self, input: ParseStream) -> syn::Result<()> {
if self.ignore != ReflectIgnoreBehavior::None {
return Err(input.error(format!(
"only one of {:?} is allowed",
[IGNORE_ALL_ATTR, IGNORE_SERIALIZATION_ATTR]
)));
}
input.parse::<kw::skip_serializing>()?;
self.ignore = ReflectIgnoreBehavior::IgnoreSerialization;
Ok(())
}
/// Parse `clone` attribute.
///
/// Examples:
/// - `#[reflect(clone)]`
/// - `#[reflect(clone = "path::to::func")]`
fn parse_clone(&mut self, input: ParseStream) -> syn::Result<()> {
if !matches!(self.clone, CloneBehavior::Default) {
return Err(input.error(format!("only one of {:?} is allowed", [CLONE_ATTR])));
}
input.parse::<kw::clone>()?;
if input.peek(Token![=]) {
input.parse::<Token![=]>()?;
let lit = input.parse::<LitStr>()?;
self.clone = CloneBehavior::Func(lit.parse()?);
} else {
self.clone = CloneBehavior::Trait;
}
Ok(())
}
/// Parse `default` attribute.
///
/// Examples:
/// - `#[reflect(default)]`
/// - `#[reflect(default = "path::to::func")]`
fn parse_default(&mut self, input: ParseStream) -> syn::Result<()> {
if !matches!(self.default, DefaultBehavior::Required) {
return Err(input.error(format!("only one of {:?} is allowed", [DEFAULT_ATTR])));
}
input.parse::<kw::default>()?;
if input.peek(Token![=]) {
input.parse::<Token![=]>()?;
let lit = input.parse::<LitStr>()?;
self.default = DefaultBehavior::Func(lit.parse()?);
} else {
self.default = DefaultBehavior::Default;
}
Ok(())
}
/// Parse `@` (custom attribute) attribute.
///
/// Examples:
/// - `#[reflect(@(foo = "bar"))]`
/// - `#[reflect(@(min = 0.0, max = 1.0))]`
fn parse_custom_attribute(&mut self, input: ParseStream) -> syn::Result<()> {
self.custom_attributes.parse_custom_attribute(input)
}
/// Parse `remote` attribute.
///
/// Examples:
/// - `#[reflect(remote = path::to::RemoteType)]`
fn parse_remote(&mut self, input: ParseStream) -> syn::Result<()> {
if let Some(remote) = self.remote.as_ref() {
return Err(input.error(format!(
"remote type already specified as {}",
remote.to_token_stream()
)));
}
input.parse::<kw::remote>()?;
input.parse::<Token![=]>()?;
self.remote = Some(input.parse()?);
Ok(())
}
/// Returns `Some(true)` if the field has a generic remote type.
///
/// If the remote type is not generic, returns `Some(false)`.
///
/// If the field does not have a remote type, returns `None`.
pub fn is_remote_generic(&self) -> Option<bool> {
if let Type::Path(type_path) = self.remote.as_ref()? {
type_path
.path
.segments
.last()
.map(|segment| !segment.arguments.is_empty())
} else {
Some(false)
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/from_reflect.rs | crates/bevy_reflect/derive/src/from_reflect.rs | use crate::{
container_attributes::REFLECT_DEFAULT,
derive_data::ReflectEnum,
enum_utility::{EnumVariantOutputData, FromReflectVariantBuilder, VariantBuilder},
field_attributes::DefaultBehavior,
where_clause_options::WhereClauseOptions,
ReflectMeta, ReflectStruct,
};
use bevy_macro_utils::as_member;
use bevy_macro_utils::fq_std::{FQClone, FQDefault, FQOption};
use proc_macro2::Span;
use quote::{quote, ToTokens};
use syn::{Field, Ident, Lit, LitInt, LitStr, Member};
/// Implements `FromReflect` for the given struct
pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> proc_macro2::TokenStream {
impl_struct_internal(reflect_struct, false)
}
/// Implements `FromReflect` for the given tuple struct
pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> proc_macro2::TokenStream {
impl_struct_internal(reflect_struct, true)
}
pub(crate) fn impl_opaque(meta: &ReflectMeta) -> proc_macro2::TokenStream {
let type_path = meta.type_path();
let bevy_reflect_path = meta.bevy_reflect_path();
let (impl_generics, ty_generics, where_clause) = type_path.generics().split_for_impl();
let where_from_reflect_clause = WhereClauseOptions::new(meta).extend_where_clause(where_clause);
let downcast = match meta.remote_ty() {
Some(remote) => {
let remote_ty = remote.type_path();
quote! {
<Self as #bevy_reflect_path::ReflectRemote>::into_wrapper(
#FQClone::clone(
<dyn #bevy_reflect_path::PartialReflect>::try_downcast_ref::<#remote_ty>(reflect)?
)
)
}
}
None => quote! {
#FQClone::clone(
<dyn #bevy_reflect_path::PartialReflect>::try_downcast_ref::<#type_path #ty_generics>(reflect)?
)
},
};
quote! {
impl #impl_generics #bevy_reflect_path::FromReflect for #type_path #ty_generics #where_from_reflect_clause {
fn from_reflect(reflect: &dyn #bevy_reflect_path::PartialReflect) -> #FQOption<Self> {
#FQOption::Some(#downcast)
}
}
}
}
/// Implements `FromReflect` for the given enum type
pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> proc_macro2::TokenStream {
let fqoption = FQOption.into_token_stream();
let enum_path = reflect_enum.meta().type_path();
let bevy_reflect_path = reflect_enum.meta().bevy_reflect_path();
let ref_value = Ident::new("__param0", Span::call_site());
let EnumVariantOutputData {
variant_names,
variant_constructors,
..
} = FromReflectVariantBuilder::new(reflect_enum).build(&ref_value);
let match_branches = if reflect_enum.meta().is_remote_wrapper() {
quote! {
#(#variant_names => #fqoption::Some(Self(#variant_constructors)),)*
}
} else {
quote! {
#(#variant_names => #fqoption::Some(#variant_constructors),)*
}
};
let (impl_generics, ty_generics, where_clause) = enum_path.generics().split_for_impl();
// Add FromReflect bound for each active field
let where_from_reflect_clause = reflect_enum
.where_clause_options()
.extend_where_clause(where_clause);
quote! {
impl #impl_generics #bevy_reflect_path::FromReflect for #enum_path #ty_generics #where_from_reflect_clause {
fn from_reflect(#ref_value: &dyn #bevy_reflect_path::PartialReflect) -> #FQOption<Self> {
if let #bevy_reflect_path::ReflectRef::Enum(#ref_value) =
#bevy_reflect_path::PartialReflect::reflect_ref(#ref_value)
{
match #bevy_reflect_path::Enum::variant_name(#ref_value) {
#match_branches
name => panic!("variant with name `{}` does not exist on enum `{}`", name, <Self as #bevy_reflect_path::TypePath>::type_path()),
}
} else {
#FQOption::None
}
}
}
}
}
/// Container for a struct's members (field name or index) and their
/// corresponding values.
struct MemberValuePair(Vec<Member>, Vec<proc_macro2::TokenStream>);
impl MemberValuePair {
pub fn new(items: (Vec<Member>, Vec<proc_macro2::TokenStream>)) -> Self {
Self(items.0, items.1)
}
}
fn impl_struct_internal(
reflect_struct: &ReflectStruct,
is_tuple: bool,
) -> proc_macro2::TokenStream {
let fqoption = FQOption.into_token_stream();
let struct_path = reflect_struct.meta().type_path();
let remote_ty = reflect_struct.meta().remote_ty();
let bevy_reflect_path = reflect_struct.meta().bevy_reflect_path();
let ref_struct = Ident::new("__ref_struct", Span::call_site());
let ref_struct_type = if is_tuple {
Ident::new("TupleStruct", Span::call_site())
} else {
Ident::new("Struct", Span::call_site())
};
let MemberValuePair(active_members, active_values) =
get_active_fields(reflect_struct, &ref_struct, &ref_struct_type, is_tuple);
let is_defaultable = reflect_struct.meta().attrs().contains(REFLECT_DEFAULT);
// The constructed "Self" ident
let __this = Ident::new("__this", Span::call_site());
// The reflected type: either `Self` or a remote type
let (reflect_ty, constructor, retval) = if let Some(remote_ty) = remote_ty {
let constructor = match remote_ty.as_expr_path() {
Ok(path) => path,
Err(err) => return err.into_compile_error(),
};
let remote_ty = remote_ty.type_path();
(
quote!(#remote_ty),
quote!(#constructor),
quote!(Self(#__this)),
)
} else {
(quote!(Self), quote!(Self), quote!(#__this))
};
let constructor = if is_defaultable {
quote! {
let mut #__this = <#reflect_ty as #FQDefault>::default();
#(
// The closure catches any failing `?` within `active_values`.
if let #fqoption::Some(__field) = (|| #active_values)() {
// Iff field exists -> use its value
#__this.#active_members = __field;
}
)*
#FQOption::Some(#retval)
}
} else {
let MemberValuePair(ignored_members, ignored_values) = get_ignored_fields(reflect_struct);
quote! {
let #__this = #constructor {
#(#active_members: #active_values?,)*
#(#ignored_members: #ignored_values,)*
};
#FQOption::Some(#retval)
}
};
let (impl_generics, ty_generics, where_clause) = reflect_struct
.meta()
.type_path()
.generics()
.split_for_impl();
// Add FromReflect bound for each active field
let where_from_reflect_clause = reflect_struct
.where_clause_options()
.extend_where_clause(where_clause);
quote! {
impl #impl_generics #bevy_reflect_path::FromReflect for #struct_path #ty_generics #where_from_reflect_clause {
fn from_reflect(reflect: &dyn #bevy_reflect_path::PartialReflect) -> #FQOption<Self> {
if let #bevy_reflect_path::ReflectRef::#ref_struct_type(#ref_struct)
= #bevy_reflect_path::PartialReflect::reflect_ref(reflect)
{
#constructor
} else {
#FQOption::None
}
}
}
}
}
/// Get the collection of ignored field definitions
///
/// Each value of the `MemberValuePair` is a token stream that generates a
/// default value for the ignored field.
fn get_ignored_fields(reflect_struct: &ReflectStruct) -> MemberValuePair {
MemberValuePair::new(
reflect_struct
.ignored_fields()
.map(|field| {
let member = as_member(field.data.ident.as_ref(), field.declaration_index);
let value = match &field.attrs.default {
DefaultBehavior::Func(path) => quote! {#path()},
_ => quote! {#FQDefault::default()},
};
(member, value)
})
.unzip(),
)
}
/// Get the collection of active field definitions.
///
/// Each value of the `MemberValuePair` is a token stream that generates a
/// closure of type `fn() -> Option<T>` where `T` is that field's type.
fn get_active_fields(
reflect_struct: &ReflectStruct,
dyn_struct_name: &Ident,
struct_type: &Ident,
is_tuple: bool,
) -> MemberValuePair {
let bevy_reflect_path = reflect_struct.meta().bevy_reflect_path();
MemberValuePair::new(
reflect_struct
.active_fields()
.map(|field| {
let member = as_member(field.data.ident.as_ref(), field.declaration_index);
let accessor = get_field_accessor(
field.data,
field.reflection_index.expect("field should be active"),
is_tuple,
);
let ty = field.reflected_type().clone();
let real_ty = &field.data.ty;
let get_field = quote! {
#bevy_reflect_path::#struct_type::field(#dyn_struct_name, #accessor)
};
let into_remote = |value: proc_macro2::TokenStream| {
if field.attrs.is_remote_generic().unwrap_or_default() {
quote! {
#FQOption::Some(
// SAFETY: The remote type should always be a `#[repr(transparent)]` for the actual field type
unsafe {
::core::mem::transmute_copy::<#ty, #real_ty>(
&::core::mem::ManuallyDrop::new(#value?)
)
}
)
}
} else if field.attrs().remote.is_some() {
quote! {
#FQOption::Some(
// SAFETY: The remote type should always be a `#[repr(transparent)]` for the actual field type
unsafe {
::core::mem::transmute::<#ty, #real_ty>(#value?)
}
)
}
} else {
value
}
};
let value = match &field.attrs.default {
DefaultBehavior::Func(path) => {
let value = into_remote(quote! {
<#ty as #bevy_reflect_path::FromReflect>::from_reflect(field)
});
quote! {
if let #FQOption::Some(field) = #get_field {
#value
} else {
#FQOption::Some(#path())
}
}
}
DefaultBehavior::Default => {
let value = into_remote(quote! {
<#ty as #bevy_reflect_path::FromReflect>::from_reflect(field)
});
quote! {
if let #FQOption::Some(field) = #get_field {
#value
} else {
#FQOption::Some(#FQDefault::default())
}
}
}
DefaultBehavior::Required => {
let value = into_remote(quote! {
<#ty as #bevy_reflect_path::FromReflect>::from_reflect(#get_field?)
});
quote! {
#value
}
}
};
(member, value)
})
.unzip(),
)
}
/// Returns the accessor for a given field of a struct or tuple struct.
///
/// This differs from a member in that it needs to be a number for tuple structs
/// and a string for standard structs.
fn get_field_accessor(field: &Field, index: usize, is_tuple: bool) -> Lit {
if is_tuple {
Lit::Int(LitInt::new(&index.to_string(), Span::call_site()))
} else {
field
.ident
.as_ref()
.map(|ident| Lit::Str(LitStr::new(&ident.to_string(), Span::call_site())))
.unwrap_or_else(|| Lit::Str(LitStr::new(&index.to_string(), Span::call_site())))
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/meta.rs | crates/bevy_reflect/derive/src/meta.rs | use bevy_macro_utils::BevyManifest;
use syn::Path;
/// Returns the correct path for `bevy_reflect`.
pub(crate) fn get_bevy_reflect_path() -> Path {
BevyManifest::shared(|manifest| manifest.get_path("bevy_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/derive/src/derive_data.rs | crates/bevy_reflect/derive/src/derive_data.rs | use core::fmt;
use indexmap::IndexSet;
use proc_macro2::Span;
use crate::{
container_attributes::{ContainerAttributes, FromReflectAttrs, TypePathAttrs},
field_attributes::FieldAttributes,
remote::RemoteType,
serialization::SerializationDataDef,
string_expr::StringExpr,
type_path::parse_path_no_leading_colon,
where_clause_options::WhereClauseOptions,
REFLECT_ATTRIBUTE_NAME, TYPE_NAME_ATTRIBUTE_NAME, TYPE_PATH_ATTRIBUTE_NAME,
};
use bevy_macro_utils::ResultSifter;
use quote::{format_ident, quote, ToTokens};
use syn::{token::Comma, MacroDelimiter};
use crate::enum_utility::{EnumVariantOutputData, ReflectCloneVariantBuilder, VariantBuilder};
use crate::field_attributes::CloneBehavior;
use crate::generics::generate_generics;
use bevy_macro_utils::fq_std::{FQClone, FQOption, FQResult};
use syn::{
parse_str, punctuated::Punctuated, spanned::Spanned, Data, DeriveInput, Field, Fields,
GenericParam, Generics, Ident, LitStr, Member, Meta, Path, PathSegment, Type, TypeParam,
Variant,
};
pub(crate) enum ReflectDerive<'a> {
Struct(ReflectStruct<'a>),
TupleStruct(ReflectStruct<'a>),
UnitStruct(ReflectStruct<'a>),
Enum(ReflectEnum<'a>),
Opaque(ReflectMeta<'a>),
}
/// Metadata present on all reflected types, including name, generics, and attributes.
///
/// # Example
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// #[derive(Reflect)]
/// // traits
/// // |----------------------------------------|
/// #[reflect(PartialEq, Serialize, Deserialize, Default)]
/// // type_path generics
/// // |-------------------||----------|
/// struct ThingThatImReflecting<T1, T2, T3> {/* ... */}
/// ```
pub(crate) struct ReflectMeta<'a> {
/// The registered traits for this type.
attrs: ContainerAttributes,
/// The path to this type.
type_path: ReflectTypePath<'a>,
/// The optional remote type to use instead of the actual type.
remote_ty: Option<RemoteType<'a>>,
/// A cached instance of the path to the `bevy_reflect` crate.
bevy_reflect_path: Path,
/// The documentation for this type, if any
#[cfg(feature = "reflect_documentation")]
docs: crate::documentation::Documentation,
}
/// Struct data used by derive macros for `Reflect` and `FromReflect`.
///
/// # Example
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// #[derive(Reflect)]
/// #[reflect(PartialEq, Serialize, Deserialize, Default)]
/// struct ThingThatImReflecting<T1, T2, T3> {
/// x: T1, // |
/// y: T2, // |- fields
/// z: T3 // |
/// }
/// ```
pub(crate) struct ReflectStruct<'a> {
meta: ReflectMeta<'a>,
serialization_data: Option<SerializationDataDef>,
fields: Vec<StructField<'a>>,
}
/// Enum data used by derive macros for `Reflect` and `FromReflect`.
///
/// # Example
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// #[derive(Reflect)]
/// #[reflect(PartialEq, Serialize, Deserialize, Default)]
/// enum ThingThatImReflecting<T1, T2, T3> {
/// A(T1), // |
/// B, // |- variants
/// C { foo: T2, bar: T3 } // |
/// }
/// ```
pub(crate) struct ReflectEnum<'a> {
meta: ReflectMeta<'a>,
variants: Vec<EnumVariant<'a>>,
}
/// Represents a field on a struct or tuple struct.
#[derive(Clone)]
pub(crate) struct StructField<'a> {
/// The raw field.
pub data: &'a Field,
/// The reflection-based attributes on the field.
pub attrs: FieldAttributes,
/// The index of this field within the struct.
pub declaration_index: usize,
/// The index of this field as seen by the reflection API.
///
/// This index accounts for the removal of [ignored] fields.
/// It will only be `Some(index)` when the field is not ignored.
///
/// [ignored]: crate::field_attributes::ReflectIgnoreBehavior::IgnoreAlways
pub reflection_index: Option<usize>,
/// The documentation for this field, if any
#[cfg(feature = "reflect_documentation")]
pub doc: crate::documentation::Documentation,
}
/// Represents a variant on an enum.
pub(crate) struct EnumVariant<'a> {
/// The raw variant.
pub data: &'a Variant,
/// The fields within this variant.
pub fields: EnumVariantFields<'a>,
/// The reflection-based attributes on the variant.
pub attrs: FieldAttributes,
/// The documentation for this variant, if any
#[cfg(feature = "reflect_documentation")]
pub doc: crate::documentation::Documentation,
}
pub(crate) enum EnumVariantFields<'a> {
Named(Vec<StructField<'a>>),
Unnamed(Vec<StructField<'a>>),
Unit,
}
/// How the macro was invoked.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum ReflectImplSource {
/// Using `impl_reflect!`.
ImplRemoteType,
/// Using `#[derive(...)]`.
DeriveLocalType,
/// Using `#[reflect_remote]`.
RemoteReflect,
}
/// Which trait the macro explicitly implements.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum ReflectTraitToImpl {
Reflect,
FromReflect,
TypePath,
}
/// The provenance of a macro invocation.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) struct ReflectProvenance {
pub source: ReflectImplSource,
pub trait_: ReflectTraitToImpl,
}
impl fmt::Display for ReflectProvenance {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use self::{ReflectImplSource as S, ReflectTraitToImpl as T};
let str = match (self.source, self.trait_) {
(S::ImplRemoteType, T::Reflect) => "`impl_reflect`",
(S::DeriveLocalType, T::Reflect) => "`#[derive(Reflect)]`",
(S::DeriveLocalType, T::FromReflect) => "`#[derive(FromReflect)]`",
(S::DeriveLocalType, T::TypePath) => "`#[derive(TypePath)]`",
(S::RemoteReflect, T::Reflect) => "`#[reflect_remote]`",
(S::RemoteReflect, T::FromReflect | T::TypePath)
| (S::ImplRemoteType, T::FromReflect | T::TypePath) => unreachable!(),
};
f.write_str(str)
}
}
impl<'a> ReflectDerive<'a> {
pub fn from_input(
input: &'a DeriveInput,
provenance: ReflectProvenance,
) -> Result<Self, syn::Error> {
let mut container_attributes = ContainerAttributes::default();
// Should indicate whether `#[type_path = "..."]` was used.
let mut custom_path: Option<Path> = None;
// Should indicate whether `#[type_name = "..."]` was used.
let mut custom_type_name: Option<Ident> = None;
#[cfg(feature = "reflect_documentation")]
let mut doc = crate::documentation::Documentation::default();
for attribute in &input.attrs {
match &attribute.meta {
Meta::List(meta_list) if meta_list.path.is_ident(REFLECT_ATTRIBUTE_NAME) => {
if let MacroDelimiter::Paren(_) = meta_list.delimiter {
container_attributes.parse_meta_list(meta_list, provenance.trait_)?;
} else {
return Err(syn::Error::new(
meta_list.delimiter.span().join(),
format_args!(
"`#[{REFLECT_ATTRIBUTE_NAME}(\"...\")]` must use parentheses `(` and `)`"
),
));
}
}
Meta::NameValue(pair) if pair.path.is_ident(TYPE_PATH_ATTRIBUTE_NAME) => {
let syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(lit),
..
}) = &pair.value
else {
return Err(syn::Error::new(
pair.span(),
format_args!("`#[{TYPE_PATH_ATTRIBUTE_NAME} = \"...\"]` must be a string literal"),
));
};
custom_path = Some(syn::parse::Parser::parse_str(
parse_path_no_leading_colon,
&lit.value(),
)?);
}
Meta::NameValue(pair) if pair.path.is_ident(TYPE_NAME_ATTRIBUTE_NAME) => {
let syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(lit),
..
}) = &pair.value
else {
return Err(syn::Error::new(
pair.span(),
format_args!("`#[{TYPE_NAME_ATTRIBUTE_NAME} = \"...\"]` must be a string literal"),
));
};
custom_type_name = Some(parse_str(&lit.value())?);
}
#[cfg(feature = "reflect_documentation")]
Meta::NameValue(pair) if pair.path.is_ident("doc") => {
if let syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(lit),
..
}) = &pair.value
{
doc.push(lit.value());
}
}
_ => continue,
}
}
match (&mut custom_path, custom_type_name) {
(Some(path), custom_type_name) => {
let ident = custom_type_name.unwrap_or_else(|| input.ident.clone());
path.segments.push(PathSegment::from(ident));
}
(None, Some(name)) => {
return Err(syn::Error::new(
name.span(),
format!("cannot use `#[{TYPE_NAME_ATTRIBUTE_NAME} = \"...\"]` without a `#[{TYPE_PATH_ATTRIBUTE_NAME} = \"...\"]` attribute."),
));
}
_ => (),
}
let type_path = ReflectTypePath::Internal {
ident: &input.ident,
custom_path,
generics: &input.generics,
};
let meta = ReflectMeta::new(type_path, container_attributes);
if provenance.source == ReflectImplSource::ImplRemoteType
&& meta.type_path_attrs().should_auto_derive()
&& !meta.type_path().has_custom_path()
{
return Err(syn::Error::new(
meta.type_path().span(),
format!("a #[{TYPE_PATH_ATTRIBUTE_NAME} = \"...\"] attribute must be specified when using {provenance}"),
));
}
#[cfg(feature = "reflect_documentation")]
let meta = meta.with_docs(doc);
if meta.attrs().is_opaque() {
return Ok(Self::Opaque(meta));
}
match &input.data {
Data::Struct(data) => {
let fields = Self::collect_struct_fields(&data.fields)?;
let serialization_data =
SerializationDataDef::new(&fields, &meta.bevy_reflect_path)?;
let reflect_struct = ReflectStruct {
meta,
serialization_data,
fields,
};
match data.fields {
Fields::Named(..) => Ok(Self::Struct(reflect_struct)),
Fields::Unnamed(..) => Ok(Self::TupleStruct(reflect_struct)),
Fields::Unit => Ok(Self::UnitStruct(reflect_struct)),
}
}
Data::Enum(data) => {
let variants = Self::collect_enum_variants(&data.variants)?;
let reflect_enum = ReflectEnum { meta, variants };
Ok(Self::Enum(reflect_enum))
}
Data::Union(..) => Err(syn::Error::new(
input.span(),
"reflection not supported for unions",
)),
}
}
/// Set the remote type for this derived type.
///
/// # Panics
///
/// Panics when called on [`ReflectDerive::Opaque`].
pub fn set_remote(&mut self, remote_ty: Option<RemoteType<'a>>) {
match self {
Self::Struct(data) | Self::TupleStruct(data) | Self::UnitStruct(data) => {
data.meta.remote_ty = remote_ty;
}
Self::Enum(data) => {
data.meta.remote_ty = remote_ty;
}
Self::Opaque(meta) => {
meta.remote_ty = remote_ty;
}
}
}
/// Get the remote type path, if any.
pub fn remote_ty(&self) -> Option<RemoteType<'_>> {
match self {
Self::Struct(data) | Self::TupleStruct(data) | Self::UnitStruct(data) => {
data.meta.remote_ty()
}
Self::Enum(data) => data.meta.remote_ty(),
Self::Opaque(meta) => meta.remote_ty(),
}
}
/// Get the [`ReflectMeta`] for this derived type.
pub fn meta(&self) -> &ReflectMeta<'_> {
match self {
Self::Struct(data) | Self::TupleStruct(data) | Self::UnitStruct(data) => data.meta(),
Self::Enum(data) => data.meta(),
Self::Opaque(meta) => meta,
}
}
pub fn where_clause_options(&self) -> WhereClauseOptions<'_, '_> {
match self {
Self::Struct(data) | Self::TupleStruct(data) | Self::UnitStruct(data) => {
data.where_clause_options()
}
Self::Enum(data) => data.where_clause_options(),
Self::Opaque(meta) => WhereClauseOptions::new(meta),
}
}
fn collect_struct_fields(fields: &'a Fields) -> Result<Vec<StructField<'a>>, syn::Error> {
let mut active_index = 0;
let sifter: ResultSifter<StructField<'a>> = fields
.iter()
.enumerate()
.map(
|(declaration_index, field)| -> Result<StructField, syn::Error> {
let attrs = FieldAttributes::parse_attributes(&field.attrs)?;
let reflection_index = if attrs.ignore.is_ignored() {
None
} else {
active_index += 1;
Some(active_index - 1)
};
Ok(StructField {
declaration_index,
reflection_index,
attrs,
data: field,
#[cfg(feature = "reflect_documentation")]
doc: crate::documentation::Documentation::from_attributes(&field.attrs),
})
},
)
.fold(ResultSifter::default(), ResultSifter::fold);
sifter.finish()
}
fn collect_enum_variants(
variants: &'a Punctuated<Variant, Comma>,
) -> Result<Vec<EnumVariant<'a>>, syn::Error> {
let sifter: ResultSifter<EnumVariant<'a>> = variants
.iter()
.map(|variant| -> Result<EnumVariant, syn::Error> {
let fields = Self::collect_struct_fields(&variant.fields)?;
let fields = match variant.fields {
Fields::Named(..) => EnumVariantFields::Named(fields),
Fields::Unnamed(..) => EnumVariantFields::Unnamed(fields),
Fields::Unit => EnumVariantFields::Unit,
};
Ok(EnumVariant {
fields,
attrs: FieldAttributes::parse_attributes(&variant.attrs)?,
data: variant,
#[cfg(feature = "reflect_documentation")]
doc: crate::documentation::Documentation::from_attributes(&variant.attrs),
})
})
.fold(ResultSifter::default(), ResultSifter::fold);
sifter.finish()
}
}
impl<'a> ReflectMeta<'a> {
pub fn new(type_path: ReflectTypePath<'a>, attrs: ContainerAttributes) -> Self {
Self {
attrs,
type_path,
remote_ty: None,
bevy_reflect_path: crate::meta::get_bevy_reflect_path(),
#[cfg(feature = "reflect_documentation")]
docs: Default::default(),
}
}
/// Sets the documentation for this type.
#[cfg(feature = "reflect_documentation")]
pub fn with_docs(self, docs: crate::documentation::Documentation) -> Self {
Self { docs, ..self }
}
/// The registered reflect attributes on this struct.
pub fn attrs(&self) -> &ContainerAttributes {
&self.attrs
}
/// The `FromReflect` attributes on this type.
#[expect(
clippy::wrong_self_convention,
reason = "Method returns `FromReflectAttrs`, does not actually convert data."
)]
pub fn from_reflect(&self) -> &FromReflectAttrs {
self.attrs.from_reflect_attrs()
}
/// The `TypePath` attributes on this type.
pub fn type_path_attrs(&self) -> &TypePathAttrs {
self.attrs.type_path_attrs()
}
/// The path to this type.
pub fn type_path(&self) -> &ReflectTypePath<'a> {
&self.type_path
}
/// Get the remote type path, if any.
pub fn remote_ty(&self) -> Option<RemoteType<'_>> {
self.remote_ty
}
/// Whether this reflected type represents a remote type or not.
pub fn is_remote_wrapper(&self) -> bool {
self.remote_ty.is_some()
}
/// The cached `bevy_reflect` path.
pub fn bevy_reflect_path(&self) -> &Path {
&self.bevy_reflect_path
}
/// Returns the `GetTypeRegistration` impl as a `TokenStream`.
pub fn get_type_registration(
&self,
where_clause_options: &WhereClauseOptions,
) -> proc_macro2::TokenStream {
crate::registration::impl_get_type_registration(
where_clause_options,
None,
Option::<core::iter::Empty<&Type>>::None,
)
}
/// The collection of docstrings for this type, if any.
#[cfg(feature = "reflect_documentation")]
pub fn doc(&self) -> &crate::documentation::Documentation {
&self.docs
}
}
impl<'a> StructField<'a> {
/// Generates a `TokenStream` for `NamedField` or `UnnamedField` construction.
pub fn to_info_tokens(&self, bevy_reflect_path: &Path) -> proc_macro2::TokenStream {
let name = match &self.data.ident {
Some(ident) => ident.to_string().to_token_stream(),
None => self.reflection_index.to_token_stream(),
};
let field_info = if self.data.ident.is_some() {
quote! {
#bevy_reflect_path::NamedField
}
} else {
quote! {
#bevy_reflect_path::UnnamedField
}
};
let ty = self.reflected_type();
let mut info = quote! {
#field_info::new::<#ty>(#name)
};
let custom_attributes = &self.attrs.custom_attributes;
if !custom_attributes.is_empty() {
let custom_attributes = custom_attributes.to_tokens(bevy_reflect_path);
info.extend(quote! {
.with_custom_attributes(#custom_attributes)
});
}
#[cfg(feature = "reflect_documentation")]
{
let docs = &self.doc;
if !docs.is_empty() {
info.extend(quote! {
.with_docs(#docs)
});
}
}
info
}
/// Returns the reflected type of this field.
///
/// Normally this is just the field's defined type.
/// However, this can be adjusted to use a different type, like for representing remote types.
/// In those cases, the returned value is the remote wrapper type.
pub fn reflected_type(&self) -> &Type {
self.attrs.remote.as_ref().unwrap_or(&self.data.ty)
}
pub fn attrs(&self) -> &FieldAttributes {
&self.attrs
}
/// Generates a [`Member`] based on this field.
///
/// If the field is unnamed, the declaration index is used.
/// This allows this member to be used for both active and ignored fields.
pub fn to_member(&self) -> Member {
match &self.data.ident {
Some(ident) => Member::Named(ident.clone()),
None => Member::Unnamed(self.declaration_index.into()),
}
}
/// Returns a token stream for generating a `FieldId` for this field.
pub fn field_id(&self, bevy_reflect_path: &Path) -> proc_macro2::TokenStream {
match &self.data.ident {
Some(ident) => {
let name = ident.to_string();
quote!(#bevy_reflect_path::FieldId::Named(#bevy_reflect_path::__macro_exports::alloc_utils::Cow::Borrowed(#name)))
}
None => {
let index = self.declaration_index;
quote!(#bevy_reflect_path::FieldId::Unnamed(#index))
}
}
}
}
impl<'a> ReflectStruct<'a> {
/// Access the metadata associated with this struct definition.
pub fn meta(&self) -> &ReflectMeta<'a> {
&self.meta
}
/// Returns the [`SerializationDataDef`] for this struct.
pub fn serialization_data(&self) -> Option<&SerializationDataDef> {
self.serialization_data.as_ref()
}
/// Returns the `GetTypeRegistration` impl as a `TokenStream`.
///
/// Returns a specific implementation for structs and this method should be preferred over the generic [`get_type_registration`](ReflectMeta) method
pub fn get_type_registration(
&self,
where_clause_options: &WhereClauseOptions,
) -> proc_macro2::TokenStream {
crate::registration::impl_get_type_registration(
where_clause_options,
self.serialization_data(),
Some(self.active_types().iter()),
)
}
/// Get a collection of types which are exposed to the reflection API
pub fn active_types(&self) -> IndexSet<Type> {
// Collect into an `IndexSet` to eliminate duplicate types.
self.active_fields()
.map(|field| field.reflected_type().clone())
.collect::<IndexSet<_>>()
}
/// Get an iterator of fields which are exposed to the reflection API.
pub fn active_fields(&self) -> impl Iterator<Item = &StructField<'a>> {
self.fields()
.iter()
.filter(|field| field.attrs.ignore.is_active())
}
/// Get an iterator of fields which are ignored by the reflection API
pub fn ignored_fields(&self) -> impl Iterator<Item = &StructField<'a>> {
self.fields()
.iter()
.filter(|field| field.attrs.ignore.is_ignored())
}
/// The complete set of fields in this struct.
pub fn fields(&self) -> &[StructField<'a>] {
&self.fields
}
pub fn where_clause_options(&self) -> WhereClauseOptions<'_, '_> {
WhereClauseOptions::new_with_types(self.meta(), self.active_types())
}
/// Generates a `TokenStream` for `TypeInfo::Struct` or `TypeInfo::TupleStruct` construction.
pub fn to_info_tokens(&self, is_tuple: bool) -> proc_macro2::TokenStream {
let bevy_reflect_path = self.meta().bevy_reflect_path();
let (info_variant, info_struct) = if is_tuple {
(
Ident::new("TupleStruct", Span::call_site()),
Ident::new("TupleStructInfo", Span::call_site()),
)
} else {
(
Ident::new("Struct", Span::call_site()),
Ident::new("StructInfo", Span::call_site()),
)
};
let field_infos = self
.active_fields()
.map(|field| field.to_info_tokens(bevy_reflect_path));
let mut info = quote! {
#bevy_reflect_path::#info_struct::new::<Self>(&[
#(#field_infos),*
])
};
let custom_attributes = self.meta.attrs.custom_attributes();
if !custom_attributes.is_empty() {
let custom_attributes = custom_attributes.to_tokens(bevy_reflect_path);
info.extend(quote! {
.with_custom_attributes(#custom_attributes)
});
}
if let Some(generics) = generate_generics(self.meta()) {
info.extend(quote! {
.with_generics(#generics)
});
}
#[cfg(feature = "reflect_documentation")]
{
let docs = self.meta().doc();
if !docs.is_empty() {
info.extend(quote! {
.with_docs(#docs)
});
}
}
quote! {
#bevy_reflect_path::TypeInfo::#info_variant(#info)
}
}
/// Returns the `Reflect::reflect_clone` impl, if any, as a `TokenStream`.
pub fn get_clone_impl(&self) -> Option<proc_macro2::TokenStream> {
let bevy_reflect_path = self.meta().bevy_reflect_path();
if let container_clone @ Some(_) = self.meta().attrs().get_clone_impl(bevy_reflect_path) {
return container_clone;
}
let mut tokens = proc_macro2::TokenStream::new();
for field in self.fields().iter() {
let field_ty = field.reflected_type();
let member = field.to_member();
let accessor = self.access_for_field(field, false);
match &field.attrs.clone {
CloneBehavior::Default => {
let value = if field.attrs.ignore.is_ignored() {
let field_id = field.field_id(bevy_reflect_path);
quote! {
return #FQResult::Err(#bevy_reflect_path::ReflectCloneError::FieldNotCloneable {
field: #field_id,
variant: #FQOption::None,
container_type_path: #bevy_reflect_path::__macro_exports::alloc_utils::Cow::Borrowed(
<Self as #bevy_reflect_path::TypePath>::type_path()
)
})
}
} else {
quote! {
<#field_ty as #bevy_reflect_path::PartialReflect>::reflect_clone_and_take(#accessor)?
}
};
tokens.extend(quote! {
#member: #value,
});
}
CloneBehavior::Trait => {
tokens.extend(quote! {
#member: #FQClone::clone(#accessor),
});
}
CloneBehavior::Func(clone_fn) => {
tokens.extend(quote! {
#member: #clone_fn(#accessor),
});
}
}
}
let ctor = match self.meta.remote_ty() {
Some(ty) => {
let ty = ty.as_expr_path().ok()?.to_token_stream();
quote! {
Self(#ty {
#tokens
})
}
}
None => {
quote! {
Self {
#tokens
}
}
}
};
Some(quote! {
#[inline]
#[allow(unreachable_code, reason = "Ignored fields without a `clone` attribute will early-return with an error")]
fn reflect_clone(&self) -> #FQResult<#bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #bevy_reflect_path::Reflect>, #bevy_reflect_path::ReflectCloneError> {
#FQResult::Ok(#bevy_reflect_path::__macro_exports::alloc_utils::Box::new(#ctor))
}
})
}
/// Generates an accessor for the given field.
///
/// The mutability of the access can be controlled by the `is_mut` parameter.
///
/// Generally, this just returns something like `&self.field`.
/// However, if the struct is a remote wrapper, this then becomes `&self.0.field` in order to access the field on the inner type.
///
/// If the field itself is a remote type, the above accessor is further wrapped in a call to `ReflectRemote::as_wrapper[_mut]`.
pub fn access_for_field(
&self,
field: &StructField<'a>,
is_mutable: bool,
) -> proc_macro2::TokenStream {
let bevy_reflect_path = self.meta().bevy_reflect_path();
let member = field.to_member();
let prefix_tokens = if is_mutable { quote!(&mut) } else { quote!(&) };
let accessor = if self.meta.is_remote_wrapper() {
quote!(self.0.#member)
} else {
quote!(self.#member)
};
match &field.attrs.remote {
Some(wrapper_ty) => {
let method = if is_mutable {
format_ident!("as_wrapper_mut")
} else {
format_ident!("as_wrapper")
};
quote! {
<#wrapper_ty as #bevy_reflect_path::ReflectRemote>::#method(#prefix_tokens #accessor)
}
}
None => quote!(#prefix_tokens #accessor),
}
}
}
impl<'a> ReflectEnum<'a> {
/// Access the metadata associated with this enum definition.
pub fn meta(&self) -> &ReflectMeta<'a> {
&self.meta
}
/// Returns the given ident as a qualified unit variant of this enum.
///
/// This takes into account the remote type, if any.
pub fn get_unit(&self, variant: &Ident) -> proc_macro2::TokenStream {
let name = self
.meta
.remote_ty
.map(|path| match path.as_expr_path() {
Ok(path) => path.to_token_stream(),
Err(err) => err.into_compile_error(),
})
.unwrap_or_else(|| self.meta.type_path().to_token_stream());
quote! {
#name::#variant
}
}
/// The complete set of variants in this enum.
pub fn variants(&self) -> &[EnumVariant<'a>] {
&self.variants
}
/// Get a collection of types which are exposed to the reflection API
pub fn active_types(&self) -> IndexSet<Type> {
// Collect into an `IndexSet` to eliminate duplicate types.
self.active_fields()
.map(|field| field.reflected_type().clone())
.collect::<IndexSet<_>>()
}
/// Get an iterator of fields which are exposed to the reflection API
pub fn active_fields(&self) -> impl Iterator<Item = &StructField<'a>> {
self.variants.iter().flat_map(EnumVariant::active_fields)
}
pub fn where_clause_options(&self) -> WhereClauseOptions<'_, '_> {
WhereClauseOptions::new_with_types(self.meta(), self.active_types())
}
/// Returns the `GetTypeRegistration` impl as a `TokenStream`.
///
/// Returns a specific implementation for enums and this method should be preferred over the generic [`get_type_registration`](crate::ReflectMeta) method
pub fn get_type_registration(
&self,
where_clause_options: &WhereClauseOptions,
) -> proc_macro2::TokenStream {
crate::registration::impl_get_type_registration(
where_clause_options,
None,
Some(self.active_types().iter()),
)
}
/// Generates a `TokenStream` for `TypeInfo::Enum` construction.
pub fn to_info_tokens(&self) -> proc_macro2::TokenStream {
let bevy_reflect_path = self.meta().bevy_reflect_path();
let variants = self
.variants
.iter()
.map(|variant| variant.to_info_tokens(bevy_reflect_path));
let mut info = quote! {
#bevy_reflect_path::EnumInfo::new::<Self>(&[
#(#variants),*
])
};
let custom_attributes = self.meta.attrs.custom_attributes();
if !custom_attributes.is_empty() {
let custom_attributes = custom_attributes.to_tokens(bevy_reflect_path);
info.extend(quote! {
.with_custom_attributes(#custom_attributes)
});
}
if let Some(generics) = generate_generics(self.meta()) {
info.extend(quote! {
.with_generics(#generics)
});
}
#[cfg(feature = "reflect_documentation")]
{
let docs = self.meta().doc();
if !docs.is_empty() {
info.extend(quote! {
.with_docs(#docs)
});
}
}
quote! {
#bevy_reflect_path::TypeInfo::Enum(#info)
}
}
/// Returns the `Reflect::reflect_clone` impl, if any, as a `TokenStream`.
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/registration.rs | crates/bevy_reflect/derive/src/registration.rs | //! Contains code related specifically to Bevy's type registration.
use crate::{serialization::SerializationDataDef, where_clause_options::WhereClauseOptions};
use quote::quote;
use syn::Type;
/// Creates the `GetTypeRegistration` impl for the given type data.
pub(crate) fn impl_get_type_registration<'a>(
where_clause_options: &WhereClauseOptions,
serialization_data: Option<&SerializationDataDef>,
type_dependencies: Option<impl Iterator<Item = &'a Type>>,
) -> proc_macro2::TokenStream {
let meta = where_clause_options.meta();
let type_path = meta.type_path();
let bevy_reflect_path = meta.bevy_reflect_path();
let registration_data = meta.attrs().idents();
let type_deps_fn = type_dependencies.map(|deps| {
quote! {
#[inline(never)]
fn register_type_dependencies(registry: &mut #bevy_reflect_path::TypeRegistry) {
#(<#deps as #bevy_reflect_path::__macro_exports::RegisterForReflection>::__register(registry);)*
}
}
});
let (impl_generics, ty_generics, where_clause) = type_path.generics().split_for_impl();
let where_reflect_clause = where_clause_options.extend_where_clause(where_clause);
let from_reflect_data = if meta.from_reflect().should_auto_derive() {
Some(quote! {
registration.insert::<#bevy_reflect_path::ReflectFromReflect>(#bevy_reflect_path::FromType::<Self>::from_type());
})
} else {
None
};
let serialization_data = serialization_data.map(|data| {
let serialization_data = data.as_serialization_data(bevy_reflect_path);
quote! {
registration.insert::<#bevy_reflect_path::serde::SerializationData>(#serialization_data);
}
});
quote! {
impl #impl_generics #bevy_reflect_path::GetTypeRegistration for #type_path #ty_generics #where_reflect_clause {
fn get_type_registration() -> #bevy_reflect_path::TypeRegistration {
let mut registration = #bevy_reflect_path::TypeRegistration::of::<Self>();
registration.insert::<#bevy_reflect_path::ReflectFromPtr>(#bevy_reflect_path::FromType::<Self>::from_type());
#from_reflect_data
#serialization_data
#(registration.register_type_data::<#registration_data, Self>();)*
registration
}
#type_deps_fn
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/where_clause_options.rs | crates/bevy_reflect/derive/src/where_clause_options.rs | use crate::derive_data::ReflectMeta;
use bevy_macro_utils::fq_std::{FQAny, FQSend, FQSync};
use indexmap::IndexSet;
use proc_macro2::{TokenStream, TokenTree};
use quote::{quote, ToTokens};
use syn::{punctuated::Punctuated, Ident, Token, Type, WhereClause};
/// Options defining how to extend the `where` clause for reflection.
pub(crate) struct WhereClauseOptions<'a, 'b> {
meta: &'a ReflectMeta<'b>,
active_types: IndexSet<Type>,
}
impl<'a, 'b> WhereClauseOptions<'a, 'b> {
pub fn new(meta: &'a ReflectMeta<'b>) -> Self {
Self {
meta,
active_types: IndexSet::new(),
}
}
pub fn new_with_types(meta: &'a ReflectMeta<'b>, active_types: IndexSet<Type>) -> Self {
Self { meta, active_types }
}
pub fn meta(&self) -> &'a ReflectMeta<'b> {
self.meta
}
/// Extends the `where` clause for a type with additional bounds needed for the reflection
/// impls.
///
/// The default bounds added are as follows:
/// - `Self` has:
/// - `Any + Send + Sync` bounds, if generic over types
/// - An `Any` bound, if generic over lifetimes but not types
/// - No bounds, if generic over neither types nor lifetimes
/// - Any given bounds in a `where` clause on the type
/// - Type parameters have the bound `TypePath` unless `#[reflect(type_path = false)]` is
/// present
/// - Active fields with non-generic types have the bounds `TypePath`, either `PartialReflect`
/// if `#[reflect(from_reflect = false)]` is present or `FromReflect` otherwise,
/// `MaybeTyped`, and `RegisterForReflection` (or no bounds at all if
/// `#[reflect(no_field_bounds)]` is present)
///
/// When the derive is used with `#[reflect(where)]`, the bounds specified in the attribute are
/// added as well.
///
/// # Example
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// #[derive(Reflect)]
/// struct Foo<T, U> {
/// a: T,
/// #[reflect(ignore)]
/// b: U
/// }
/// ```
///
/// Generates the following where clause:
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// where
/// // `Self` bounds:
/// Foo<T, U>: Any + Send + Sync,
/// // Type parameter bounds:
/// T: TypePath,
/// U: TypePath,
/// // Active non-generic field bounds
/// T: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
///
/// ```
///
/// If we add various things to the type:
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// #[derive(Reflect)]
/// #[reflect(where T: MyTrait)]
/// #[reflect(no_field_bounds)]
/// struct Foo<T, U>
/// where T: Clone
/// {
/// a: T,
/// #[reflect(ignore)]
/// b: U
/// }
/// ```
///
/// It will instead generate the following where clause:
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// where
/// // `Self` bounds:
/// Foo<T, U>: Any + Send + Sync,
/// // Given bounds:
/// T: Clone,
/// // Type parameter bounds:
/// T: TypePath,
/// U: TypePath,
/// // No active non-generic field bounds
/// // Custom bounds
/// T: MyTrait,
/// ```
pub fn extend_where_clause(&self, where_clause: Option<&WhereClause>) -> TokenStream {
let mut generic_where_clause = quote! { where };
// Bounds on `Self`. We would normally just use `Self`, but that won't work for generating
// things like assertion functions and trait impls for a type's reference (e.g. `impl
// FromArg for &MyType`).
let generics = self.meta.type_path().generics();
if generics.type_params().next().is_some() {
// Generic over types? We need `Any + Send + Sync`.
let this = self.meta.type_path().true_type();
generic_where_clause.extend(quote! { #this: #FQAny + #FQSend + #FQSync, });
} else if generics.lifetimes().next().is_some() {
// Generic only over lifetimes? We need `'static`.
let this = self.meta.type_path().true_type();
generic_where_clause.extend(quote! { #this: 'static, });
}
// Maintain existing where clause bounds, if any.
if let Some(where_clause) = where_clause {
let predicates = where_clause.predicates.iter();
generic_where_clause.extend(quote! { #(#predicates,)* });
}
// Add additional reflection trait bounds.
let predicates = self.predicates();
generic_where_clause.extend(quote! {
#predicates
});
generic_where_clause
}
/// Returns an iterator the where clause predicates to extended the where clause with.
fn predicates(&self) -> Punctuated<TokenStream, Token![,]> {
let mut predicates = Punctuated::new();
if let Some(type_param_predicates) = self.type_param_predicates() {
predicates.extend(type_param_predicates);
}
if let Some(field_predicates) = self.active_field_predicates() {
predicates.extend(field_predicates);
}
if let Some(custom_where) = self.meta.attrs().custom_where() {
predicates.push(custom_where.predicates.to_token_stream());
}
predicates
}
/// Returns an iterator over the where clause predicates for the type parameters
/// if they require one.
fn type_param_predicates(&self) -> Option<impl Iterator<Item = TokenStream> + '_> {
self.type_path_bound().map(|type_path_bound| {
self.meta
.type_path()
.generics()
.type_params()
.map(move |param| {
let ident = ¶m.ident;
quote!(#ident : #type_path_bound)
})
})
}
/// Returns an iterator over the where clause predicates for the active fields.
fn active_field_predicates(&self) -> Option<impl Iterator<Item = TokenStream> + '_> {
if self.meta.attrs().no_field_bounds() {
None
} else {
let bevy_reflect_path = self.meta.bevy_reflect_path();
let reflect_bound = self.reflect_bound();
// Get the identifiers of all type parameters.
let type_param_idents = self
.meta
.type_path()
.generics()
.type_params()
.map(|type_param| type_param.ident.clone())
.collect::<Vec<Ident>>();
// Do any of the identifiers in `idents` appear in `token_stream`?
fn is_any_ident_in_token_stream(idents: &[Ident], token_stream: TokenStream) -> bool {
for token_tree in token_stream {
match token_tree {
TokenTree::Ident(ident) => {
if idents.contains(&ident) {
return true;
}
}
TokenTree::Group(group) => {
if is_any_ident_in_token_stream(idents, group.stream()) {
return true;
}
}
TokenTree::Punct(_) | TokenTree::Literal(_) => {}
}
}
false
}
Some(self.active_types.iter().filter_map(move |ty| {
// Field type bounds are only required if `ty` is generic. How to determine that?
// Search `ty`s token stream for identifiers that match the identifiers from the
// function's type params. E.g. if `T` and `U` are the type param identifiers and
// `ty` is `Vec<[T; 4]>` then the `T` identifiers match. This is a bit hacky, but
// it works.
let is_generic =
is_any_ident_in_token_stream(&type_param_idents, ty.to_token_stream());
is_generic.then(|| {
quote!(
#ty: #reflect_bound
// Needed to construct `NamedField` and `UnnamedField` instances for
// the `Typed` impl.
+ #bevy_reflect_path::TypePath
// Needed for `Typed` impls
+ #bevy_reflect_path::MaybeTyped
// Needed for registering type dependencies in the
// `GetTypeRegistration` impl.
+ #bevy_reflect_path::__macro_exports::RegisterForReflection
)
})
}))
}
}
/// The `PartialReflect` or `FromReflect` bound to use based on `#[reflect(from_reflect = false)]`.
fn reflect_bound(&self) -> TokenStream {
let bevy_reflect_path = self.meta.bevy_reflect_path();
if self.meta.from_reflect().should_auto_derive() {
quote!(#bevy_reflect_path::FromReflect)
} else {
quote!(#bevy_reflect_path::PartialReflect)
}
}
/// The `TypePath` bounds to use based on `#[reflect(type_path = false)]`.
fn type_path_bound(&self) -> Option<TokenStream> {
if self.meta.type_path_attrs().should_auto_derive() {
let bevy_reflect_path = self.meta.bevy_reflect_path();
Some(quote!(#bevy_reflect_path::TypePath))
} else {
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/derive/src/container_attributes.rs | crates/bevy_reflect/derive/src/container_attributes.rs | //! Contains code related to container attributes for reflected types.
//!
//! A container attribute is an attribute which applies to an entire struct or enum
//! as opposed to a particular field or variant. An example of such an attribute is
//! the derive helper attribute for `Reflect`, which looks like:
//! `#[reflect(PartialEq, Default, ...)]`.
use crate::{custom_attributes::CustomAttributes, derive_data::ReflectTraitToImpl};
use bevy_macro_utils::{
fq_std::{FQAny, FQClone, FQOption, FQResult},
terminated_parser,
};
use proc_macro2::{Ident, Span};
use quote::quote_spanned;
use syn::{
ext::IdentExt, parenthesized, parse::ParseStream, spanned::Spanned, token, Expr, LitBool,
MetaList, MetaNameValue, Path, Token, WhereClause,
};
mod kw {
syn::custom_keyword!(from_reflect);
syn::custom_keyword!(type_path);
syn::custom_keyword!(Debug);
syn::custom_keyword!(PartialEq);
syn::custom_keyword!(Hash);
syn::custom_keyword!(Clone);
syn::custom_keyword!(no_field_bounds);
syn::custom_keyword!(no_auto_register);
syn::custom_keyword!(opaque);
}
// The "special" trait idents that are used internally for reflection.
// Received via attributes like `#[reflect(PartialEq, Hash, ...)]`
const DEBUG_ATTR: &str = "Debug";
const PARTIAL_EQ_ATTR: &str = "PartialEq";
const HASH_ATTR: &str = "Hash";
// The traits listed below are not considered "special" (i.e. they use the `ReflectMyTrait` syntax)
// but useful to know exist nonetheless
pub(crate) const REFLECT_DEFAULT: &str = "ReflectDefault";
// Attributes for `FromReflect` implementation
const FROM_REFLECT_ATTR: &str = "from_reflect";
// Attributes for `TypePath` implementation
const TYPE_PATH_ATTR: &str = "type_path";
// The error message to show when a trait/type is specified multiple times
const CONFLICTING_TYPE_DATA_MESSAGE: &str = "conflicting type data registration";
/// A marker for trait implementations registered via the `Reflect` derive macro.
#[derive(Clone, Default)]
pub(crate) enum TraitImpl {
/// The trait is not registered as implemented.
#[default]
NotImplemented,
/// The trait is registered as implemented.
Implemented(Span),
/// The trait is registered with a custom function rather than an actual implementation.
Custom(Path, Span),
}
impl TraitImpl {
/// Merges this [`TraitImpl`] with another.
///
/// Update `self` with whichever value is not [`TraitImpl::NotImplemented`].
/// If `other` is [`TraitImpl::NotImplemented`], then `self` is not modified.
/// An error is returned if neither value is [`TraitImpl::NotImplemented`].
pub fn merge(&mut self, other: TraitImpl) -> Result<(), syn::Error> {
match (&self, other) {
(TraitImpl::NotImplemented, value) => {
*self = value;
Ok(())
}
(_, TraitImpl::NotImplemented) => Ok(()),
(_, TraitImpl::Implemented(span) | TraitImpl::Custom(_, span)) => {
Err(syn::Error::new(span, CONFLICTING_TYPE_DATA_MESSAGE))
}
}
}
}
/// A collection of attributes used for deriving `FromReflect`.
#[derive(Clone, Default)]
pub(crate) struct FromReflectAttrs {
auto_derive: Option<LitBool>,
}
impl FromReflectAttrs {
/// Returns true if `FromReflect` should be automatically derived as part of the `Reflect` derive.
pub fn should_auto_derive(&self) -> bool {
self.auto_derive.as_ref().is_none_or(LitBool::value)
}
}
/// A collection of attributes used for deriving `TypePath` via the `Reflect` derive.
///
/// Note that this differs from the attributes used by the `TypePath` derive itself,
/// which look like `[type_path = "my_crate::foo"]`.
/// The attributes used by reflection take the form `#[reflect(type_path = false)]`.
///
/// These attributes should only be used for `TypePath` configuration specific to
/// deriving `Reflect`.
#[derive(Clone, Default)]
pub(crate) struct TypePathAttrs {
auto_derive: Option<LitBool>,
}
impl TypePathAttrs {
/// Returns true if `TypePath` should be automatically derived as part of the `Reflect` derive.
pub fn should_auto_derive(&self) -> bool {
self.auto_derive.as_ref().is_none_or(LitBool::value)
}
}
/// A collection of traits that have been registered for a reflected type.
///
/// This keeps track of a few traits that are utilized internally for reflection
/// (we'll call these traits _special traits_ within this context), but it
/// will also keep track of all registered traits. Traits are registered as part of the
/// `Reflect` derive macro using the helper attribute: `#[reflect(...)]`.
///
/// The list of special traits are as follows:
/// * `Debug`
/// * `Hash`
/// * `PartialEq`
///
/// When registering a trait, there are a few things to keep in mind:
/// * Traits must have a valid `Reflect{}` struct in scope. For example, `Default`
/// needs `bevy_reflect::prelude::ReflectDefault` in scope.
/// * Traits must be single path identifiers. This means you _must_ use `Default`
/// instead of `std::default::Default` (otherwise it will try to register `Reflectstd`!)
/// * A custom function may be supplied in place of an actual implementation
/// for the special traits (but still follows the same single-path identifier
/// rules as normal).
///
/// # Example
///
/// Registering the `Default` implementation:
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// // Import ReflectDefault so it's accessible by the derive macro
/// use bevy_reflect::prelude::ReflectDefault;
///
/// #[derive(Reflect, Default)]
/// #[reflect(Default)]
/// struct Foo;
/// ```
///
/// Registering the `Hash` implementation:
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// // `Hash` is a "special trait" and does not need (nor have) a ReflectHash struct
///
/// #[derive(Reflect, Hash)]
/// #[reflect(Hash)]
/// struct Foo;
/// ```
///
/// Registering the `Hash` implementation using a custom function:
///
/// ```ignore (bevy_reflect is not accessible from this crate)
/// // This function acts as our `Hash` implementation and
/// // corresponds to the `Reflect::reflect_hash` method.
/// fn get_hash(foo: &Foo) -> Option<u64> {
/// Some(123)
/// }
///
/// #[derive(Reflect)]
/// // Register the custom `Hash` function
/// #[reflect(Hash(get_hash))]
/// struct Foo;
/// ```
///
/// > __Note:__ Registering a custom function only works for special traits.
#[derive(Default, Clone)]
pub(crate) struct ContainerAttributes {
clone: TraitImpl,
debug: TraitImpl,
hash: TraitImpl,
partial_eq: TraitImpl,
from_reflect_attrs: FromReflectAttrs,
type_path_attrs: TypePathAttrs,
custom_where: Option<WhereClause>,
no_field_bounds: bool,
no_auto_register: bool,
custom_attributes: CustomAttributes,
is_opaque: bool,
idents: Vec<Ident>,
}
impl ContainerAttributes {
/// Parse a comma-separated list of container attributes.
///
/// # Example
/// - `Hash, Debug(custom_debug), MyTrait`
pub fn parse_terminated(
&mut self,
input: ParseStream,
trait_: ReflectTraitToImpl,
) -> syn::Result<()> {
terminated_parser(Token![,], |stream| {
self.parse_container_attribute(stream, trait_)
})(input)?;
Ok(())
}
/// Parse the contents of a `#[reflect(...)]` attribute into a [`ContainerAttributes`] instance.
///
/// # Example
/// - `#[reflect(Hash, Debug(custom_debug), MyTrait)]`
/// - `#[reflect(no_field_bounds)]`
pub fn parse_meta_list(
&mut self,
meta: &MetaList,
trait_: ReflectTraitToImpl,
) -> syn::Result<()> {
meta.parse_args_with(|stream: ParseStream| self.parse_terminated(stream, trait_))
}
/// Parse a single container attribute.
fn parse_container_attribute(
&mut self,
input: ParseStream,
trait_: ReflectTraitToImpl,
) -> syn::Result<()> {
let lookahead = input.lookahead1();
if lookahead.peek(Token![@]) {
self.custom_attributes.parse_custom_attribute(input)
} else if lookahead.peek(Token![where]) {
self.parse_custom_where(input)
} else if lookahead.peek(kw::from_reflect) {
self.parse_from_reflect(input, trait_)
} else if lookahead.peek(kw::type_path) {
self.parse_type_path(input, trait_)
} else if lookahead.peek(kw::opaque) {
self.parse_opaque(input)
} else if lookahead.peek(kw::no_field_bounds) {
self.parse_no_field_bounds(input)
} else if lookahead.peek(kw::Clone) {
self.parse_clone(input)
} else if lookahead.peek(kw::no_auto_register) {
self.parse_no_auto_register(input)
} else if lookahead.peek(kw::Debug) {
self.parse_debug(input)
} else if lookahead.peek(kw::Hash) {
self.parse_hash(input)
} else if lookahead.peek(kw::PartialEq) {
self.parse_partial_eq(input)
} else if lookahead.peek(Ident::peek_any) {
self.parse_ident(input)
} else {
Err(lookahead.error())
}
}
/// Parse an ident (for registration).
///
/// Examples:
/// - `#[reflect(MyTrait)]` (registers `ReflectMyTrait`)
fn parse_ident(&mut self, input: ParseStream) -> syn::Result<()> {
let ident = input.parse::<Ident>()?;
if input.peek(token::Paren) {
return Err(syn::Error::new(ident.span(), format!(
"only [{DEBUG_ATTR:?}, {PARTIAL_EQ_ATTR:?}, {HASH_ATTR:?}] may specify custom functions",
)));
}
let ident_name = ident.to_string();
// Create the reflect ident
let mut reflect_ident = crate::ident::get_reflect_ident(&ident_name);
// We set the span to the old ident so any compile errors point to that ident instead
reflect_ident.set_span(ident.span());
add_unique_ident(&mut self.idents, reflect_ident)?;
Ok(())
}
/// Parse `clone` attribute.
///
/// Examples:
/// - `#[reflect(Clone)]`
/// - `#[reflect(Clone(custom_clone_fn))]`
fn parse_clone(&mut self, input: ParseStream) -> syn::Result<()> {
let ident = input.parse::<kw::Clone>()?;
if input.peek(token::Paren) {
let content;
parenthesized!(content in input);
let path = content.parse::<Path>()?;
self.clone.merge(TraitImpl::Custom(path, ident.span))?;
} else {
self.clone = TraitImpl::Implemented(ident.span);
}
Ok(())
}
/// Parse special `Debug` registration.
///
/// Examples:
/// - `#[reflect(Debug)]`
/// - `#[reflect(Debug(custom_debug_fn))]`
fn parse_debug(&mut self, input: ParseStream) -> syn::Result<()> {
let ident = input.parse::<kw::Debug>()?;
if input.peek(token::Paren) {
let content;
parenthesized!(content in input);
let path = content.parse::<Path>()?;
self.debug.merge(TraitImpl::Custom(path, ident.span))?;
} else {
self.debug = TraitImpl::Implemented(ident.span);
}
Ok(())
}
/// Parse special `PartialEq` registration.
///
/// Examples:
/// - `#[reflect(PartialEq)]`
/// - `#[reflect(PartialEq(custom_partial_eq_fn))]`
fn parse_partial_eq(&mut self, input: ParseStream) -> syn::Result<()> {
let ident = input.parse::<kw::PartialEq>()?;
if input.peek(token::Paren) {
let content;
parenthesized!(content in input);
let path = content.parse::<Path>()?;
self.partial_eq.merge(TraitImpl::Custom(path, ident.span))?;
} else {
self.partial_eq = TraitImpl::Implemented(ident.span);
}
Ok(())
}
/// Parse special `Hash` registration.
///
/// Examples:
/// - `#[reflect(Hash)]`
/// - `#[reflect(Hash(custom_hash_fn))]`
fn parse_hash(&mut self, input: ParseStream) -> syn::Result<()> {
let ident = input.parse::<kw::Hash>()?;
if input.peek(token::Paren) {
let content;
parenthesized!(content in input);
let path = content.parse::<Path>()?;
self.hash.merge(TraitImpl::Custom(path, ident.span))?;
} else {
self.hash = TraitImpl::Implemented(ident.span);
}
Ok(())
}
/// Parse `opaque` attribute.
///
/// Examples:
/// - `#[reflect(opaque)]`
fn parse_opaque(&mut self, input: ParseStream) -> syn::Result<()> {
input.parse::<kw::opaque>()?;
self.is_opaque = true;
Ok(())
}
/// Parse `no_field_bounds` attribute.
///
/// Examples:
/// - `#[reflect(no_field_bounds)]`
fn parse_no_field_bounds(&mut self, input: ParseStream) -> syn::Result<()> {
input.parse::<kw::no_field_bounds>()?;
self.no_field_bounds = true;
Ok(())
}
/// Parse `no_auto_register` attribute.
///
/// Examples:
/// - `#[reflect(no_auto_register)]`
fn parse_no_auto_register(&mut self, input: ParseStream) -> syn::Result<()> {
input.parse::<kw::no_auto_register>()?;
self.no_auto_register = true;
Ok(())
}
/// Parse `where` attribute.
///
/// Examples:
/// - `#[reflect(where T: Debug)]`
fn parse_custom_where(&mut self, input: ParseStream) -> syn::Result<()> {
self.custom_where = Some(input.parse()?);
Ok(())
}
/// Parse `from_reflect` attribute.
///
/// Examples:
/// - `#[reflect(from_reflect = false)]`
fn parse_from_reflect(
&mut self,
input: ParseStream,
trait_: ReflectTraitToImpl,
) -> syn::Result<()> {
let pair = input.parse::<MetaNameValue>()?;
let extracted_bool = extract_bool(&pair.value, |lit| {
// Override `lit` if this is a `FromReflect` derive.
// This typically means a user is opting out of the default implementation
// from the `Reflect` derive and using the `FromReflect` derive directly instead.
if trait_ == ReflectTraitToImpl::FromReflect {
LitBool::new(true, Span::call_site())
} else {
lit.clone()
}
})?;
if let Some(existing) = &self.from_reflect_attrs.auto_derive {
if existing.value() != extracted_bool.value() {
return Err(syn::Error::new(
extracted_bool.span(),
format!("`{FROM_REFLECT_ATTR}` already set to {}", existing.value()),
));
}
} else {
self.from_reflect_attrs.auto_derive = Some(extracted_bool);
}
Ok(())
}
/// Parse `type_path` attribute.
///
/// Examples:
/// - `#[reflect(type_path = false)]`
fn parse_type_path(
&mut self,
input: ParseStream,
trait_: ReflectTraitToImpl,
) -> syn::Result<()> {
let pair = input.parse::<MetaNameValue>()?;
let extracted_bool = extract_bool(&pair.value, |lit| {
// Override `lit` if this is a `FromReflect` derive.
// This typically means a user is opting out of the default implementation
// from the `Reflect` derive and using the `FromReflect` derive directly instead.
if trait_ == ReflectTraitToImpl::TypePath {
LitBool::new(true, Span::call_site())
} else {
lit.clone()
}
})?;
if let Some(existing) = &self.type_path_attrs.auto_derive {
if existing.value() != extracted_bool.value() {
return Err(syn::Error::new(
extracted_bool.span(),
format!("`{TYPE_PATH_ATTR}` already set to {}", existing.value()),
));
}
} else {
self.type_path_attrs.auto_derive = Some(extracted_bool);
}
Ok(())
}
/// Returns true if the given reflected trait name (i.e. `ReflectDefault` for `Default`)
/// is registered for this type.
pub fn contains(&self, name: &str) -> bool {
self.idents.iter().any(|ident| ident == name)
}
/// The list of reflected traits by their reflected ident (i.e. `ReflectDefault` for `Default`).
pub fn idents(&self) -> &[Ident] {
&self.idents
}
/// The `FromReflect` configuration found within `#[reflect(...)]` attributes on this type.
#[expect(
clippy::wrong_self_convention,
reason = "Method returns `FromReflectAttrs`, does not actually convert data."
)]
pub fn from_reflect_attrs(&self) -> &FromReflectAttrs {
&self.from_reflect_attrs
}
/// The `TypePath` configuration found within `#[reflect(...)]` attributes on this type.
pub fn type_path_attrs(&self) -> &TypePathAttrs {
&self.type_path_attrs
}
/// Returns the implementation of `PartialReflect::reflect_hash` as a `TokenStream`.
///
/// If `Hash` was not registered, returns `None`.
pub fn get_hash_impl(&self, bevy_reflect_path: &Path) -> Option<proc_macro2::TokenStream> {
match &self.hash {
&TraitImpl::Implemented(span) => Some(quote_spanned! {span=>
fn reflect_hash(&self) -> #FQOption<u64> {
use ::core::hash::{Hash, Hasher};
let mut hasher = #bevy_reflect_path::utility::reflect_hasher();
Hash::hash(&#FQAny::type_id(self), &mut hasher);
Hash::hash(self, &mut hasher);
#FQOption::Some(Hasher::finish(&hasher))
}
}),
&TraitImpl::Custom(ref impl_fn, span) => Some(quote_spanned! {span=>
fn reflect_hash(&self) -> #FQOption<u64> {
#FQOption::Some(#impl_fn(self))
}
}),
TraitImpl::NotImplemented => None,
}
}
/// Returns the implementation of `PartialReflect::reflect_partial_eq` as a `TokenStream`.
///
/// If `PartialEq` was not registered, returns `None`.
pub fn get_partial_eq_impl(
&self,
bevy_reflect_path: &Path,
) -> Option<proc_macro2::TokenStream> {
match &self.partial_eq {
&TraitImpl::Implemented(span) => Some(quote_spanned! {span=>
fn reflect_partial_eq(&self, value: &dyn #bevy_reflect_path::PartialReflect) -> #FQOption<bool> {
let value = <dyn #bevy_reflect_path::PartialReflect>::try_downcast_ref::<Self>(value);
if let #FQOption::Some(value) = value {
#FQOption::Some(::core::cmp::PartialEq::eq(self, value))
} else {
#FQOption::Some(false)
}
}
}),
&TraitImpl::Custom(ref impl_fn, span) => Some(quote_spanned! {span=>
fn reflect_partial_eq(&self, value: &dyn #bevy_reflect_path::PartialReflect) -> #FQOption<bool> {
#FQOption::Some(#impl_fn(self, value))
}
}),
TraitImpl::NotImplemented => None,
}
}
/// Returns the implementation of `PartialReflect::debug` as a `TokenStream`.
///
/// If `Debug` was not registered, returns `None`.
pub fn get_debug_impl(&self) -> Option<proc_macro2::TokenStream> {
match &self.debug {
&TraitImpl::Implemented(span) => Some(quote_spanned! {span=>
fn debug(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::fmt::Debug::fmt(self, f)
}
}),
&TraitImpl::Custom(ref impl_fn, span) => Some(quote_spanned! {span=>
fn debug(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
#impl_fn(self, f)
}
}),
TraitImpl::NotImplemented => None,
}
}
pub fn get_clone_impl(&self, bevy_reflect_path: &Path) -> Option<proc_macro2::TokenStream> {
match &self.clone {
&TraitImpl::Implemented(span) => Some(quote_spanned! {span=>
#[inline]
fn reflect_clone(&self) -> #FQResult<#bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #bevy_reflect_path::Reflect>, #bevy_reflect_path::ReflectCloneError> {
#FQResult::Ok(#bevy_reflect_path::__macro_exports::alloc_utils::Box::new(#FQClone::clone(self)))
}
}),
&TraitImpl::Custom(ref impl_fn, span) => Some(quote_spanned! {span=>
#[inline]
fn reflect_clone(&self) -> #FQResult<#bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #bevy_reflect_path::Reflect>, #bevy_reflect_path::ReflectCloneError> {
#FQResult::Ok(#bevy_reflect_path::__macro_exports::alloc_utils::Box::new(#impl_fn(self)))
}
}),
TraitImpl::NotImplemented => None,
}
}
pub fn custom_attributes(&self) -> &CustomAttributes {
&self.custom_attributes
}
/// The custom where configuration found within `#[reflect(...)]` attributes on this type.
pub fn custom_where(&self) -> Option<&WhereClause> {
self.custom_where.as_ref()
}
/// Returns true if the `no_field_bounds` attribute was found on this type.
pub fn no_field_bounds(&self) -> bool {
self.no_field_bounds
}
/// Returns true if the `no_auto_register` attribute was found on this type.
#[cfg(feature = "auto_register")]
pub fn no_auto_register(&self) -> bool {
self.no_auto_register
}
/// Returns true if the `opaque` attribute was found on this type.
pub fn is_opaque(&self) -> bool {
self.is_opaque
}
}
/// Adds an identifier to a vector of identifiers if it is not already present.
///
/// Returns an error if the identifier already exists in the list.
fn add_unique_ident(idents: &mut Vec<Ident>, ident: Ident) -> Result<(), syn::Error> {
let ident_name = ident.to_string();
if idents.iter().any(|i| i == ident_name.as_str()) {
return Err(syn::Error::new(ident.span(), CONFLICTING_TYPE_DATA_MESSAGE));
}
idents.push(ident);
Ok(())
}
/// Extract a boolean value from an expression.
///
/// The mapper exists so that the caller can conditionally choose to use the given
/// value or supply their own.
fn extract_bool(
value: &Expr,
mut mapper: impl FnMut(&LitBool) -> LitBool,
) -> Result<LitBool, syn::Error> {
match value {
Expr::Lit(syn::ExprLit {
lit: syn::Lit::Bool(lit),
..
}) => Ok(mapper(lit)),
_ => Err(syn::Error::new(value.span(), "Expected a boolean value")),
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/custom_attributes.rs | crates/bevy_reflect/derive/src/custom_attributes.rs | use proc_macro2::TokenStream;
use quote::quote;
use syn::{parse::ParseStream, Expr, Path, Token};
#[derive(Default, Clone)]
pub(crate) struct CustomAttributes {
attributes: Vec<Expr>,
}
impl CustomAttributes {
/// Generates a `TokenStream` for `CustomAttributes` construction.
pub fn to_tokens(&self, bevy_reflect_path: &Path) -> TokenStream {
let attributes = self.attributes.iter().map(|value| {
quote! {
.with_attribute(#value)
}
});
quote! {
#bevy_reflect_path::attributes::CustomAttributes::default()
#(#attributes)*
}
}
/// Inserts a custom attribute into the list.
pub fn push(&mut self, value: Expr) -> syn::Result<()> {
self.attributes.push(value);
Ok(())
}
/// Is the collection empty?
pub fn is_empty(&self) -> bool {
self.attributes.is_empty()
}
/// Parse `@` (custom attribute) attribute.
///
/// Examples:
/// - `#[reflect(@Foo))]`
/// - `#[reflect(@Bar::baz("qux"))]`
/// - `#[reflect(@0..256u8)]`
pub fn parse_custom_attribute(&mut self, input: ParseStream) -> syn::Result<()> {
input.parse::<Token![@]>()?;
self.push(input.parse()?)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/impls/tuple_structs.rs | crates/bevy_reflect/derive/src/impls/tuple_structs.rs | use crate::{
impls::{common_partial_reflect_methods, impl_full_reflect, impl_type_path, impl_typed},
struct_utility::FieldAccessors,
ReflectStruct,
};
use bevy_macro_utils::fq_std::{FQDefault, FQOption, FQResult};
use quote::{quote, ToTokens};
/// Implements `TupleStruct`, `GetTypeRegistration`, and `Reflect` for the given derive data.
pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> proc_macro2::TokenStream {
let fqoption = FQOption.into_token_stream();
let bevy_reflect_path = reflect_struct.meta().bevy_reflect_path();
let struct_path = reflect_struct.meta().type_path();
let FieldAccessors {
fields_ref,
fields_mut,
field_indices,
field_count,
..
} = FieldAccessors::new(reflect_struct);
let where_clause_options = reflect_struct.where_clause_options();
let get_type_registration_impl = reflect_struct.get_type_registration(&where_clause_options);
let typed_impl = impl_typed(&where_clause_options, reflect_struct.to_info_tokens(true));
let type_path_impl = impl_type_path(reflect_struct.meta());
let full_reflect_impl = impl_full_reflect(&where_clause_options);
let common_methods = common_partial_reflect_methods(
reflect_struct.meta(),
|| Some(quote!(#bevy_reflect_path::tuple_struct_partial_eq)),
|| None,
);
let clone_fn = reflect_struct.get_clone_impl();
#[cfg(not(feature = "functions"))]
let function_impls = None::<proc_macro2::TokenStream>;
#[cfg(feature = "functions")]
let function_impls = crate::impls::impl_function_traits(&where_clause_options);
let (impl_generics, ty_generics, where_clause) = reflect_struct
.meta()
.type_path()
.generics()
.split_for_impl();
#[cfg(not(feature = "auto_register"))]
let auto_register = None::<proc_macro2::TokenStream>;
#[cfg(feature = "auto_register")]
let auto_register = crate::impls::reflect_auto_registration(reflect_struct.meta());
let where_reflect_clause = where_clause_options.extend_where_clause(where_clause);
quote! {
#get_type_registration_impl
#typed_impl
#type_path_impl
#full_reflect_impl
#function_impls
#auto_register
impl #impl_generics #bevy_reflect_path::TupleStruct for #struct_path #ty_generics #where_reflect_clause {
fn field(&self, index: usize) -> #FQOption<&dyn #bevy_reflect_path::PartialReflect> {
match index {
#(#field_indices => #fqoption::Some(#fields_ref),)*
_ => #FQOption::None,
}
}
fn field_mut(&mut self, index: usize) -> #FQOption<&mut dyn #bevy_reflect_path::PartialReflect> {
match index {
#(#field_indices => #fqoption::Some(#fields_mut),)*
_ => #FQOption::None,
}
}
#[inline]
fn field_len(&self) -> usize {
#field_count
}
#[inline]
fn iter_fields(&self) -> #bevy_reflect_path::TupleStructFieldIter {
#bevy_reflect_path::TupleStructFieldIter::new(self)
}
fn to_dynamic_tuple_struct(&self) -> #bevy_reflect_path::DynamicTupleStruct {
let mut dynamic: #bevy_reflect_path::DynamicTupleStruct = #FQDefault::default();
dynamic.set_represented_type(#bevy_reflect_path::PartialReflect::get_represented_type_info(self));
#(dynamic.insert_boxed(#bevy_reflect_path::PartialReflect::to_dynamic(#fields_ref));)*
dynamic
}
}
impl #impl_generics #bevy_reflect_path::PartialReflect for #struct_path #ty_generics #where_reflect_clause {
#[inline]
fn get_represented_type_info(&self) -> #FQOption<&'static #bevy_reflect_path::TypeInfo> {
#FQOption::Some(<Self as #bevy_reflect_path::Typed>::type_info())
}
#[inline]
fn try_apply(
&mut self,
value: &dyn #bevy_reflect_path::PartialReflect
) -> #FQResult<(), #bevy_reflect_path::ApplyError> {
if let #bevy_reflect_path::ReflectRef::TupleStruct(struct_value) =
#bevy_reflect_path::PartialReflect::reflect_ref(value) {
for (i, value) in ::core::iter::Iterator::enumerate(#bevy_reflect_path::TupleStruct::iter_fields(struct_value)) {
if let #FQOption::Some(v) = #bevy_reflect_path::TupleStruct::field_mut(self, i) {
#bevy_reflect_path::PartialReflect::try_apply(v, value)?;
}
}
} else {
return #FQResult::Err(
#bevy_reflect_path::ApplyError::MismatchedKinds {
from_kind: #bevy_reflect_path::PartialReflect::reflect_kind(value),
to_kind: #bevy_reflect_path::ReflectKind::TupleStruct,
}
);
}
#FQResult::Ok(())
}
#[inline]
fn reflect_kind(&self) -> #bevy_reflect_path::ReflectKind {
#bevy_reflect_path::ReflectKind::TupleStruct
}
#[inline]
fn reflect_ref(&self) -> #bevy_reflect_path::ReflectRef {
#bevy_reflect_path::ReflectRef::TupleStruct(self)
}
#[inline]
fn reflect_mut(&mut self) -> #bevy_reflect_path::ReflectMut {
#bevy_reflect_path::ReflectMut::TupleStruct(self)
}
#[inline]
fn reflect_owned(self: #bevy_reflect_path::__macro_exports::alloc_utils::Box<Self>) -> #bevy_reflect_path::ReflectOwned {
#bevy_reflect_path::ReflectOwned::TupleStruct(self)
}
#common_methods
#clone_fn
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/impls/structs.rs | crates/bevy_reflect/derive/src/impls/structs.rs | use crate::{
impls::{common_partial_reflect_methods, impl_full_reflect, impl_type_path, impl_typed},
struct_utility::FieldAccessors,
ReflectStruct,
};
use bevy_macro_utils::fq_std::{FQDefault, FQOption, FQResult};
use quote::{quote, ToTokens};
/// Implements `Struct`, `GetTypeRegistration`, and `Reflect` for the given derive data.
pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> proc_macro2::TokenStream {
let fqoption = FQOption.into_token_stream();
let bevy_reflect_path = reflect_struct.meta().bevy_reflect_path();
let struct_path = reflect_struct.meta().type_path();
let field_names = reflect_struct
.active_fields()
.map(|field| {
field
.data
.ident
.as_ref()
.map(ToString::to_string)
.unwrap_or_else(|| field.declaration_index.to_string())
})
.collect::<Vec<String>>();
let FieldAccessors {
fields_ref,
fields_mut,
field_indices,
field_count,
..
} = FieldAccessors::new(reflect_struct);
let where_clause_options = reflect_struct.where_clause_options();
let typed_impl = impl_typed(&where_clause_options, reflect_struct.to_info_tokens(false));
let type_path_impl = impl_type_path(reflect_struct.meta());
let full_reflect_impl = impl_full_reflect(&where_clause_options);
let common_methods = common_partial_reflect_methods(
reflect_struct.meta(),
|| Some(quote!(#bevy_reflect_path::struct_partial_eq)),
|| None,
);
let clone_fn = reflect_struct.get_clone_impl();
#[cfg(not(feature = "functions"))]
let function_impls = None::<proc_macro2::TokenStream>;
#[cfg(feature = "functions")]
let function_impls = crate::impls::impl_function_traits(&where_clause_options);
let get_type_registration_impl = reflect_struct.get_type_registration(&where_clause_options);
let (impl_generics, ty_generics, where_clause) = reflect_struct
.meta()
.type_path()
.generics()
.split_for_impl();
#[cfg(not(feature = "auto_register"))]
let auto_register = None::<proc_macro2::TokenStream>;
#[cfg(feature = "auto_register")]
let auto_register = crate::impls::reflect_auto_registration(reflect_struct.meta());
let where_reflect_clause = where_clause_options.extend_where_clause(where_clause);
quote! {
#get_type_registration_impl
#typed_impl
#type_path_impl
#full_reflect_impl
#function_impls
#auto_register
impl #impl_generics #bevy_reflect_path::Struct for #struct_path #ty_generics #where_reflect_clause {
fn field(&self, name: &str) -> #FQOption<&dyn #bevy_reflect_path::PartialReflect> {
match name {
#(#field_names => #fqoption::Some(#fields_ref),)*
_ => #FQOption::None,
}
}
fn field_mut(&mut self, name: &str) -> #FQOption<&mut dyn #bevy_reflect_path::PartialReflect> {
match name {
#(#field_names => #fqoption::Some(#fields_mut),)*
_ => #FQOption::None,
}
}
fn field_at(&self, index: usize) -> #FQOption<&dyn #bevy_reflect_path::PartialReflect> {
match index {
#(#field_indices => #fqoption::Some(#fields_ref),)*
_ => #FQOption::None,
}
}
fn field_at_mut(&mut self, index: usize) -> #FQOption<&mut dyn #bevy_reflect_path::PartialReflect> {
match index {
#(#field_indices => #fqoption::Some(#fields_mut),)*
_ => #FQOption::None,
}
}
fn name_at(&self, index: usize) -> #FQOption<&str> {
match index {
#(#field_indices => #fqoption::Some(#field_names),)*
_ => #FQOption::None,
}
}
fn field_len(&self) -> usize {
#field_count
}
fn iter_fields(&self) -> #bevy_reflect_path::FieldIter {
#bevy_reflect_path::FieldIter::new(self)
}
fn to_dynamic_struct(&self) -> #bevy_reflect_path::DynamicStruct {
let mut dynamic: #bevy_reflect_path::DynamicStruct = #FQDefault::default();
dynamic.set_represented_type(#bevy_reflect_path::PartialReflect::get_represented_type_info(self));
#(dynamic.insert_boxed(#field_names, #bevy_reflect_path::PartialReflect::to_dynamic(#fields_ref));)*
dynamic
}
}
impl #impl_generics #bevy_reflect_path::PartialReflect for #struct_path #ty_generics #where_reflect_clause {
#[inline]
fn get_represented_type_info(&self) -> #FQOption<&'static #bevy_reflect_path::TypeInfo> {
#FQOption::Some(<Self as #bevy_reflect_path::Typed>::type_info())
}
#[inline]
fn try_apply(
&mut self,
value: &dyn #bevy_reflect_path::PartialReflect
) -> #FQResult<(), #bevy_reflect_path::ApplyError> {
if let #bevy_reflect_path::ReflectRef::Struct(struct_value)
= #bevy_reflect_path::PartialReflect::reflect_ref(value) {
for (i, value) in ::core::iter::Iterator::enumerate(#bevy_reflect_path::Struct::iter_fields(struct_value)) {
let name = #bevy_reflect_path::Struct::name_at(struct_value, i).unwrap();
if let #FQOption::Some(v) = #bevy_reflect_path::Struct::field_mut(self, name) {
#bevy_reflect_path::PartialReflect::try_apply(v, value)?;
}
}
} else {
return #FQResult::Err(
#bevy_reflect_path::ApplyError::MismatchedKinds {
from_kind: #bevy_reflect_path::PartialReflect::reflect_kind(value),
to_kind: #bevy_reflect_path::ReflectKind::Struct
}
);
}
#FQResult::Ok(())
}
#[inline]
fn reflect_kind(&self) -> #bevy_reflect_path::ReflectKind {
#bevy_reflect_path::ReflectKind::Struct
}
#[inline]
fn reflect_ref(&self) -> #bevy_reflect_path::ReflectRef {
#bevy_reflect_path::ReflectRef::Struct(self)
}
#[inline]
fn reflect_mut(&mut self) -> #bevy_reflect_path::ReflectMut {
#bevy_reflect_path::ReflectMut::Struct(self)
}
#[inline]
fn reflect_owned(self: #bevy_reflect_path::__macro_exports::alloc_utils::Box<Self>) -> #bevy_reflect_path::ReflectOwned {
#bevy_reflect_path::ReflectOwned::Struct(self)
}
#common_methods
#clone_fn
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/impls/enums.rs | crates/bevy_reflect/derive/src/impls/enums.rs | use crate::{
derive_data::{EnumVariantFields, ReflectEnum, StructField},
enum_utility::{EnumVariantOutputData, TryApplyVariantBuilder, VariantBuilder},
impls::{common_partial_reflect_methods, impl_full_reflect, impl_type_path, impl_typed},
};
use bevy_macro_utils::fq_std::{FQOption, FQResult};
use proc_macro2::{Ident, Span};
use quote::quote;
use syn::{Fields, Path};
pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> proc_macro2::TokenStream {
let bevy_reflect_path = reflect_enum.meta().bevy_reflect_path();
let enum_path = reflect_enum.meta().type_path();
let is_remote = reflect_enum.meta().is_remote_wrapper();
// For `match self` expressions where self is a reference
let match_this = if is_remote {
quote!(&self.0)
} else {
quote!(self)
};
// For `match self` expressions where self is a mutable reference
let match_this_mut = if is_remote {
quote!(&mut self.0)
} else {
quote!(self)
};
// For `*self` assignments
let deref_this = if is_remote {
quote!(self.0)
} else {
quote!(*self)
};
let ref_name = Ident::new("__name_param", Span::call_site());
let ref_index = Ident::new("__index_param", Span::call_site());
let ref_value = Ident::new("__value_param", Span::call_site());
let EnumImpls {
enum_field,
enum_field_mut,
enum_field_at,
enum_field_at_mut,
enum_index_of,
enum_name_at,
enum_field_len,
enum_variant_name,
enum_variant_index,
enum_variant_type,
} = generate_impls(reflect_enum, &ref_index, &ref_name);
let EnumVariantOutputData {
variant_names,
variant_constructors,
..
} = TryApplyVariantBuilder::new(reflect_enum).build(&ref_value);
let where_clause_options = reflect_enum.where_clause_options();
let typed_impl = impl_typed(&where_clause_options, reflect_enum.to_info_tokens());
let type_path_impl = impl_type_path(reflect_enum.meta());
let full_reflect_impl = impl_full_reflect(&where_clause_options);
let common_methods = common_partial_reflect_methods(
reflect_enum.meta(),
|| Some(quote!(#bevy_reflect_path::enum_partial_eq)),
|| Some(quote!(#bevy_reflect_path::enum_hash)),
);
let clone_fn = reflect_enum.get_clone_impl();
#[cfg(not(feature = "functions"))]
let function_impls = None::<proc_macro2::TokenStream>;
#[cfg(feature = "functions")]
let function_impls = crate::impls::impl_function_traits(&where_clause_options);
let get_type_registration_impl = reflect_enum.get_type_registration(&where_clause_options);
let (impl_generics, ty_generics, where_clause) =
reflect_enum.meta().type_path().generics().split_for_impl();
#[cfg(not(feature = "auto_register"))]
let auto_register = None::<proc_macro2::TokenStream>;
#[cfg(feature = "auto_register")]
let auto_register = crate::impls::reflect_auto_registration(reflect_enum.meta());
let where_reflect_clause = where_clause_options.extend_where_clause(where_clause);
quote! {
#get_type_registration_impl
#typed_impl
#type_path_impl
#full_reflect_impl
#function_impls
#auto_register
impl #impl_generics #bevy_reflect_path::Enum for #enum_path #ty_generics #where_reflect_clause {
fn field(&self, #ref_name: &str) -> #FQOption<&dyn #bevy_reflect_path::PartialReflect> {
match #match_this {
#(#enum_field,)*
_ => #FQOption::None,
}
}
fn field_at(&self, #ref_index: usize) -> #FQOption<&dyn #bevy_reflect_path::PartialReflect> {
match #match_this {
#(#enum_field_at,)*
_ => #FQOption::None,
}
}
fn field_mut(&mut self, #ref_name: &str) -> #FQOption<&mut dyn #bevy_reflect_path::PartialReflect> {
match #match_this_mut {
#(#enum_field_mut,)*
_ => #FQOption::None,
}
}
fn field_at_mut(&mut self, #ref_index: usize) -> #FQOption<&mut dyn #bevy_reflect_path::PartialReflect> {
match #match_this_mut {
#(#enum_field_at_mut,)*
_ => #FQOption::None,
}
}
fn index_of(&self, #ref_name: &str) -> #FQOption<usize> {
match #match_this {
#(#enum_index_of,)*
_ => #FQOption::None,
}
}
fn name_at(&self, #ref_index: usize) -> #FQOption<&str> {
match #match_this {
#(#enum_name_at,)*
_ => #FQOption::None,
}
}
fn iter_fields(&self) -> #bevy_reflect_path::VariantFieldIter {
#bevy_reflect_path::VariantFieldIter::new(self)
}
#[inline]
fn field_len(&self) -> usize {
match #match_this {
#(#enum_field_len,)*
_ => 0,
}
}
#[inline]
fn variant_name(&self) -> &str {
match #match_this {
#(#enum_variant_name,)*
_ => unreachable!(),
}
}
#[inline]
fn variant_index(&self) -> usize {
match #match_this {
#(#enum_variant_index,)*
_ => unreachable!(),
}
}
#[inline]
fn variant_type(&self) -> #bevy_reflect_path::VariantType {
match #match_this {
#(#enum_variant_type,)*
_ => unreachable!(),
}
}
fn to_dynamic_enum(&self) -> #bevy_reflect_path::DynamicEnum {
#bevy_reflect_path::DynamicEnum::from_ref::<Self>(self)
}
}
impl #impl_generics #bevy_reflect_path::PartialReflect for #enum_path #ty_generics #where_reflect_clause {
#[inline]
fn get_represented_type_info(&self) -> #FQOption<&'static #bevy_reflect_path::TypeInfo> {
#FQOption::Some(<Self as #bevy_reflect_path::Typed>::type_info())
}
#[inline]
fn try_apply(
&mut self,
#ref_value: &dyn #bevy_reflect_path::PartialReflect
) -> #FQResult<(), #bevy_reflect_path::ApplyError> {
if let #bevy_reflect_path::ReflectRef::Enum(#ref_value) =
#bevy_reflect_path::PartialReflect::reflect_ref(#ref_value) {
if #bevy_reflect_path::Enum::variant_name(self) == #bevy_reflect_path::Enum::variant_name(#ref_value) {
// Same variant -> just update fields
match #bevy_reflect_path::Enum::variant_type(#ref_value) {
#bevy_reflect_path::VariantType::Struct => {
for field in #bevy_reflect_path::Enum::iter_fields(#ref_value) {
let name = field.name().unwrap();
if let #FQOption::Some(v) = #bevy_reflect_path::Enum::field_mut(self, name) {
#bevy_reflect_path::PartialReflect::try_apply(v, field.value())?;
}
}
}
#bevy_reflect_path::VariantType::Tuple => {
for (index, field) in ::core::iter::Iterator::enumerate(#bevy_reflect_path::Enum::iter_fields(#ref_value)) {
if let #FQOption::Some(v) = #bevy_reflect_path::Enum::field_at_mut(self, index) {
#bevy_reflect_path::PartialReflect::try_apply(v, field.value())?;
}
}
}
_ => {}
}
} else {
// New variant -> perform a switch
match #bevy_reflect_path::Enum::variant_name(#ref_value) {
#(#variant_names => {
#deref_this = #variant_constructors
})*
name => {
return #FQResult::Err(
#bevy_reflect_path::ApplyError::UnknownVariant {
enum_name: ::core::convert::Into::into(#bevy_reflect_path::DynamicTypePath::reflect_type_path(self)),
variant_name: ::core::convert::Into::into(name),
}
);
}
}
}
} else {
return #FQResult::Err(
#bevy_reflect_path::ApplyError::MismatchedKinds {
from_kind: #bevy_reflect_path::PartialReflect::reflect_kind(#ref_value),
to_kind: #bevy_reflect_path::ReflectKind::Enum,
}
);
}
#FQResult::Ok(())
}
fn reflect_kind(&self) -> #bevy_reflect_path::ReflectKind {
#bevy_reflect_path::ReflectKind::Enum
}
fn reflect_ref(&self) -> #bevy_reflect_path::ReflectRef {
#bevy_reflect_path::ReflectRef::Enum(self)
}
fn reflect_mut(&mut self) -> #bevy_reflect_path::ReflectMut {
#bevy_reflect_path::ReflectMut::Enum(self)
}
fn reflect_owned(self: #bevy_reflect_path::__macro_exports::alloc_utils::Box<Self>) -> #bevy_reflect_path::ReflectOwned {
#bevy_reflect_path::ReflectOwned::Enum(self)
}
#common_methods
#clone_fn
}
}
}
struct EnumImpls {
enum_field: Vec<proc_macro2::TokenStream>,
enum_field_mut: Vec<proc_macro2::TokenStream>,
enum_field_at: Vec<proc_macro2::TokenStream>,
enum_field_at_mut: Vec<proc_macro2::TokenStream>,
enum_index_of: Vec<proc_macro2::TokenStream>,
enum_name_at: Vec<proc_macro2::TokenStream>,
enum_field_len: Vec<proc_macro2::TokenStream>,
enum_variant_name: Vec<proc_macro2::TokenStream>,
enum_variant_index: Vec<proc_macro2::TokenStream>,
enum_variant_type: Vec<proc_macro2::TokenStream>,
}
fn generate_impls(reflect_enum: &ReflectEnum, ref_index: &Ident, ref_name: &Ident) -> EnumImpls {
let bevy_reflect_path = reflect_enum.meta().bevy_reflect_path();
let mut enum_field = Vec::new();
let mut enum_field_mut = Vec::new();
let mut enum_field_at = Vec::new();
let mut enum_field_at_mut = Vec::new();
let mut enum_index_of = Vec::new();
let mut enum_name_at = Vec::new();
let mut enum_field_len = Vec::new();
let mut enum_variant_name = Vec::new();
let mut enum_variant_index = Vec::new();
let mut enum_variant_type = Vec::new();
for (variant_index, variant) in reflect_enum.variants().iter().enumerate() {
let ident = &variant.data.ident;
let name = ident.to_string();
let unit = reflect_enum.get_unit(ident);
let variant_type_ident = match variant.data.fields {
Fields::Unit => Ident::new("Unit", Span::call_site()),
Fields::Unnamed(..) => Ident::new("Tuple", Span::call_site()),
Fields::Named(..) => Ident::new("Struct", Span::call_site()),
};
enum_variant_name.push(quote! {
#unit{..} => #name
});
enum_variant_index.push(quote! {
#unit{..} => #variant_index
});
enum_variant_type.push(quote! {
#unit{..} => #bevy_reflect_path::VariantType::#variant_type_ident
});
fn process_fields(
fields: &[StructField],
mut f: impl FnMut(&StructField) + Sized,
) -> usize {
let mut field_len = 0;
for field in fields.iter() {
if field.attrs.ignore.is_ignored() {
// Ignored field
continue;
};
f(field);
field_len += 1;
}
field_len
}
/// Process the field value to account for remote types.
///
/// If the field is a remote type, then the value will be transmuted accordingly.
fn process_field_value(
ident: &Ident,
field: &StructField,
is_mutable: bool,
bevy_reflect_path: &Path,
) -> proc_macro2::TokenStream {
let method = if is_mutable {
quote!(as_wrapper_mut)
} else {
quote!(as_wrapper)
};
field
.attrs
.remote
.as_ref()
.map(|ty| quote!(<#ty as #bevy_reflect_path::ReflectRemote>::#method(#ident)))
.unwrap_or_else(|| quote!(#ident))
}
match &variant.fields {
EnumVariantFields::Unit => {
let field_len = process_fields(&[], |_| {});
enum_field_len.push(quote! {
#unit{..} => #field_len
});
}
EnumVariantFields::Unnamed(fields) => {
let field_len = process_fields(fields, |field: &StructField| {
let reflection_index = field
.reflection_index
.expect("reflection index should exist for active field");
let declare_field = syn::Index::from(field.declaration_index);
let __value = Ident::new("__value", Span::call_site());
let value_ref = process_field_value(&__value, field, false, bevy_reflect_path);
let value_mut = process_field_value(&__value, field, true, bevy_reflect_path);
enum_field_at.push(quote! {
#unit { #declare_field : #__value, .. } if #ref_index == #reflection_index => #FQOption::Some(#value_ref)
});
enum_field_at_mut.push(quote! {
#unit { #declare_field : #__value, .. } if #ref_index == #reflection_index => #FQOption::Some(#value_mut)
});
});
enum_field_len.push(quote! {
#unit{..} => #field_len
});
}
EnumVariantFields::Named(fields) => {
let field_len = process_fields(fields, |field: &StructField| {
let field_ident = field.data.ident.as_ref().unwrap();
let field_name = field_ident.to_string();
let reflection_index = field
.reflection_index
.expect("reflection index should exist for active field");
let __value = Ident::new("__value", Span::call_site());
let value_ref = process_field_value(&__value, field, false, bevy_reflect_path);
let value_mut = process_field_value(&__value, field, true, bevy_reflect_path);
enum_field.push(quote! {
#unit{ #field_ident: #__value, .. } if #ref_name == #field_name => #FQOption::Some(#value_ref)
});
enum_field_mut.push(quote! {
#unit{ #field_ident: #__value, .. } if #ref_name == #field_name => #FQOption::Some(#value_mut)
});
enum_field_at.push(quote! {
#unit{ #field_ident: #__value, .. } if #ref_index == #reflection_index => #FQOption::Some(#value_ref)
});
enum_field_at_mut.push(quote! {
#unit{ #field_ident: #__value, .. } if #ref_index == #reflection_index => #FQOption::Some(#value_mut)
});
enum_index_of.push(quote! {
#unit{ .. } if #ref_name == #field_name => #FQOption::Some(#reflection_index)
});
enum_name_at.push(quote! {
#unit{ .. } if #ref_index == #reflection_index => #FQOption::Some(#field_name)
});
});
enum_field_len.push(quote! {
#unit{..} => #field_len
});
}
};
}
EnumImpls {
enum_field,
enum_field_mut,
enum_field_at,
enum_field_at_mut,
enum_index_of,
enum_name_at,
enum_field_len,
enum_variant_name,
enum_variant_index,
enum_variant_type,
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/impls/mod.rs | crates/bevy_reflect/derive/src/impls/mod.rs | mod assertions;
mod common;
mod enums;
#[cfg(feature = "functions")]
mod func;
mod opaque;
mod structs;
mod tuple_structs;
mod typed;
pub(crate) use assertions::impl_assertions;
#[cfg(feature = "auto_register")]
pub(crate) use common::reflect_auto_registration;
pub(crate) use common::{common_partial_reflect_methods, impl_full_reflect};
pub(crate) use enums::impl_enum;
#[cfg(feature = "functions")]
pub(crate) use func::impl_function_traits;
pub(crate) use opaque::impl_opaque;
pub(crate) use structs::impl_struct;
pub(crate) use tuple_structs::impl_tuple_struct;
pub(crate) use typed::{impl_type_path, impl_typed};
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/impls/typed.rs | crates/bevy_reflect/derive/src/impls/typed.rs | use crate::{
derive_data::{ReflectMeta, ReflectTypePath},
string_expr::StringExpr,
where_clause_options::WhereClauseOptions,
};
use bevy_macro_utils::fq_std::FQOption;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
/// Returns an expression for a `NonGenericTypeCell` or `GenericTypeCell` to generate `'static` references.
fn static_type_cell(
meta: &ReflectMeta,
property: TypedProperty,
generator: TokenStream,
) -> TokenStream {
let bevy_reflect_path = meta.bevy_reflect_path();
if meta.type_path().impl_is_generic() {
let cell_type = match property {
TypedProperty::TypePath => quote!(GenericTypePathCell),
TypedProperty::TypeInfo => quote!(GenericTypeInfoCell),
};
quote! {
static CELL: #bevy_reflect_path::utility::#cell_type = #bevy_reflect_path::utility::#cell_type::new();
CELL.get_or_insert::<Self, _>(|| {
#generator
})
}
} else {
let cell_type = match property {
TypedProperty::TypePath => unreachable!(
"Cannot have a non-generic type path cell. Use string literals and core::concat instead."
),
TypedProperty::TypeInfo => quote!(NonGenericTypeInfoCell),
};
quote! {
static CELL: #bevy_reflect_path::utility::#cell_type = #bevy_reflect_path::utility::#cell_type::new();
CELL.get_or_set(|| {
#generator
})
}
}
}
#[derive(Clone, Copy)]
pub(crate) enum TypedProperty {
TypeInfo,
TypePath,
}
pub(crate) fn impl_type_path(meta: &ReflectMeta) -> TokenStream {
let where_clause_options = WhereClauseOptions::new(meta);
if !meta.attrs().type_path_attrs().should_auto_derive() {
return TokenStream::new();
}
let type_path = meta.type_path();
let bevy_reflect_path = meta.bevy_reflect_path();
let (long_type_path, short_type_path) = if type_path.impl_is_generic() {
let long_path_cell = static_type_cell(
meta,
TypedProperty::TypePath,
type_path.long_type_path(bevy_reflect_path).into_owned(),
);
let short_path_cell = static_type_cell(
meta,
TypedProperty::TypePath,
type_path.short_type_path(bevy_reflect_path).into_owned(),
);
(
long_path_cell.to_token_stream(),
short_path_cell.to_token_stream(),
)
} else {
(
type_path.long_type_path(bevy_reflect_path).into_borrowed(),
type_path.short_type_path(bevy_reflect_path).into_borrowed(),
)
};
let type_ident = wrap_in_option(type_path.type_ident().map(StringExpr::into_borrowed));
let module_path = wrap_in_option(type_path.module_path().map(StringExpr::into_borrowed));
let crate_name = wrap_in_option(type_path.crate_name().map(StringExpr::into_borrowed));
let primitive_assert = if let ReflectTypePath::Primitive(_) = type_path {
Some(quote! {
const _: () = {
mod private_scope {
// Compiles if it can be named when there are no imports.
type AssertIsPrimitive = #type_path;
}
};
})
} else {
None
};
let (impl_generics, ty_generics, where_clause) = type_path.generics().split_for_impl();
// Add Typed bound for each active field
let where_reflect_clause = where_clause_options.extend_where_clause(where_clause);
quote! {
#primitive_assert
impl #impl_generics #bevy_reflect_path::TypePath for #type_path #ty_generics #where_reflect_clause {
fn type_path() -> &'static str {
#long_type_path
}
fn short_type_path() -> &'static str {
#short_type_path
}
fn type_ident() -> Option<&'static str> {
#type_ident
}
fn crate_name() -> Option<&'static str> {
#crate_name
}
fn module_path() -> Option<&'static str> {
#module_path
}
}
}
}
pub(crate) fn impl_typed(
where_clause_options: &WhereClauseOptions,
type_info_generator: TokenStream,
) -> TokenStream {
let meta = where_clause_options.meta();
let type_path = meta.type_path();
let bevy_reflect_path = meta.bevy_reflect_path();
let type_info_cell = static_type_cell(meta, TypedProperty::TypeInfo, type_info_generator);
let (impl_generics, ty_generics, where_clause) = type_path.generics().split_for_impl();
let where_reflect_clause = where_clause_options.extend_where_clause(where_clause);
quote! {
impl #impl_generics #bevy_reflect_path::Typed for #type_path #ty_generics #where_reflect_clause {
#[inline]
fn type_info() -> &'static #bevy_reflect_path::TypeInfo {
#type_info_cell
}
}
}
}
/// Turns an `Option<TokenStream>` into a `TokenStream` for an `Option`.
fn wrap_in_option(tokens: Option<TokenStream>) -> TokenStream {
match tokens {
Some(tokens) => quote! {
#FQOption::Some(#tokens)
},
None => quote! {
#FQOption::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/derive/src/impls/common.rs | crates/bevy_reflect/derive/src/impls/common.rs | use bevy_macro_utils::fq_std::{FQAny, FQOption, FQResult};
use quote::quote;
use crate::{derive_data::ReflectMeta, where_clause_options::WhereClauseOptions};
pub fn impl_full_reflect(where_clause_options: &WhereClauseOptions) -> proc_macro2::TokenStream {
let meta = where_clause_options.meta();
let bevy_reflect_path = meta.bevy_reflect_path();
let type_path = meta.type_path();
let (impl_generics, ty_generics, where_clause) = type_path.generics().split_for_impl();
let where_reflect_clause = where_clause_options.extend_where_clause(where_clause);
let any_impls = if meta.is_remote_wrapper() {
quote! {
#[inline]
fn into_any(self: #bevy_reflect_path::__macro_exports::alloc_utils::Box<Self>) -> #bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #FQAny> {
#bevy_reflect_path::__macro_exports::alloc_utils::Box::new(self.0)
}
#[inline]
fn as_any(&self) -> &dyn #FQAny {
&self.0
}
#[inline]
fn as_any_mut(&mut self) -> &mut dyn #FQAny {
&mut self.0
}
}
} else {
quote! {
#[inline]
fn into_any(self: #bevy_reflect_path::__macro_exports::alloc_utils::Box<Self>) -> #bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #FQAny> {
self
}
#[inline]
fn as_any(&self) -> &dyn #FQAny {
self
}
#[inline]
fn as_any_mut(&mut self) -> &mut dyn #FQAny {
self
}
}
};
quote! {
impl #impl_generics #bevy_reflect_path::Reflect for #type_path #ty_generics #where_reflect_clause {
#any_impls
#[inline]
fn into_reflect(self: #bevy_reflect_path::__macro_exports::alloc_utils::Box<Self>) -> #bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #bevy_reflect_path::Reflect> {
self
}
#[inline]
fn as_reflect(&self) -> &dyn #bevy_reflect_path::Reflect {
self
}
#[inline]
fn as_reflect_mut(&mut self) -> &mut dyn #bevy_reflect_path::Reflect {
self
}
#[inline]
fn set(
&mut self,
value: #bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #bevy_reflect_path::Reflect>
) -> #FQResult<(), #bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #bevy_reflect_path::Reflect>> {
*self = <dyn #bevy_reflect_path::Reflect>::take(value)?;
#FQResult::Ok(())
}
}
}
}
pub fn common_partial_reflect_methods(
meta: &ReflectMeta,
default_partial_eq_delegate: impl FnOnce() -> Option<proc_macro2::TokenStream>,
default_hash_delegate: impl FnOnce() -> Option<proc_macro2::TokenStream>,
) -> proc_macro2::TokenStream {
let bevy_reflect_path = meta.bevy_reflect_path();
let debug_fn = meta.attrs().get_debug_impl();
let partial_eq_fn = meta
.attrs()
.get_partial_eq_impl(bevy_reflect_path)
.or_else(move || {
let default_delegate = default_partial_eq_delegate();
default_delegate.map(|func| {
quote! {
fn reflect_partial_eq(&self, value: &dyn #bevy_reflect_path::PartialReflect) -> #FQOption<bool> {
(#func)(self, value)
}
}
})
});
let hash_fn = meta
.attrs()
.get_hash_impl(bevy_reflect_path)
.or_else(move || {
let default_delegate = default_hash_delegate();
default_delegate.map(|func| {
quote! {
fn reflect_hash(&self) -> #FQOption<u64> {
(#func)(self)
}
}
})
});
quote! {
#[inline]
fn try_into_reflect(
self: #bevy_reflect_path::__macro_exports::alloc_utils::Box<Self>
) -> #FQResult<#bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #bevy_reflect_path::Reflect>, #bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #bevy_reflect_path::PartialReflect>> {
#FQResult::Ok(self)
}
#[inline]
fn try_as_reflect(&self) -> #FQOption<&dyn #bevy_reflect_path::Reflect> {
#FQOption::Some(self)
}
#[inline]
fn try_as_reflect_mut(&mut self) -> #FQOption<&mut dyn #bevy_reflect_path::Reflect> {
#FQOption::Some(self)
}
#[inline]
fn into_partial_reflect(self: #bevy_reflect_path::__macro_exports::alloc_utils::Box<Self>) -> #bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #bevy_reflect_path::PartialReflect> {
self
}
#[inline]
fn as_partial_reflect(&self) -> &dyn #bevy_reflect_path::PartialReflect {
self
}
#[inline]
fn as_partial_reflect_mut(&mut self) -> &mut dyn #bevy_reflect_path::PartialReflect {
self
}
#hash_fn
#partial_eq_fn
#debug_fn
}
}
#[cfg(feature = "auto_register")]
pub fn reflect_auto_registration(meta: &ReflectMeta) -> Option<proc_macro2::TokenStream> {
if meta.attrs().no_auto_register() {
return None;
}
let bevy_reflect_path = meta.bevy_reflect_path();
let type_path = meta.type_path();
if type_path.impl_is_generic() {
return None;
};
#[cfg(feature = "auto_register_static")]
{
use std::{
env, fs,
io::Write,
path::PathBuf,
sync::{LazyLock, Mutex},
};
// Skip unless env var is set, otherwise this might slow down rust-analyzer
if env::var("BEVY_REFLECT_AUTO_REGISTER_STATIC").is_err() {
return None;
}
// Names of registrations functions will be stored in this file.
// To allow writing to this file from multiple threads during compilation it is protected by mutex.
// This static is valid for the duration of compilation of one crate and we have one file per crate,
// so it is enough to protect compilation threads from overwriting each other.
// This file is reset on every crate recompilation.
//
// It might make sense to replace the mutex with File::lock when file_lock feature becomes stable.
static REGISTRATION_FNS_EXPORT: LazyLock<Mutex<fs::File>> = LazyLock::new(|| {
let path = PathBuf::from("target").join("bevy_reflect_type_registrations");
fs::DirBuilder::new()
.recursive(true)
.create(&path)
.unwrap_or_else(|_| panic!("Failed to create {path:?}"));
let file_path = path.join(env::var("CARGO_CRATE_NAME").unwrap());
let file = fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(&file_path)
.unwrap_or_else(|_| panic!("Failed to create {file_path:?}"));
Mutex::new(file)
});
let export_name = format!("_bevy_reflect_register_{}", uuid::Uuid::new_v4().as_u128());
{
let mut file = REGISTRATION_FNS_EXPORT.lock().unwrap();
writeln!(file, "{export_name}")
.unwrap_or_else(|_| panic!("Failed to write registration function {export_name}"));
// We must sync_data to ensure all content is written before releasing the lock.
file.sync_data().unwrap();
};
Some(quote! {
/// # Safety
/// This function must only be used by the `load_type_registrations` macro.
#[unsafe(export_name=#export_name)]
pub unsafe extern "Rust" fn bevy_register_type(registry: &mut #bevy_reflect_path::TypeRegistry) {
<#type_path as #bevy_reflect_path::__macro_exports::RegisterForReflection>::__register(registry);
}
})
}
#[cfg(all(
feature = "auto_register_inventory",
not(feature = "auto_register_static")
))]
{
Some(quote! {
#bevy_reflect_path::__macro_exports::auto_register::inventory::submit!{
#bevy_reflect_path::__macro_exports::auto_register::AutomaticReflectRegistrations(
<#type_path as #bevy_reflect_path::__macro_exports::auto_register::RegisterForReflection>::__register
)
}
})
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/impls/opaque.rs | crates/bevy_reflect/derive/src/impls/opaque.rs | use crate::{
impls::{common_partial_reflect_methods, impl_full_reflect, impl_type_path, impl_typed},
where_clause_options::WhereClauseOptions,
ReflectMeta,
};
use bevy_macro_utils::fq_std::{FQClone, FQOption, FQResult};
use quote::quote;
/// Implements `GetTypeRegistration` and `Reflect` for the given type data.
pub(crate) fn impl_opaque(meta: &ReflectMeta) -> proc_macro2::TokenStream {
let bevy_reflect_path = meta.bevy_reflect_path();
let type_path = meta.type_path();
#[cfg(feature = "reflect_documentation")]
let with_docs = {
let doc = quote::ToTokens::to_token_stream(meta.doc());
Some(quote!(.with_docs(#doc)))
};
#[cfg(not(feature = "reflect_documentation"))]
let with_docs: Option<proc_macro2::TokenStream> = None;
let where_clause_options = WhereClauseOptions::new(meta);
let typed_impl = impl_typed(
&where_clause_options,
quote! {
let info = #bevy_reflect_path::OpaqueInfo::new::<Self>() #with_docs;
#bevy_reflect_path::TypeInfo::Opaque(info)
},
);
let type_path_impl = impl_type_path(meta);
let full_reflect_impl = impl_full_reflect(&where_clause_options);
let common_methods = common_partial_reflect_methods(meta, || None, || None);
let clone_fn = meta.attrs().get_clone_impl(bevy_reflect_path);
let apply_impl = if let Some(remote_ty) = meta.remote_ty() {
let ty = remote_ty.type_path();
quote! {
if let #FQOption::Some(value) = <dyn #bevy_reflect_path::PartialReflect>::try_downcast_ref::<#ty>(value) {
*self = Self(#FQClone::clone(value));
return #FQResult::Ok(());
}
}
} else {
quote! {
if let #FQOption::Some(value) = <dyn #bevy_reflect_path::PartialReflect>::try_downcast_ref::<Self>(value) {
*self = #FQClone::clone(value);
return #FQResult::Ok(());
}
}
};
#[cfg(not(feature = "functions"))]
let function_impls = None::<proc_macro2::TokenStream>;
#[cfg(feature = "functions")]
let function_impls = crate::impls::impl_function_traits(&where_clause_options);
#[cfg(not(feature = "auto_register"))]
let auto_register = None::<proc_macro2::TokenStream>;
#[cfg(feature = "auto_register")]
let auto_register = crate::impls::reflect_auto_registration(meta);
let (impl_generics, ty_generics, where_clause) = type_path.generics().split_for_impl();
let where_reflect_clause = where_clause_options.extend_where_clause(where_clause);
let get_type_registration_impl = meta.get_type_registration(&where_clause_options);
quote! {
#get_type_registration_impl
#type_path_impl
#typed_impl
#full_reflect_impl
#function_impls
#auto_register
impl #impl_generics #bevy_reflect_path::PartialReflect for #type_path #ty_generics #where_reflect_clause {
#[inline]
fn get_represented_type_info(&self) -> #FQOption<&'static #bevy_reflect_path::TypeInfo> {
#FQOption::Some(<Self as #bevy_reflect_path::Typed>::type_info())
}
#[inline]
fn to_dynamic(&self) -> #bevy_reflect_path::__macro_exports::alloc_utils::Box<dyn #bevy_reflect_path::PartialReflect> {
#bevy_reflect_path::__macro_exports::alloc_utils::Box::new(#FQClone::clone(self))
}
#[inline]
fn try_apply(
&mut self,
value: &dyn #bevy_reflect_path::PartialReflect
) -> #FQResult<(), #bevy_reflect_path::ApplyError> {
#apply_impl
#FQResult::Err(
#bevy_reflect_path::ApplyError::MismatchedTypes {
from_type: ::core::convert::Into::into(#bevy_reflect_path::DynamicTypePath::reflect_type_path(value)),
to_type: ::core::convert::Into::into(<Self as #bevy_reflect_path::TypePath>::type_path()),
}
)
}
#[inline]
fn reflect_kind(&self) -> #bevy_reflect_path::ReflectKind {
#bevy_reflect_path::ReflectKind::Opaque
}
#[inline]
fn reflect_ref(&self) -> #bevy_reflect_path::ReflectRef {
#bevy_reflect_path::ReflectRef::Opaque(self)
}
#[inline]
fn reflect_mut(&mut self) -> #bevy_reflect_path::ReflectMut {
#bevy_reflect_path::ReflectMut::Opaque(self)
}
#[inline]
fn reflect_owned(self: #bevy_reflect_path::__macro_exports::alloc_utils::Box<Self>) -> #bevy_reflect_path::ReflectOwned {
#bevy_reflect_path::ReflectOwned::Opaque(self)
}
#common_methods
#clone_fn
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/impls/assertions.rs | crates/bevy_reflect/derive/src/impls/assertions.rs | use crate::{derive_data::ReflectDerive, remote::generate_remote_assertions};
use quote::quote;
/// Generates an anonymous block containing compile-time assertions.
pub(crate) fn impl_assertions(derive_data: &ReflectDerive) -> proc_macro2::TokenStream {
let mut output = quote!();
if let Some(assertions) = generate_remote_assertions(derive_data) {
output.extend(assertions);
}
output
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/impls/func/function_impls.rs | crates/bevy_reflect/derive/src/impls/func/function_impls.rs | use crate::{
impls::func::{
from_arg::impl_from_arg, get_ownership::impl_get_ownership, into_return::impl_into_return,
},
where_clause_options::WhereClauseOptions,
};
use quote::quote;
pub(crate) fn impl_function_traits(
where_clause_options: &WhereClauseOptions,
) -> proc_macro2::TokenStream {
let get_ownership = impl_get_ownership(where_clause_options);
let from_arg = impl_from_arg(where_clause_options);
let into_return = impl_into_return(where_clause_options);
quote! {
#get_ownership
#from_arg
#into_return
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/impls/func/from_arg.rs | crates/bevy_reflect/derive/src/impls/func/from_arg.rs | use crate::where_clause_options::WhereClauseOptions;
use bevy_macro_utils::fq_std::FQResult;
use quote::quote;
pub(crate) fn impl_from_arg(where_clause_options: &WhereClauseOptions) -> proc_macro2::TokenStream {
let meta = where_clause_options.meta();
let bevy_reflect = meta.bevy_reflect_path();
let type_path = meta.type_path();
let (impl_generics, ty_generics, where_clause) = type_path.generics().split_for_impl();
let where_reflect_clause = where_clause_options.extend_where_clause(where_clause);
quote! {
impl #impl_generics #bevy_reflect::func::args::FromArg for #type_path #ty_generics #where_reflect_clause {
type This<'from_arg> = #type_path #ty_generics;
fn from_arg(arg: #bevy_reflect::func::args::Arg) ->
#FQResult<Self::This<'_>, #bevy_reflect::func::args::ArgError>
{
arg.take_owned()
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/impls/func/get_ownership.rs | crates/bevy_reflect/derive/src/impls/func/get_ownership.rs | use crate::where_clause_options::WhereClauseOptions;
use quote::quote;
pub(crate) fn impl_get_ownership(
where_clause_options: &WhereClauseOptions,
) -> proc_macro2::TokenStream {
let meta = where_clause_options.meta();
let bevy_reflect = meta.bevy_reflect_path();
let type_path = meta.type_path();
let (impl_generics, ty_generics, where_clause) = type_path.generics().split_for_impl();
let where_reflect_clause = where_clause_options.extend_where_clause(where_clause);
quote! {
impl #impl_generics #bevy_reflect::func::args::GetOwnership for #type_path #ty_generics #where_reflect_clause {
fn ownership() -> #bevy_reflect::func::args::Ownership {
#bevy_reflect::func::args::Ownership::Owned
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/impls/func/mod.rs | crates/bevy_reflect/derive/src/impls/func/mod.rs | pub(crate) use function_impls::impl_function_traits;
mod from_arg;
mod function_impls;
mod get_ownership;
mod into_return;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/derive/src/impls/func/into_return.rs | crates/bevy_reflect/derive/src/impls/func/into_return.rs | use crate::where_clause_options::WhereClauseOptions;
use quote::quote;
pub(crate) fn impl_into_return(
where_clause_options: &WhereClauseOptions,
) -> proc_macro2::TokenStream {
let meta = where_clause_options.meta();
let bevy_reflect = meta.bevy_reflect_path();
let type_path = meta.type_path();
let (impl_generics, ty_generics, where_clause) = type_path.generics().split_for_impl();
let where_reflect_clause = where_clause_options.extend_where_clause(where_clause);
quote! {
impl #impl_generics #bevy_reflect::func::IntoReturn for #type_path #ty_generics #where_reflect_clause {
fn into_return<'into_return>(self) -> #bevy_reflect::func::Return<'into_return>
where Self: 'into_return
{
#bevy_reflect::func::Return::Owned(#bevy_reflect::__macro_exports::alloc_utils::Box::new(self))
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_camera_controller/src/lib.rs | crates/bevy_camera_controller/src/lib.rs | //! A home for first-party camera controllers for Bevy,
//! used for moving the camera around your scene.
//!
//! This crate serves two key purposes:
//!
//! 1. It provides functional camera controllers to help users quickly get started.
//! 2. It holds the camera controllers used by Bevy's own examples and tooling.
//!
//! While these camera controllers are customizable,
//! there is a limit to the customization options available.
//! If you find your project requires different behavior,
//! do not hesitate to copy-paste the camera controller code
//! into your own project and modify it as needed.
//!
//! Each of the provided controllers is gated behind a feature flag,
//! so you don't have to pay for unused camera controllers.
//! These features are all off by default; to enable them,
//! you need to specify the desired features in your Cargo.toml file.
//!
//! For example, to enable the `free_camera` camera controller,
//! you would add the following to your Cargo.toml:
//!
//! ```toml
//! [dependencies]
//! bevy = { version = "0.X", features = ["free_camera"] }
//! ```
//!
//! Once the correct feature is enabled,
//! add the camera controller plugin to your Bevy app.
//! If your camera is for debugging and development purposes,
//! consider adding a feature flag (e.g. `dev-mode`) or a run condition on
//! the systems in the plugin, which can check a configuration resource.
//!
//! For a full overview of the available camera controllers,
//! please check out the modules of this crate.
//! Each camera controller is stored in its own module,
//! and gated behind a feature flag of the same name.
#![warn(missing_docs)]
#[cfg(feature = "free_camera")]
pub mod free_camera;
#[cfg(feature = "pan_camera")]
pub mod pan_camera;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_camera_controller/src/free_camera.rs | crates/bevy_camera_controller/src/free_camera.rs | //! A camera controller that allows the user to move freely around the scene.
//!
//! Free cameras are helpful for exploring large scenes, level editors and for debugging.
//! They are rarely useful as-is for gameplay,
//! as they allow the user to move freely in all directions,
//! which can be disorienting, and they can clip through objects and terrain.
//!
//! You may have heard of a "fly camera" — a type of free camera designed for fluid "flying" movement and quickly surveying large areas.
//! By contrast, the default settings of this particular free camera are optimized for precise control.
//!
//! To use this controller, add [`FreeCameraPlugin`] to your app,
//! and attach the [`FreeCamera`] component to your camera entity.
//! The required [`FreeCameraState`] component will be added automatically.
//!
//! To configure the settings of this controller, modify the fields of the [`FreeCamera`] component.
use bevy_app::{App, Plugin, RunFixedMainLoop, RunFixedMainLoopSystems};
use bevy_camera::Camera;
use bevy_ecs::prelude::*;
use bevy_input::keyboard::KeyCode;
use bevy_input::mouse::{
AccumulatedMouseMotion, AccumulatedMouseScroll, MouseButton, MouseScrollUnit,
};
use bevy_input::ButtonInput;
use bevy_log::info;
use bevy_math::{EulerRot, Quat, StableInterpolate, Vec2, Vec3};
use bevy_time::{Real, Time};
use bevy_transform::prelude::Transform;
use bevy_window::{CursorGrabMode, CursorOptions, Window};
use core::{f32::consts::*, fmt};
/// A freecam-style camera controller plugin.
///
/// Use the [`FreeCamera`] struct to add and customize the controller for a camera entity.
/// The camera's dynamic state is managed by the [`FreeCameraState`] struct.
pub struct FreeCameraPlugin;
impl Plugin for FreeCameraPlugin {
fn build(&self, app: &mut App) {
// This ordering is required so that both fixed update and update systems can see the results correctly
app.add_systems(
RunFixedMainLoop,
run_freecamera_controller.in_set(RunFixedMainLoopSystems::BeforeFixedMainLoop),
);
}
}
/// Scales mouse motion into yaw/pitch movement.
///
/// Based on Valorant's default sensitivity, not entirely sure why it is exactly 1.0 / 180.0,
/// but we're guessing it is a misunderstanding between degrees/radians and then sticking with
/// it because it felt nice.
const RADIANS_PER_DOT: f32 = 1.0 / 180.0;
/// Stores the settings for the [`FreeCamera`] controller.
///
/// This component defines static configuration for camera controls,
/// including movement speed, sensitivity, and input bindings.
///
/// From the controller’s perspective, this data is treated as immutable,
/// but it may be modified externally (e.g., by a settings UI) at runtime.
///
/// Add this component to a [`Camera`] entity to enable `FreeCamera` controls.
/// The associated dynamic state is automatically handled by [`FreeCameraState`],
/// which is added to the entity as a required component.
///
/// To activate the controller, add the [`FreeCameraPlugin`] to your [`App`].
#[derive(Component)]
#[require(FreeCameraState)]
pub struct FreeCamera {
/// Multiplier for pitch and yaw rotation speed.
pub sensitivity: f32,
/// [`KeyCode`] for forward translation.
pub key_forward: KeyCode,
/// [`KeyCode`] for backward translation.
pub key_back: KeyCode,
/// [`KeyCode`] for left translation.
pub key_left: KeyCode,
/// [`KeyCode`] for right translation.
pub key_right: KeyCode,
/// [`KeyCode`] for up translation.
pub key_up: KeyCode,
/// [`KeyCode`] for down translation.
pub key_down: KeyCode,
/// [`KeyCode`] to use [`run_speed`](FreeCamera::run_speed) instead of
/// [`walk_speed`](FreeCamera::walk_speed) for translation.
pub key_run: KeyCode,
/// [`MouseButton`] for grabbing the mouse focus.
pub mouse_key_cursor_grab: MouseButton,
/// [`KeyCode`] for grabbing the keyboard focus.
pub keyboard_key_toggle_cursor_grab: KeyCode,
/// Base multiplier for unmodified translation speed.
pub walk_speed: f32,
/// Base multiplier for running translation speed.
pub run_speed: f32,
/// Multiplier for how the mouse scroll wheel modifies [`walk_speed`](FreeCamera::walk_speed)
/// and [`run_speed`](FreeCamera::run_speed).
pub scroll_factor: f32,
/// Friction factor used to exponentially decay [`velocity`](FreeCameraState::velocity) over time.
pub friction: f32,
}
impl Default for FreeCamera {
fn default() -> Self {
Self {
sensitivity: 0.2,
key_forward: KeyCode::KeyW,
key_back: KeyCode::KeyS,
key_left: KeyCode::KeyA,
key_right: KeyCode::KeyD,
key_up: KeyCode::KeyE,
key_down: KeyCode::KeyQ,
key_run: KeyCode::ShiftLeft,
mouse_key_cursor_grab: MouseButton::Left,
keyboard_key_toggle_cursor_grab: KeyCode::KeyM,
walk_speed: 5.0,
run_speed: 15.0,
scroll_factor: 0.5,
friction: 40.0,
}
}
}
impl fmt::Display for FreeCamera {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"
Freecamera Controls:
Mouse\t- Move camera orientation
Scroll\t- Adjust movement speed
{:?}\t- Hold to grab cursor
{:?}\t- Toggle cursor grab
{:?} & {:?}\t- Fly forward & backwards
{:?} & {:?}\t- Fly sideways left & right
{:?} & {:?}\t- Fly up & down
{:?}\t- Fly faster while held",
self.mouse_key_cursor_grab,
self.keyboard_key_toggle_cursor_grab,
self.key_forward,
self.key_back,
self.key_left,
self.key_right,
self.key_up,
self.key_down,
self.key_run,
)
}
}
/// Tracks the runtime state of a [`FreeCamera`] controller.
///
/// This component holds dynamic data that changes during camera operation,
/// such as pitch, yaw, velocity, and whether the controller is currently enabled.
///
/// It is automatically added to any entity that has a [`FreeCamera`] component,
/// and is updated by the [`FreeCameraPlugin`] systems in response to user input.
#[derive(Component)]
pub struct FreeCameraState {
/// Enables [`FreeCamera`] controls when `true`.
pub enabled: bool,
/// Internal flag indicating if this controller has been initialized by the [`FreeCameraPlugin`].
initialized: bool,
/// This [`FreeCamera`]'s pitch rotation.
pub pitch: f32,
/// This [`FreeCamera`]'s yaw rotation.
pub yaw: f32,
/// Multiplier applied to movement speed.
pub speed_multiplier: f32,
/// This [`FreeCamera`]'s translation velocity.
pub velocity: Vec3,
}
impl Default for FreeCameraState {
fn default() -> Self {
Self {
enabled: true,
initialized: false,
pitch: 0.0,
yaw: 0.0,
speed_multiplier: 1.0,
velocity: Vec3::ZERO,
}
}
}
/// Updates the camera's position and orientation based on user input.
///
/// - [`FreeCamera`] contains static configuration such as key bindings, movement speed, and sensitivity.
/// - [`FreeCameraState`] stores the dynamic runtime state, including pitch, yaw, velocity, and enable flags.
///
/// This system is typically added via the [`FreeCameraPlugin`].
pub fn run_freecamera_controller(
time: Res<Time<Real>>,
mut windows: Query<(&Window, &mut CursorOptions)>,
accumulated_mouse_motion: Res<AccumulatedMouseMotion>,
accumulated_mouse_scroll: Res<AccumulatedMouseScroll>,
mouse_button_input: Res<ButtonInput<MouseButton>>,
key_input: Res<ButtonInput<KeyCode>>,
mut toggle_cursor_grab: Local<bool>,
mut mouse_cursor_grab: Local<bool>,
mut query: Query<(&mut Transform, &mut FreeCameraState, &FreeCamera), With<Camera>>,
) {
let dt = time.delta_secs();
let Ok((mut transform, mut state, config)) = query.single_mut() else {
return;
};
if !state.initialized {
let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
state.yaw = yaw;
state.pitch = pitch;
state.initialized = true;
info!("{}", *config);
}
if !state.enabled {
// don't keep the cursor grabbed if the camera controller was disabled.
if *toggle_cursor_grab || *mouse_cursor_grab {
*toggle_cursor_grab = false;
*mouse_cursor_grab = false;
for (_, mut cursor_options) in &mut windows {
cursor_options.grab_mode = CursorGrabMode::None;
cursor_options.visible = true;
}
}
return;
}
let mut scroll = 0.0;
let amount = match accumulated_mouse_scroll.unit {
MouseScrollUnit::Line => accumulated_mouse_scroll.delta.y,
MouseScrollUnit::Pixel => {
accumulated_mouse_scroll.delta.y / MouseScrollUnit::SCROLL_UNIT_CONVERSION_FACTOR
}
};
scroll += amount;
state.speed_multiplier += scroll * config.scroll_factor;
// Clamp the speed multiplier for safety
state.speed_multiplier = state.speed_multiplier.clamp(0.0, f32::MAX);
// Handle key input
let mut axis_input = Vec3::ZERO;
if key_input.pressed(config.key_forward) {
axis_input.z += 1.0;
}
if key_input.pressed(config.key_back) {
axis_input.z -= 1.0;
}
if key_input.pressed(config.key_right) {
axis_input.x += 1.0;
}
if key_input.pressed(config.key_left) {
axis_input.x -= 1.0;
}
if key_input.pressed(config.key_up) {
axis_input.y += 1.0;
}
if key_input.pressed(config.key_down) {
axis_input.y -= 1.0;
}
let mut cursor_grab_change = false;
if key_input.just_pressed(config.keyboard_key_toggle_cursor_grab) {
*toggle_cursor_grab = !*toggle_cursor_grab;
cursor_grab_change = true;
}
if mouse_button_input.just_pressed(config.mouse_key_cursor_grab) {
*mouse_cursor_grab = true;
cursor_grab_change = true;
}
if mouse_button_input.just_released(config.mouse_key_cursor_grab) {
*mouse_cursor_grab = false;
cursor_grab_change = true;
}
let cursor_grab = *mouse_cursor_grab || *toggle_cursor_grab;
// Update velocity
if axis_input != Vec3::ZERO {
let max_speed = if key_input.pressed(config.key_run) {
config.run_speed * state.speed_multiplier
} else {
config.walk_speed * state.speed_multiplier
};
state.velocity = axis_input.normalize() * max_speed;
} else {
let friction = config.friction.clamp(0.0, f32::MAX);
state.velocity.smooth_nudge(&Vec3::ZERO, friction, dt);
if state.velocity.length_squared() < 1e-6 {
state.velocity = Vec3::ZERO;
}
}
// Apply movement update
if state.velocity != Vec3::ZERO {
let forward = *transform.forward();
let right = *transform.right();
transform.translation += state.velocity.x * dt * right
+ state.velocity.y * dt * Vec3::Y
+ state.velocity.z * dt * forward;
}
// Handle cursor grab
if cursor_grab_change {
if cursor_grab {
for (window, mut cursor_options) in &mut windows {
if !window.focused {
continue;
}
cursor_options.grab_mode = CursorGrabMode::Locked;
cursor_options.visible = false;
}
} else {
for (_, mut cursor_options) in &mut windows {
cursor_options.grab_mode = CursorGrabMode::None;
cursor_options.visible = true;
}
}
}
// Handle mouse input
if accumulated_mouse_motion.delta != Vec2::ZERO && cursor_grab {
// Apply look update
state.pitch = (state.pitch
- accumulated_mouse_motion.delta.y * RADIANS_PER_DOT * config.sensitivity)
.clamp(-PI / 2., PI / 2.);
state.yaw -= accumulated_mouse_motion.delta.x * RADIANS_PER_DOT * config.sensitivity;
transform.rotation = Quat::from_euler(EulerRot::ZYX, 0.0, state.yaw, state.pitch);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_camera_controller/src/pan_camera.rs | crates/bevy_camera_controller/src/pan_camera.rs | //! A controller for 2D cameras that supports panning, zooming, and rotation.
//!
//! To use this controller, add [`PanCameraPlugin`] to your app,
//! and insert a [`PanCamera`] component into your camera entity.
//!
//! To configure the settings of this controller, modify the fields of the [`PanCamera`] component.
use bevy_app::{App, Plugin, RunFixedMainLoop, RunFixedMainLoopSystems};
use bevy_camera::Camera;
use bevy_ecs::prelude::*;
use bevy_input::keyboard::KeyCode;
use bevy_input::mouse::{AccumulatedMouseScroll, MouseScrollUnit};
use bevy_input::ButtonInput;
use bevy_math::{Vec2, Vec3};
use bevy_time::{Real, Time};
use bevy_transform::prelude::Transform;
use core::{f32::consts::*, fmt};
/// A plugin that enables 2D camera panning and zooming controls.
///
/// Add this plugin to your [`App`] to enable [`PanCamera`] behavior
/// on any camera entity that has the [`PanCamera`] component.
pub struct PanCameraPlugin;
impl Plugin for PanCameraPlugin {
fn build(&self, app: &mut App) {
app.add_systems(
RunFixedMainLoop,
run_pancamera_controller.in_set(RunFixedMainLoopSystems::BeforeFixedMainLoop),
);
}
}
/// Configuration and state for a 2D panning camera controller.
///
/// Add this component to a [`Camera`] entity to enable keyboard and mouse controls
/// for panning, zooming, and optional rotation. Requires the [`PanCameraPlugin`].
#[derive(Component)]
pub struct PanCamera {
/// Enables this [`PanCamera`] when `true`.
pub enabled: bool,
/// Current zoom level (factor applied to camera scale).
pub zoom_factor: f32,
/// Minimum allowed zoom level.
pub min_zoom: f32,
/// Maximum allowed zoom level.
pub max_zoom: f32,
/// Translation speed for panning movement.
pub zoom_speed: f32,
/// [`KeyCode`] to zoom in.
pub key_zoom_in: Option<KeyCode>,
/// [`KeyCode`] to zoom out.
pub key_zoom_out: Option<KeyCode>,
/// This [`PanCamera`]'s translation speed.
pub pan_speed: f32,
/// [`KeyCode`] for upward translation.
pub key_up: Option<KeyCode>,
/// [`KeyCode`] for downward translation.
pub key_down: Option<KeyCode>,
/// [`KeyCode`] for leftward translation.
pub key_left: Option<KeyCode>,
/// [`KeyCode`] for rightward translation.
pub key_right: Option<KeyCode>,
/// Rotation speed multiplier (in radians per second).
pub rotation_speed: f32,
/// [`KeyCode`] for counter-clockwise rotation.
pub key_rotate_ccw: Option<KeyCode>,
/// [`KeyCode`] for clockwise rotation.
pub key_rotate_cw: Option<KeyCode>,
}
/// Provides the default values for the `PanCamera` controller.
///
/// The default settings are:
/// - Zoom factor: 1.0
/// - Min zoom: 0.1
/// - Max zoom: 5.0
/// - Zoom speed: 0.1
/// - Zoom in/out key: +/-
/// - Pan speed: 500.0
/// - Move up/down: W/S
/// - Move left/right: A/D
/// - Rotation speed: PI (radians per second)
/// - Rotation ccw/cw: Q/E
impl Default for PanCamera {
/// Provides the default values for the `PanCamera` controller.
///
/// Users can override these values by manually creating a `PanCamera` instance
/// or modifying the default instance.
fn default() -> Self {
Self {
enabled: true,
zoom_factor: 1.0,
min_zoom: 0.1,
max_zoom: 5.0,
zoom_speed: 0.1,
key_zoom_in: Some(KeyCode::Equal),
key_zoom_out: Some(KeyCode::Minus),
pan_speed: 500.0,
key_up: Some(KeyCode::KeyW),
key_down: Some(KeyCode::KeyS),
key_left: Some(KeyCode::KeyA),
key_right: Some(KeyCode::KeyD),
rotation_speed: PI,
key_rotate_ccw: Some(KeyCode::KeyQ),
key_rotate_cw: Some(KeyCode::KeyE),
}
}
}
impl PanCamera {
fn key_to_string(key: &Option<KeyCode>) -> String {
key.map_or("None".to_string(), |k| format!("{:?}", k))
}
}
impl fmt::Display for PanCamera {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"
PanCamera Controls:
Move Up / Down - {} / {}
Move Left / Right - {} / {}
Rotate CCW / CW - {} / {}
Zoom - Mouse Scroll + {} / {}
",
Self::key_to_string(&self.key_up),
Self::key_to_string(&self.key_down),
Self::key_to_string(&self.key_left),
Self::key_to_string(&self.key_right),
Self::key_to_string(&self.key_rotate_ccw),
Self::key_to_string(&self.key_rotate_cw),
Self::key_to_string(&self.key_zoom_in),
Self::key_to_string(&self.key_zoom_out),
)
}
}
/// This system is typically added via the [`PanCameraPlugin`].
///
/// Reads inputs and then moves the camera entity according
/// to the settings given in [`PanCamera`].
///
/// **Note**: The zoom applied in this controller is linear. The zoom factor is directly adjusted
/// based on the input (either from the mouse scroll or keyboard).
fn run_pancamera_controller(
time: Res<Time<Real>>,
key_input: Res<ButtonInput<KeyCode>>,
accumulated_mouse_scroll: Res<AccumulatedMouseScroll>,
mut query: Query<(&mut Transform, &mut PanCamera), With<Camera>>,
) {
let dt = time.delta_secs();
let Ok((mut transform, mut controller)) = query.single_mut() else {
return;
};
if !controller.enabled {
return;
}
// === Movement
let mut movement = Vec2::ZERO;
if let Some(key) = controller.key_left {
if key_input.pressed(key) {
movement.x -= 1.0;
}
}
if let Some(key) = controller.key_right {
if key_input.pressed(key) {
movement.x += 1.0;
}
}
if let Some(key) = controller.key_down {
if key_input.pressed(key) {
movement.y -= 1.0;
}
}
if let Some(key) = controller.key_up {
if key_input.pressed(key) {
movement.y += 1.0;
}
}
if movement != Vec2::ZERO {
let right = transform.right();
let up = transform.up();
let delta = (right * movement.x + up * movement.y).normalize() * controller.pan_speed * dt;
transform.translation.x += delta.x;
transform.translation.y += delta.y;
}
// === Rotation
if let Some(key) = controller.key_rotate_ccw {
if key_input.pressed(key) {
transform.rotate_z(controller.rotation_speed * dt);
}
}
if let Some(key) = controller.key_rotate_cw {
if key_input.pressed(key) {
transform.rotate_z(-controller.rotation_speed * dt);
}
}
// === Zoom
let mut zoom_amount = 0.0;
// (with keys)
if let Some(key) = controller.key_zoom_in {
if key_input.pressed(key) {
zoom_amount -= controller.zoom_speed;
}
}
if let Some(key) = controller.key_zoom_out {
if key_input.pressed(key) {
zoom_amount += controller.zoom_speed;
}
}
// (with mouse wheel)
let mouse_scroll = match accumulated_mouse_scroll.unit {
MouseScrollUnit::Line => accumulated_mouse_scroll.delta.y,
MouseScrollUnit::Pixel => {
accumulated_mouse_scroll.delta.y / MouseScrollUnit::SCROLL_UNIT_CONVERSION_FACTOR
}
};
zoom_amount += mouse_scroll * controller.zoom_speed;
controller.zoom_factor =
(controller.zoom_factor - zoom_amount).clamp(controller.min_zoom, controller.max_zoom);
transform.scale = Vec3::splat(controller.zoom_factor);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_encase_derive/src/lib.rs | crates/bevy_encase_derive/src/lib.rs | #![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")]
#![forbid(unsafe_code)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(
html_logo_url = "https://bevy.org/assets/icon.png",
html_favicon_url = "https://bevy.org/assets/icon.png"
)]
use bevy_macro_utils::BevyManifest;
use encase_derive_impl::{implement, syn};
const ENCASE: &str = "encase";
fn bevy_encase_path() -> syn::Path {
BevyManifest::shared(|bevy_manifest| {
bevy_manifest
.maybe_get_path("bevy_render")
.map(|bevy_render_path| {
let mut segments = bevy_render_path.segments;
segments.push(BevyManifest::parse_str("render_resource"));
syn::Path {
leading_colon: None,
segments,
}
})
.map(|path| {
let mut segments = path.segments;
segments.push(BevyManifest::parse_str(ENCASE));
syn::Path {
leading_colon: None,
segments,
}
})
.unwrap_or_else(|| bevy_manifest.get_path(ENCASE))
})
}
implement!(bevy_encase_path());
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/compass.rs | crates/bevy_math/src/compass.rs | use crate::Dir2;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
#[cfg(all(feature = "serialize", feature = "bevy_reflect"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
use core::ops::Neg;
use glam::Vec2;
/// A compass enum with 4 directions.
/// ```text
/// N (North)
/// ▲
/// │
/// │
/// W (West) ┼─────► E (East)
/// │
/// │
/// ▼
/// S (South)
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Hash, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Deserialize, Serialize)
)]
pub enum CompassQuadrant {
/// Corresponds to [`Dir2::Y`] and [`Dir2::NORTH`]
North,
/// Corresponds to [`Dir2::X`] and [`Dir2::EAST`]
East,
/// Corresponds to [`Dir2::NEG_X`] and [`Dir2::SOUTH`]
South,
/// Corresponds to [`Dir2::NEG_Y`] and [`Dir2::WEST`]
West,
}
impl CompassQuadrant {
/// Converts a standard index to a [`CompassQuadrant`].
///
/// Starts at 0 for [`CompassQuadrant::North`] and increments clockwise.
pub const fn from_index(index: usize) -> Option<Self> {
match index {
0 => Some(Self::North),
1 => Some(Self::East),
2 => Some(Self::South),
3 => Some(Self::West),
_ => None,
}
}
/// Converts a [`CompassQuadrant`] to a standard index.
///
/// Starts at 0 for [`CompassQuadrant::North`] and increments clockwise.
pub const fn to_index(self) -> usize {
match self {
Self::North => 0,
Self::East => 1,
Self::South => 2,
Self::West => 3,
}
}
/// Returns the opposite [`CompassQuadrant`], located 180 degrees from `self`.
///
/// This can also be accessed via the `-` operator, using the [`Neg`] trait.
pub const fn opposite(&self) -> CompassQuadrant {
match self {
Self::North => Self::South,
Self::East => Self::West,
Self::South => Self::North,
Self::West => Self::East,
}
}
/// Checks if a point is in the direction represented by this [`CompassQuadrant`] from an origin.
///
/// This uses a cone-based check: the vector from origin to the candidate point
/// must have a positive dot product with the direction vector.
///
/// Uses standard mathematical coordinates where Y increases upward.
///
/// # Arguments
///
/// * `origin` - The starting position
/// * `candidate` - The target position to check
///
/// # Returns
///
/// `true` if the candidate is generally in the direction of this quadrant from the origin.
///
/// # Example
///
/// ```
/// use bevy_math::{CompassQuadrant, Vec2};
///
/// let origin = Vec2::new(0.0, 0.0);
/// let north_point = Vec2::new(0.0, 10.0); // Above origin (Y+ = up)
/// let east_point = Vec2::new(10.0, 0.0); // Right of origin
///
/// assert!(CompassQuadrant::North.is_in_direction(origin, north_point));
/// assert!(!CompassQuadrant::North.is_in_direction(origin, east_point));
/// ```
pub fn is_in_direction(self, origin: Vec2, candidate: Vec2) -> bool {
let dir = Dir2::from(self);
let to_candidate = candidate - origin;
to_candidate.dot(*dir) > 0.0
}
}
/// A compass enum with 8 directions.
/// ```text
/// N (North)
/// ▲
/// NW │ NE
/// ╲ │ ╱
/// W (West) ┼─────► E (East)
/// ╱ │ ╲
/// SW │ SE
/// ▼
/// S (South)
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Hash, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Deserialize, Serialize)
)]
pub enum CompassOctant {
/// Corresponds to [`Dir2::Y`] and [`Dir2::NORTH`]
North,
/// Corresponds to [`Dir2::NORTH_EAST`]
NorthEast,
/// Corresponds to [`Dir2::X`] and [`Dir2::EAST`]
East,
/// Corresponds to [`Dir2::SOUTH_EAST`]
SouthEast,
/// Corresponds to [`Dir2::NEG_X`] and [`Dir2::SOUTH`]
South,
/// Corresponds to [`Dir2::SOUTH_WEST`]
SouthWest,
/// Corresponds to [`Dir2::NEG_Y`] and [`Dir2::WEST`]
West,
/// Corresponds to [`Dir2::NORTH_WEST`]
NorthWest,
}
impl CompassOctant {
/// Converts a standard index to a [`CompassOctant`].
///
/// Starts at 0 for [`CompassOctant::North`] and increments clockwise.
pub const fn from_index(index: usize) -> Option<Self> {
match index {
0 => Some(Self::North),
1 => Some(Self::NorthEast),
2 => Some(Self::East),
3 => Some(Self::SouthEast),
4 => Some(Self::South),
5 => Some(Self::SouthWest),
6 => Some(Self::West),
7 => Some(Self::NorthWest),
_ => None,
}
}
/// Converts a [`CompassOctant`] to a standard index.
///
/// Starts at 0 for [`CompassOctant::North`] and increments clockwise.
pub const fn to_index(self) -> usize {
match self {
Self::North => 0,
Self::NorthEast => 1,
Self::East => 2,
Self::SouthEast => 3,
Self::South => 4,
Self::SouthWest => 5,
Self::West => 6,
Self::NorthWest => 7,
}
}
/// Returns the opposite [`CompassOctant`], located 180 degrees from `self`.
///
/// This can also be accessed via the `-` operator, using the [`Neg`] trait.
pub const fn opposite(&self) -> CompassOctant {
match self {
Self::North => Self::South,
Self::NorthEast => Self::SouthWest,
Self::East => Self::West,
Self::SouthEast => Self::NorthWest,
Self::South => Self::North,
Self::SouthWest => Self::NorthEast,
Self::West => Self::East,
Self::NorthWest => Self::SouthEast,
}
}
/// Checks if a point is in the direction represented by this [`CompassOctant`] from an origin.
///
/// This uses a cone-based check: the vector from origin to the candidate point
/// must have a positive dot product with the direction vector.
///
/// Uses standard mathematical coordinates where Y increases upward.
///
/// # Arguments
///
/// * `origin` - The starting position
/// * `candidate` - The target position to check
///
/// # Returns
///
/// `true` if the candidate is generally in the direction of this octant from the origin.
///
/// # Example
///
/// ```
/// use bevy_math::{CompassOctant, Vec2};
///
/// let origin = Vec2::new(0.0, 0.0);
/// let north_point = Vec2::new(0.0, 10.0); // Above origin (Y+ = up)
/// let east_point = Vec2::new(10.0, 0.0); // Right of origin
///
/// assert!(CompassOctant::North.is_in_direction(origin, north_point));
/// assert!(!CompassOctant::North.is_in_direction(origin, east_point));
/// ```
pub fn is_in_direction(self, origin: Vec2, candidate: Vec2) -> bool {
let dir = Dir2::from(self);
let to_candidate = candidate - origin;
to_candidate.dot(*dir) > 0.0
}
}
impl From<CompassQuadrant> for Dir2 {
fn from(q: CompassQuadrant) -> Self {
match q {
CompassQuadrant::North => Dir2::NORTH,
CompassQuadrant::East => Dir2::EAST,
CompassQuadrant::South => Dir2::SOUTH,
CompassQuadrant::West => Dir2::WEST,
}
}
}
impl From<Dir2> for CompassQuadrant {
/// Converts a [`Dir2`] to a [`CompassQuadrant`] in a lossy manner.
/// Converting back to a [`Dir2`] is not guaranteed to yield the same value.
fn from(dir: Dir2) -> Self {
let angle = dir.to_angle().to_degrees();
match angle {
-135.0..=-45.0 => Self::South,
-45.0..=45.0 => Self::East,
45.0..=135.0 => Self::North,
135.0..=180.0 | -180.0..=-135.0 => Self::West,
_ => unreachable!(),
}
}
}
impl From<CompassOctant> for Dir2 {
fn from(o: CompassOctant) -> Self {
match o {
CompassOctant::North => Dir2::NORTH,
CompassOctant::NorthEast => Dir2::NORTH_EAST,
CompassOctant::East => Dir2::EAST,
CompassOctant::SouthEast => Dir2::SOUTH_EAST,
CompassOctant::South => Dir2::SOUTH,
CompassOctant::SouthWest => Dir2::SOUTH_WEST,
CompassOctant::West => Dir2::WEST,
CompassOctant::NorthWest => Dir2::NORTH_WEST,
}
}
}
impl From<Dir2> for CompassOctant {
/// Converts a [`Dir2`] to a [`CompassOctant`] in a lossy manner.
/// Converting back to a [`Dir2`] is not guaranteed to yield the same value.
fn from(dir: Dir2) -> Self {
let angle = dir.to_angle().to_degrees();
match angle {
-112.5..=-67.5 => Self::South,
-67.5..=-22.5 => Self::SouthEast,
-22.5..=22.5 => Self::East,
22.5..=67.5 => Self::NorthEast,
67.5..=112.5 => Self::North,
112.5..=157.5 => Self::NorthWest,
157.5..=180.0 | -180.0..=-157.5 => Self::West,
-157.5..=-112.5 => Self::SouthWest,
_ => unreachable!(),
}
}
}
impl Neg for CompassQuadrant {
type Output = CompassQuadrant;
fn neg(self) -> Self::Output {
self.opposite()
}
}
impl Neg for CompassOctant {
type Output = CompassOctant;
fn neg(self) -> Self::Output {
self.opposite()
}
}
#[cfg(test)]
mod test_compass_quadrant {
use crate::{CompassQuadrant, Dir2, Vec2};
#[test]
fn test_cardinal_directions() {
let tests = [
(
Dir2::new(Vec2::new(1.0, 0.0)).unwrap(),
CompassQuadrant::East,
),
(
Dir2::new(Vec2::new(0.0, 1.0)).unwrap(),
CompassQuadrant::North,
),
(
Dir2::new(Vec2::new(-1.0, 0.0)).unwrap(),
CompassQuadrant::West,
),
(
Dir2::new(Vec2::new(0.0, -1.0)).unwrap(),
CompassQuadrant::South,
),
];
for (dir, expected) in tests {
assert_eq!(CompassQuadrant::from(dir), expected);
}
}
#[test]
fn test_north_pie_slice() {
let tests = [
(
Dir2::new(Vec2::new(-0.1, 0.9)).unwrap(),
CompassQuadrant::North,
),
(
Dir2::new(Vec2::new(0.1, 0.9)).unwrap(),
CompassQuadrant::North,
),
];
for (dir, expected) in tests {
assert_eq!(CompassQuadrant::from(dir), expected);
}
}
#[test]
fn test_east_pie_slice() {
let tests = [
(
Dir2::new(Vec2::new(0.9, 0.1)).unwrap(),
CompassQuadrant::East,
),
(
Dir2::new(Vec2::new(0.9, -0.1)).unwrap(),
CompassQuadrant::East,
),
];
for (dir, expected) in tests {
assert_eq!(CompassQuadrant::from(dir), expected);
}
}
#[test]
fn test_south_pie_slice() {
let tests = [
(
Dir2::new(Vec2::new(-0.1, -0.9)).unwrap(),
CompassQuadrant::South,
),
(
Dir2::new(Vec2::new(0.1, -0.9)).unwrap(),
CompassQuadrant::South,
),
];
for (dir, expected) in tests {
assert_eq!(CompassQuadrant::from(dir), expected);
}
}
#[test]
fn test_west_pie_slice() {
let tests = [
(
Dir2::new(Vec2::new(-0.9, -0.1)).unwrap(),
CompassQuadrant::West,
),
(
Dir2::new(Vec2::new(-0.9, 0.1)).unwrap(),
CompassQuadrant::West,
),
];
for (dir, expected) in tests {
assert_eq!(CompassQuadrant::from(dir), expected);
}
}
#[test]
fn out_of_bounds_indexes_return_none() {
assert_eq!(CompassQuadrant::from_index(4), None);
assert_eq!(CompassQuadrant::from_index(5), None);
assert_eq!(CompassQuadrant::from_index(usize::MAX), None);
}
#[test]
fn compass_indexes_are_reversible() {
for i in 0..4 {
let quadrant = CompassQuadrant::from_index(i).unwrap();
assert_eq!(quadrant.to_index(), i);
}
}
#[test]
fn opposite_directions_reverse_themselves() {
for i in 0..4 {
let quadrant = CompassQuadrant::from_index(i).unwrap();
assert_eq!(-(-quadrant), quadrant);
}
}
}
#[cfg(test)]
mod test_compass_octant {
use crate::{CompassOctant, Dir2, Vec2};
#[test]
fn test_cardinal_directions() {
let tests = [
(
Dir2::new(Vec2::new(-0.5, 0.5)).unwrap(),
CompassOctant::NorthWest,
),
(
Dir2::new(Vec2::new(0.0, 1.0)).unwrap(),
CompassOctant::North,
),
(
Dir2::new(Vec2::new(0.5, 0.5)).unwrap(),
CompassOctant::NorthEast,
),
(Dir2::new(Vec2::new(1.0, 0.0)).unwrap(), CompassOctant::East),
(
Dir2::new(Vec2::new(0.5, -0.5)).unwrap(),
CompassOctant::SouthEast,
),
(
Dir2::new(Vec2::new(0.0, -1.0)).unwrap(),
CompassOctant::South,
),
(
Dir2::new(Vec2::new(-0.5, -0.5)).unwrap(),
CompassOctant::SouthWest,
),
(
Dir2::new(Vec2::new(-1.0, 0.0)).unwrap(),
CompassOctant::West,
),
];
for (dir, expected) in tests {
assert_eq!(CompassOctant::from(dir), expected);
}
}
#[test]
fn test_north_pie_slice() {
let tests = [
(
Dir2::new(Vec2::new(-0.1, 0.9)).unwrap(),
CompassOctant::North,
),
(
Dir2::new(Vec2::new(0.1, 0.9)).unwrap(),
CompassOctant::North,
),
];
for (dir, expected) in tests {
assert_eq!(CompassOctant::from(dir), expected);
}
}
#[test]
fn test_north_east_pie_slice() {
let tests = [
(
Dir2::new(Vec2::new(0.4, 0.6)).unwrap(),
CompassOctant::NorthEast,
),
(
Dir2::new(Vec2::new(0.6, 0.4)).unwrap(),
CompassOctant::NorthEast,
),
];
for (dir, expected) in tests {
assert_eq!(CompassOctant::from(dir), expected);
}
}
#[test]
fn test_east_pie_slice() {
let tests = [
(Dir2::new(Vec2::new(0.9, 0.1)).unwrap(), CompassOctant::East),
(
Dir2::new(Vec2::new(0.9, -0.1)).unwrap(),
CompassOctant::East,
),
];
for (dir, expected) in tests {
assert_eq!(CompassOctant::from(dir), expected);
}
}
#[test]
fn test_south_east_pie_slice() {
let tests = [
(
Dir2::new(Vec2::new(0.4, -0.6)).unwrap(),
CompassOctant::SouthEast,
),
(
Dir2::new(Vec2::new(0.6, -0.4)).unwrap(),
CompassOctant::SouthEast,
),
];
for (dir, expected) in tests {
assert_eq!(CompassOctant::from(dir), expected);
}
}
#[test]
fn test_south_pie_slice() {
let tests = [
(
Dir2::new(Vec2::new(-0.1, -0.9)).unwrap(),
CompassOctant::South,
),
(
Dir2::new(Vec2::new(0.1, -0.9)).unwrap(),
CompassOctant::South,
),
];
for (dir, expected) in tests {
assert_eq!(CompassOctant::from(dir), expected);
}
}
#[test]
fn test_south_west_pie_slice() {
let tests = [
(
Dir2::new(Vec2::new(-0.4, -0.6)).unwrap(),
CompassOctant::SouthWest,
),
(
Dir2::new(Vec2::new(-0.6, -0.4)).unwrap(),
CompassOctant::SouthWest,
),
];
for (dir, expected) in tests {
assert_eq!(CompassOctant::from(dir), expected);
}
}
#[test]
fn test_west_pie_slice() {
let tests = [
(
Dir2::new(Vec2::new(-0.9, -0.1)).unwrap(),
CompassOctant::West,
),
(
Dir2::new(Vec2::new(-0.9, 0.1)).unwrap(),
CompassOctant::West,
),
];
for (dir, expected) in tests {
assert_eq!(CompassOctant::from(dir), expected);
}
}
#[test]
fn test_north_west_pie_slice() {
let tests = [
(
Dir2::new(Vec2::new(-0.4, 0.6)).unwrap(),
CompassOctant::NorthWest,
),
(
Dir2::new(Vec2::new(-0.6, 0.4)).unwrap(),
CompassOctant::NorthWest,
),
];
for (dir, expected) in tests {
assert_eq!(CompassOctant::from(dir), expected);
}
}
#[test]
fn out_of_bounds_indexes_return_none() {
assert_eq!(CompassOctant::from_index(8), None);
assert_eq!(CompassOctant::from_index(9), None);
assert_eq!(CompassOctant::from_index(usize::MAX), None);
}
#[test]
fn compass_indexes_are_reversible() {
for i in 0..8 {
let octant = CompassOctant::from_index(i).unwrap();
assert_eq!(octant.to_index(), i);
}
}
#[test]
fn opposite_directions_reverse_themselves() {
for i in 0..8 {
let octant = CompassOctant::from_index(i).unwrap();
assert_eq!(-(-octant), octant);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/lib.rs | crates/bevy_math/src/lib.rs | #![forbid(unsafe_code)]
#![cfg_attr(
any(docsrs, docsrs_dep),
expect(
internal_features,
reason = "rustdoc_internals is needed for fake_variadic"
)
)]
#![cfg_attr(any(docsrs, docsrs_dep), feature(rustdoc_internals))]
#![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"
)]
#![no_std]
//! Provides math types and functionality for the Bevy game engine.
//!
//! The commonly used types are vectors like [`Vec2`] and [`Vec3`],
//! matrices like [`Mat2`], [`Mat3`] and [`Mat4`] and orientation representations
//! like [`Quat`].
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "alloc")]
extern crate alloc;
mod affine3;
mod aspect_ratio;
pub mod bounding;
pub mod common_traits;
mod compass;
pub mod cubic_splines;
mod direction;
mod float_ord;
mod isometry;
mod mat3;
pub mod ops;
pub mod primitives;
mod ray;
mod rects;
mod rotation2d;
#[cfg(feature = "curve")]
pub mod curve;
#[cfg(feature = "rand")]
pub mod sampling;
pub use affine3::*;
pub use aspect_ratio::AspectRatio;
pub use common_traits::*;
pub use compass::{CompassOctant, CompassQuadrant};
pub use direction::*;
pub use float_ord::*;
pub use isometry::{Isometry2d, Isometry3d};
pub use mat3::*;
pub use ops::FloatPow;
pub use ray::{Ray2d, Ray3d};
pub use rects::*;
pub use rotation2d::Rot2;
#[cfg(feature = "curve")]
pub use curve::Curve;
#[cfg(feature = "rand")]
pub use sampling::{FromRng, ShapeSample};
/// The math prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
pub mod prelude {
#[doc(hidden)]
pub use crate::{
bvec2, bvec3, bvec3a, bvec4, bvec4a,
cubic_splines::{CubicNurbsError, CubicSegment, RationalSegment},
direction::{Dir2, Dir3, Dir3A},
ivec2, ivec3, ivec4, mat2, mat3, mat3a, mat4, ops,
primitives::*,
quat, uvec2, uvec3, uvec4, vec2, vec3, vec3a, vec4, BVec2, BVec3, BVec3A, BVec4, BVec4A,
EulerRot, FloatExt, IRect, IVec2, IVec3, IVec4, Isometry2d, Isometry3d, Mat2, Mat3, Mat3A,
Mat4, Quat, Ray2d, Ray3d, Rect, Rot2, StableInterpolate, URect, UVec2, UVec3, UVec4, Vec2,
Vec2Swizzles, Vec3, Vec3A, Vec3Swizzles, Vec4, Vec4Swizzles,
};
#[doc(hidden)]
#[cfg(feature = "curve")]
pub use crate::curve::*;
#[doc(hidden)]
#[cfg(feature = "rand")]
pub use crate::sampling::{FromRng, ShapeSample};
#[cfg(feature = "alloc")]
#[doc(hidden)]
pub use crate::cubic_splines::{
CubicBSpline, CubicBezier, CubicCardinalSpline, CubicCurve, CubicGenerator, CubicHermite,
CubicNurbs, CyclicCubicGenerator, RationalCurve, RationalGenerator,
};
}
pub use glam::*;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/mat3.rs | crates/bevy_math/src/mat3.rs | //! Extra utilities for 3×3 matrices.
use glam::{Mat3A, Vec3, Vec3A};
/// Creates a 3×3 matrix that reflects points across the plane at the origin
/// with the given normal.
///
/// This is also known as a [Householder matrix]. It has the general form I -
/// 2NNᵀ, where N is the normal of the plane and I is the identity matrix.
///
/// If the plane across which points are to be reflected isn't at the origin,
/// you can create a translation matrix that translates the points to the
/// origin, then apply the matrix that this function returns on top of that, and
/// finally translate back to the original position.
///
/// See the `mirror` example for a demonstration of how you might use this
/// function.
///
/// [Householder matrix]: https://en.wikipedia.org/wiki/Householder_transformation
#[doc(alias = "householder")]
pub fn reflection_matrix(plane_normal: Vec3) -> Mat3A {
// N times Nᵀ.
let n_nt = Mat3A::from_cols(
Vec3A::from(plane_normal) * plane_normal.x,
Vec3A::from(plane_normal) * plane_normal.y,
Vec3A::from(plane_normal) * plane_normal.z,
);
Mat3A::IDENTITY - n_nt * 2.0
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/affine3.rs | crates/bevy_math/src/affine3.rs | use glam::{Affine3A, Mat3, Vec3, Vec3Swizzles, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
/// Reduced-size version of `glam::Affine3A` for use when storage has
/// significant performance impact. Convert to `glam::Affine3A` to do
/// non-trivial calculations.
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
pub struct Affine3 {
/// Scaling, rotation, shears, and other non-translation affine transforms
pub matrix3: Mat3,
/// Translation
pub translation: Vec3,
}
impl Affine3 {
/// Calculates the transpose of the affine 4x3 matrix to a 3x4 and formats it for packing into GPU buffers
#[inline]
pub fn to_transpose(&self) -> [Vec4; 3] {
let transpose_3x3 = self.matrix3.transpose();
[
transpose_3x3.x_axis.extend(self.translation.x),
transpose_3x3.y_axis.extend(self.translation.y),
transpose_3x3.z_axis.extend(self.translation.z),
]
}
/// Calculates the inverse transpose of the 3x3 matrix and formats it for packing into GPU buffers
#[inline]
pub fn inverse_transpose_3x3(&self) -> ([Vec4; 2], f32) {
let inverse_transpose_3x3 = Affine3A::from(self).inverse().matrix3.transpose();
(
[
(inverse_transpose_3x3.x_axis, inverse_transpose_3x3.y_axis.x).into(),
(
inverse_transpose_3x3.y_axis.yz(),
inverse_transpose_3x3.z_axis.xy(),
)
.into(),
],
inverse_transpose_3x3.z_axis.z,
)
}
}
impl From<&Affine3A> for Affine3 {
fn from(affine: &Affine3A) -> Self {
Self {
matrix3: affine.matrix3.into(),
translation: affine.translation.into(),
}
}
}
impl From<&Affine3> for Affine3A {
fn from(affine3: &Affine3) -> Self {
Self {
matrix3: affine3.matrix3.into(),
translation: affine3.translation.into(),
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/isometry.rs | crates/bevy_math/src/isometry.rs | //! Isometry types for expressing rigid motions in two and three dimensions.
use crate::{Affine2, Affine3, Affine3A, Dir2, Dir3, Mat3, Mat3A, Quat, Rot2, Vec2, Vec3, Vec3A};
use core::ops::Mul;
#[cfg(feature = "approx")]
use approx::{AbsDiffEq, RelativeEq, UlpsEq};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
#[cfg(all(feature = "bevy_reflect", feature = "serialize"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
/// An isometry in two dimensions, representing a rotation followed by a translation.
/// This can often be useful for expressing relative positions and transformations from one position to another.
///
/// In particular, this type represents a distance-preserving transformation known as a *rigid motion* or a *direct motion*,
/// and belongs to the special [Euclidean group] SE(2). This includes translation and rotation, but excludes reflection.
///
/// For the three-dimensional version, see [`Isometry3d`].
///
/// [Euclidean group]: https://en.wikipedia.org/wiki/Euclidean_group
///
/// # Example
///
/// Isometries can be created from a given translation and rotation:
///
/// ```
/// # use bevy_math::{Isometry2d, Rot2, Vec2};
/// #
/// let iso = Isometry2d::new(Vec2::new(2.0, 1.0), Rot2::degrees(90.0));
/// ```
///
/// Or from separate parts:
///
/// ```
/// # use bevy_math::{Isometry2d, Rot2, Vec2};
/// #
/// let iso1 = Isometry2d::from_translation(Vec2::new(2.0, 1.0));
/// let iso2 = Isometry2d::from_rotation(Rot2::degrees(90.0));
/// ```
///
/// The isometries can be used to transform points:
///
/// ```
/// # use approx::assert_abs_diff_eq;
/// # use bevy_math::{Isometry2d, Rot2, Vec2};
/// #
/// let iso = Isometry2d::new(Vec2::new(2.0, 1.0), Rot2::degrees(90.0));
/// let point = Vec2::new(4.0, 4.0);
///
/// // These are equivalent
/// let result = iso.transform_point(point);
/// let result = iso * point;
///
/// assert_eq!(result, Vec2::new(-2.0, 5.0));
/// ```
///
/// Isometries can also be composed together:
///
/// ```
/// # use bevy_math::{Isometry2d, Rot2, Vec2};
/// #
/// # let iso = Isometry2d::new(Vec2::new(2.0, 1.0), Rot2::degrees(90.0));
/// # let iso1 = Isometry2d::from_translation(Vec2::new(2.0, 1.0));
/// # let iso2 = Isometry2d::from_rotation(Rot2::degrees(90.0));
/// #
/// assert_eq!(iso1 * iso2, iso);
/// ```
///
/// One common operation is to compute an isometry representing the relative positions of two objects
/// for things like intersection tests. This can be done with an inverse transformation:
///
/// ```
/// # use bevy_math::{Isometry2d, Rot2, Vec2};
/// #
/// let circle_iso = Isometry2d::from_translation(Vec2::new(2.0, 1.0));
/// let rectangle_iso = Isometry2d::from_rotation(Rot2::degrees(90.0));
///
/// // Compute the relative position and orientation between the two shapes
/// let relative_iso = circle_iso.inverse() * rectangle_iso;
///
/// // Or alternatively, to skip an extra rotation operation:
/// let relative_iso = circle_iso.inverse_mul(rectangle_iso);
/// ```
#[derive(Copy, Clone, Default, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Isometry2d {
/// The rotational part of a two-dimensional isometry.
pub rotation: Rot2,
/// The translational part of a two-dimensional isometry.
pub translation: Vec2,
}
impl Isometry2d {
/// The identity isometry which represents the rigid motion of not doing anything.
pub const IDENTITY: Self = Isometry2d {
rotation: Rot2::IDENTITY,
translation: Vec2::ZERO,
};
/// Create a two-dimensional isometry from a rotation and a translation.
#[inline]
pub const fn new(translation: Vec2, rotation: Rot2) -> Self {
Isometry2d {
rotation,
translation,
}
}
/// Create a two-dimensional isometry from a rotation.
#[inline]
pub const fn from_rotation(rotation: Rot2) -> Self {
Isometry2d {
rotation,
translation: Vec2::ZERO,
}
}
/// Create a two-dimensional isometry from a translation.
#[inline]
pub const fn from_translation(translation: Vec2) -> Self {
Isometry2d {
rotation: Rot2::IDENTITY,
translation,
}
}
/// Create a two-dimensional isometry from a translation with the given `x` and `y` components.
#[inline]
pub const fn from_xy(x: f32, y: f32) -> Self {
Isometry2d {
rotation: Rot2::IDENTITY,
translation: Vec2::new(x, y),
}
}
/// The inverse isometry that undoes this one.
#[inline]
pub fn inverse(&self) -> Self {
let inv_rot = self.rotation.inverse();
Isometry2d {
rotation: inv_rot,
translation: inv_rot * -self.translation,
}
}
/// Compute `iso1.inverse() * iso2` in a more efficient way for one-shot cases.
///
/// If the same isometry is used multiple times, it is more efficient to instead compute
/// the inverse once and use that for each transformation.
#[inline]
pub fn inverse_mul(&self, rhs: Self) -> Self {
let inv_rot = self.rotation.inverse();
let delta_translation = rhs.translation - self.translation;
Self::new(inv_rot * delta_translation, inv_rot * rhs.rotation)
}
/// Transform a point by rotating and translating it using this isometry.
#[inline]
pub fn transform_point(&self, point: Vec2) -> Vec2 {
self.rotation * point + self.translation
}
/// Transform a point by rotating and translating it using the inverse of this isometry.
///
/// This is more efficient than `iso.inverse().transform_point(point)` for one-shot cases.
/// If the same isometry is used multiple times, it is more efficient to instead compute
/// the inverse once and use that for each transformation.
#[inline]
pub fn inverse_transform_point(&self, point: Vec2) -> Vec2 {
self.rotation.inverse() * (point - self.translation)
}
}
impl From<Isometry2d> for Affine2 {
#[inline]
fn from(iso: Isometry2d) -> Self {
Affine2 {
matrix2: iso.rotation.into(),
translation: iso.translation,
}
}
}
impl From<Vec2> for Isometry2d {
#[inline]
fn from(translation: Vec2) -> Self {
Isometry2d::from_translation(translation)
}
}
impl From<Rot2> for Isometry2d {
#[inline]
fn from(rotation: Rot2) -> Self {
Isometry2d::from_rotation(rotation)
}
}
impl Mul for Isometry2d {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self::Output {
Isometry2d {
rotation: self.rotation * rhs.rotation,
translation: self.rotation * rhs.translation + self.translation,
}
}
}
impl Mul<Vec2> for Isometry2d {
type Output = Vec2;
#[inline]
fn mul(self, rhs: Vec2) -> Self::Output {
self.transform_point(rhs)
}
}
impl Mul<Dir2> for Isometry2d {
type Output = Dir2;
#[inline]
fn mul(self, rhs: Dir2) -> Self::Output {
self.rotation * rhs
}
}
#[cfg(feature = "approx")]
impl AbsDiffEq for Isometry2d {
type Epsilon = <f32 as AbsDiffEq>::Epsilon;
fn default_epsilon() -> Self::Epsilon {
f32::default_epsilon()
}
fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
self.rotation.abs_diff_eq(&other.rotation, epsilon)
&& self.translation.abs_diff_eq(other.translation, epsilon)
}
}
#[cfg(feature = "approx")]
impl RelativeEq for Isometry2d {
fn default_max_relative() -> Self::Epsilon {
Self::default_epsilon()
}
fn relative_eq(
&self,
other: &Self,
epsilon: Self::Epsilon,
max_relative: Self::Epsilon,
) -> bool {
self.rotation
.relative_eq(&other.rotation, epsilon, max_relative)
&& self
.translation
.relative_eq(&other.translation, epsilon, max_relative)
}
}
#[cfg(feature = "approx")]
impl UlpsEq for Isometry2d {
fn default_max_ulps() -> u32 {
4
}
fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
self.rotation.ulps_eq(&other.rotation, epsilon, max_ulps)
&& self
.translation
.ulps_eq(&other.translation, epsilon, max_ulps)
}
}
/// An isometry in three dimensions, representing a rotation followed by a translation.
/// This can often be useful for expressing relative positions and transformations from one position to another.
///
/// In particular, this type represents a distance-preserving transformation known as a *rigid motion* or a *direct motion*,
/// and belongs to the special [Euclidean group] SE(3). This includes translation and rotation, but excludes reflection.
///
/// For the two-dimensional version, see [`Isometry2d`].
///
/// [Euclidean group]: https://en.wikipedia.org/wiki/Euclidean_group
///
/// # Example
///
/// Isometries can be created from a given translation and rotation:
///
/// ```
/// # use bevy_math::{Isometry3d, Quat, Vec3};
/// # use std::f32::consts::FRAC_PI_2;
/// #
/// let iso = Isometry3d::new(Vec3::new(2.0, 1.0, 3.0), Quat::from_rotation_z(FRAC_PI_2));
/// ```
///
/// Or from separate parts:
///
/// ```
/// # use bevy_math::{Isometry3d, Quat, Vec3};
/// # use std::f32::consts::FRAC_PI_2;
/// #
/// let iso1 = Isometry3d::from_translation(Vec3::new(2.0, 1.0, 3.0));
/// let iso2 = Isometry3d::from_rotation(Quat::from_rotation_z(FRAC_PI_2));
/// ```
///
/// The isometries can be used to transform points:
///
/// ```
/// # use approx::assert_relative_eq;
/// # use bevy_math::{Isometry3d, Quat, Vec3};
/// # use std::f32::consts::FRAC_PI_2;
/// #
/// let iso = Isometry3d::new(Vec3::new(2.0, 1.0, 3.0), Quat::from_rotation_z(FRAC_PI_2));
/// let point = Vec3::new(4.0, 4.0, 4.0);
///
/// // These are equivalent
/// let result = iso.transform_point(point);
/// let result = iso * point;
///
/// assert_relative_eq!(result, Vec3::new(-2.0, 5.0, 7.0));
/// ```
///
/// Isometries can also be composed together:
///
/// ```
/// # use bevy_math::{Isometry3d, Quat, Vec3};
/// # use std::f32::consts::FRAC_PI_2;
/// #
/// # let iso = Isometry3d::new(Vec3::new(2.0, 1.0, 3.0), Quat::from_rotation_z(FRAC_PI_2));
/// # let iso1 = Isometry3d::from_translation(Vec3::new(2.0, 1.0, 3.0));
/// # let iso2 = Isometry3d::from_rotation(Quat::from_rotation_z(FRAC_PI_2));
/// #
/// assert_eq!(iso1 * iso2, iso);
/// ```
///
/// One common operation is to compute an isometry representing the relative positions of two objects
/// for things like intersection tests. This can be done with an inverse transformation:
///
/// ```
/// # use bevy_math::{Isometry3d, Quat, Vec3};
/// # use std::f32::consts::FRAC_PI_2;
/// #
/// let sphere_iso = Isometry3d::from_translation(Vec3::new(2.0, 1.0, 3.0));
/// let cuboid_iso = Isometry3d::from_rotation(Quat::from_rotation_z(FRAC_PI_2));
///
/// // Compute the relative position and orientation between the two shapes
/// let relative_iso = sphere_iso.inverse() * cuboid_iso;
///
/// // Or alternatively, to skip an extra rotation operation:
/// let relative_iso = sphere_iso.inverse_mul(cuboid_iso);
/// ```
#[derive(Copy, Clone, Default, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Isometry3d {
/// The rotational part of a three-dimensional isometry.
pub rotation: Quat,
/// The translational part of a three-dimensional isometry.
pub translation: Vec3A,
}
impl Isometry3d {
/// The identity isometry which represents the rigid motion of not doing anything.
pub const IDENTITY: Self = Isometry3d {
rotation: Quat::IDENTITY,
translation: Vec3A::ZERO,
};
/// Create a three-dimensional isometry from a rotation and a translation.
#[inline]
pub fn new(translation: impl Into<Vec3A>, rotation: Quat) -> Self {
Isometry3d {
rotation,
translation: translation.into(),
}
}
/// Create a three-dimensional isometry from a rotation.
#[inline]
pub const fn from_rotation(rotation: Quat) -> Self {
Isometry3d {
rotation,
translation: Vec3A::ZERO,
}
}
/// Create a three-dimensional isometry from a translation.
#[inline]
pub fn from_translation(translation: impl Into<Vec3A>) -> Self {
Isometry3d {
rotation: Quat::IDENTITY,
translation: translation.into(),
}
}
/// Create a three-dimensional isometry from a translation with the given `x`, `y`, and `z` components.
#[inline]
pub const fn from_xyz(x: f32, y: f32, z: f32) -> Self {
Isometry3d {
rotation: Quat::IDENTITY,
translation: Vec3A::new(x, y, z),
}
}
/// The inverse isometry that undoes this one.
#[inline]
pub fn inverse(&self) -> Self {
let inv_rot = self.rotation.inverse();
Isometry3d {
rotation: inv_rot,
translation: inv_rot * -self.translation,
}
}
/// Compute `iso1.inverse() * iso2` in a more efficient way for one-shot cases.
///
/// If the same isometry is used multiple times, it is more efficient to instead compute
/// the inverse once and use that for each transformation.
#[inline]
pub fn inverse_mul(&self, rhs: Self) -> Self {
let inv_rot = self.rotation.inverse();
let delta_translation = rhs.translation - self.translation;
Self::new(inv_rot * delta_translation, inv_rot * rhs.rotation)
}
/// Transform a point by rotating and translating it using this isometry.
#[inline]
pub fn transform_point(&self, point: impl Into<Vec3A>) -> Vec3A {
self.rotation * point.into() + self.translation
}
/// Transform a point by rotating and translating it using the inverse of this isometry.
///
/// This is more efficient than `iso.inverse().transform_point(point)` for one-shot cases.
/// If the same isometry is used multiple times, it is more efficient to instead compute
/// the inverse once and use that for each transformation.
#[inline]
pub fn inverse_transform_point(&self, point: impl Into<Vec3A>) -> Vec3A {
self.rotation.inverse() * (point.into() - self.translation)
}
}
impl From<Isometry3d> for Affine3 {
#[inline]
fn from(iso: Isometry3d) -> Self {
Affine3 {
matrix3: Mat3::from_quat(iso.rotation),
translation: iso.translation.into(),
}
}
}
impl From<Isometry3d> for Affine3A {
#[inline]
fn from(iso: Isometry3d) -> Self {
Affine3A {
matrix3: Mat3A::from_quat(iso.rotation),
translation: iso.translation,
}
}
}
impl From<Vec3> for Isometry3d {
#[inline]
fn from(translation: Vec3) -> Self {
Isometry3d::from_translation(translation)
}
}
impl From<Vec3A> for Isometry3d {
#[inline]
fn from(translation: Vec3A) -> Self {
Isometry3d::from_translation(translation)
}
}
impl From<Quat> for Isometry3d {
#[inline]
fn from(rotation: Quat) -> Self {
Isometry3d::from_rotation(rotation)
}
}
impl Mul for Isometry3d {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self::Output {
Isometry3d {
rotation: self.rotation * rhs.rotation,
translation: self.rotation * rhs.translation + self.translation,
}
}
}
impl Mul<Vec3A> for Isometry3d {
type Output = Vec3A;
#[inline]
fn mul(self, rhs: Vec3A) -> Self::Output {
self.transform_point(rhs)
}
}
impl Mul<Vec3> for Isometry3d {
type Output = Vec3;
#[inline]
fn mul(self, rhs: Vec3) -> Self::Output {
self.transform_point(rhs).into()
}
}
impl Mul<Dir3> for Isometry3d {
type Output = Dir3;
#[inline]
fn mul(self, rhs: Dir3) -> Self::Output {
self.rotation * rhs
}
}
#[cfg(feature = "approx")]
impl AbsDiffEq for Isometry3d {
type Epsilon = <f32 as AbsDiffEq>::Epsilon;
fn default_epsilon() -> Self::Epsilon {
f32::default_epsilon()
}
fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
self.rotation.abs_diff_eq(other.rotation, epsilon)
&& self.translation.abs_diff_eq(other.translation, epsilon)
}
}
#[cfg(feature = "approx")]
impl RelativeEq for Isometry3d {
fn default_max_relative() -> Self::Epsilon {
Self::default_epsilon()
}
fn relative_eq(
&self,
other: &Self,
epsilon: Self::Epsilon,
max_relative: Self::Epsilon,
) -> bool {
self.rotation
.relative_eq(&other.rotation, epsilon, max_relative)
&& self
.translation
.relative_eq(&other.translation, epsilon, max_relative)
}
}
#[cfg(feature = "approx")]
impl UlpsEq for Isometry3d {
fn default_max_ulps() -> u32 {
4
}
fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
self.rotation.ulps_eq(&other.rotation, epsilon, max_ulps)
&& self
.translation
.ulps_eq(&other.translation, epsilon, max_ulps)
}
}
#[cfg(test)]
#[cfg(feature = "approx")]
mod tests {
use super::*;
use crate::{vec2, vec3, vec3a};
use approx::assert_abs_diff_eq;
use core::f32::consts::{FRAC_PI_2, FRAC_PI_3};
#[test]
fn mul_2d() {
let iso1 = Isometry2d::new(vec2(1.0, 0.0), Rot2::FRAC_PI_2);
let iso2 = Isometry2d::new(vec2(0.0, 1.0), Rot2::FRAC_PI_2);
let expected = Isometry2d::new(vec2(0.0, 0.0), Rot2::PI);
assert_abs_diff_eq!(iso1 * iso2, expected);
}
#[test]
fn inverse_mul_2d() {
let iso1 = Isometry2d::new(vec2(1.0, 0.0), Rot2::FRAC_PI_2);
let iso2 = Isometry2d::new(vec2(0.0, 0.0), Rot2::PI);
let expected = Isometry2d::new(vec2(0.0, 1.0), Rot2::FRAC_PI_2);
assert_abs_diff_eq!(iso1.inverse_mul(iso2), expected);
}
#[test]
fn mul_3d() {
let iso1 = Isometry3d::new(vec3(1.0, 0.0, 0.0), Quat::from_rotation_x(FRAC_PI_2));
let iso2 = Isometry3d::new(vec3(0.0, 1.0, 0.0), Quat::IDENTITY);
let expected = Isometry3d::new(vec3(1.0, 0.0, 1.0), Quat::from_rotation_x(FRAC_PI_2));
assert_abs_diff_eq!(iso1 * iso2, expected);
}
#[test]
fn inverse_mul_3d() {
let iso1 = Isometry3d::new(vec3(1.0, 0.0, 0.0), Quat::from_rotation_x(FRAC_PI_2));
let iso2 = Isometry3d::new(vec3(1.0, 0.0, 1.0), Quat::from_rotation_x(FRAC_PI_2));
let expected = Isometry3d::new(vec3(0.0, 1.0, 0.0), Quat::IDENTITY);
assert_abs_diff_eq!(iso1.inverse_mul(iso2), expected);
}
#[test]
fn identity_2d() {
let iso = Isometry2d::new(vec2(-1.0, -0.5), Rot2::degrees(75.0));
assert_abs_diff_eq!(Isometry2d::IDENTITY * iso, iso);
assert_abs_diff_eq!(iso * Isometry2d::IDENTITY, iso);
}
#[test]
fn identity_3d() {
let iso = Isometry3d::new(vec3(-1.0, 2.5, 3.3), Quat::from_rotation_z(FRAC_PI_3));
assert_abs_diff_eq!(Isometry3d::IDENTITY * iso, iso);
assert_abs_diff_eq!(iso * Isometry3d::IDENTITY, iso);
}
#[test]
fn inverse_2d() {
let iso = Isometry2d::new(vec2(-1.0, -0.5), Rot2::degrees(75.0));
let inv = iso.inverse();
assert_abs_diff_eq!(iso * inv, Isometry2d::IDENTITY);
assert_abs_diff_eq!(inv * iso, Isometry2d::IDENTITY);
}
#[test]
fn inverse_3d() {
let iso = Isometry3d::new(vec3(-1.0, 2.5, 3.3), Quat::from_rotation_z(FRAC_PI_3));
let inv = iso.inverse();
assert_abs_diff_eq!(iso * inv, Isometry3d::IDENTITY);
assert_abs_diff_eq!(inv * iso, Isometry3d::IDENTITY);
}
#[test]
fn transform_2d() {
let iso = Isometry2d::new(vec2(0.5, -0.5), Rot2::FRAC_PI_2);
let point = vec2(1.0, 1.0);
assert_abs_diff_eq!(vec2(-0.5, 0.5), iso * point);
}
#[test]
fn inverse_transform_2d() {
let iso = Isometry2d::new(vec2(0.5, -0.5), Rot2::FRAC_PI_2);
let point = vec2(-0.5, 0.5);
assert_abs_diff_eq!(vec2(1.0, 1.0), iso.inverse_transform_point(point));
}
#[test]
fn transform_3d() {
let iso = Isometry3d::new(vec3(1.0, 0.0, 0.0), Quat::from_rotation_y(FRAC_PI_2));
let point = vec3(1.0, 1.0, 1.0);
assert_abs_diff_eq!(vec3(2.0, 1.0, -1.0), iso * point);
}
#[test]
fn inverse_transform_3d() {
let iso = Isometry3d::new(vec3(1.0, 0.0, 0.0), Quat::from_rotation_y(FRAC_PI_2));
let point = vec3(2.0, 1.0, -1.0);
assert_abs_diff_eq!(vec3a(1.0, 1.0, 1.0), iso.inverse_transform_point(point));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/ray.rs | crates/bevy_math/src/ray.rs | use crate::{
ops,
primitives::{InfinitePlane3d, Plane2d},
Dir2, Dir3, Vec2, Vec3,
};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
#[cfg(all(feature = "serialize", feature = "bevy_reflect"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
/// An infinite half-line starting at `origin` and going in `direction` in 2D space.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Deserialize, Serialize)
)]
pub struct Ray2d {
/// The origin of the ray.
pub origin: Vec2,
/// The direction of the ray.
pub direction: Dir2,
}
impl Ray2d {
/// Create a new `Ray2d` from a given origin and direction
#[inline]
pub const fn new(origin: Vec2, direction: Dir2) -> Self {
Self { origin, direction }
}
/// Get a point at a given distance along the ray
#[inline]
pub fn get_point(&self, distance: f32) -> Vec2 {
self.origin + *self.direction * distance
}
/// Get the distance to a plane if the ray intersects it
#[inline]
pub fn intersect_plane(&self, plane_origin: Vec2, plane: Plane2d) -> Option<f32> {
let denominator = plane.normal.dot(*self.direction);
if ops::abs(denominator) > f32::EPSILON {
let distance = (plane_origin - self.origin).dot(*plane.normal) / denominator;
if distance > f32::EPSILON {
return Some(distance);
}
}
None
}
}
/// An infinite half-line starting at `origin` and going in `direction` in 3D space.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Deserialize, Serialize)
)]
pub struct Ray3d {
/// The origin of the ray.
pub origin: Vec3,
/// The direction of the ray.
pub direction: Dir3,
}
impl Ray3d {
/// Create a new `Ray3d` from a given origin and direction
#[inline]
pub const fn new(origin: Vec3, direction: Dir3) -> Self {
Self { origin, direction }
}
/// Get a point at a given distance along the ray
#[inline]
pub fn get_point(&self, distance: f32) -> Vec3 {
self.origin + *self.direction * distance
}
/// Get the distance to a plane if the ray intersects it
#[inline]
pub fn intersect_plane(&self, plane_origin: Vec3, plane: InfinitePlane3d) -> Option<f32> {
let denominator = plane.normal.dot(*self.direction);
if ops::abs(denominator) > f32::EPSILON {
let distance = (plane_origin - self.origin).dot(*plane.normal) / denominator;
if distance > f32::EPSILON {
return Some(distance);
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn intersect_plane_2d() {
let ray = Ray2d::new(Vec2::ZERO, Dir2::Y);
// Orthogonal, and test that an inverse plane_normal has the same result
assert_eq!(
ray.intersect_plane(Vec2::Y, Plane2d::new(Vec2::Y)),
Some(1.0)
);
assert_eq!(
ray.intersect_plane(Vec2::Y, Plane2d::new(Vec2::NEG_Y)),
Some(1.0)
);
assert!(ray
.intersect_plane(Vec2::NEG_Y, Plane2d::new(Vec2::Y))
.is_none());
assert!(ray
.intersect_plane(Vec2::NEG_Y, Plane2d::new(Vec2::NEG_Y))
.is_none());
// Diagonal
assert_eq!(
ray.intersect_plane(Vec2::Y, Plane2d::new(Vec2::ONE)),
Some(1.0)
);
assert!(ray
.intersect_plane(Vec2::NEG_Y, Plane2d::new(Vec2::ONE))
.is_none());
// Parallel
assert!(ray
.intersect_plane(Vec2::X, Plane2d::new(Vec2::X))
.is_none());
// Parallel with simulated rounding error
assert!(ray
.intersect_plane(Vec2::X, Plane2d::new(Vec2::X + Vec2::Y * f32::EPSILON))
.is_none());
}
#[test]
fn intersect_plane_3d() {
let ray = Ray3d::new(Vec3::ZERO, Dir3::Z);
// Orthogonal, and test that an inverse plane_normal has the same result
assert_eq!(
ray.intersect_plane(Vec3::Z, InfinitePlane3d::new(Vec3::Z)),
Some(1.0)
);
assert_eq!(
ray.intersect_plane(Vec3::Z, InfinitePlane3d::new(Vec3::NEG_Z)),
Some(1.0)
);
assert!(ray
.intersect_plane(Vec3::NEG_Z, InfinitePlane3d::new(Vec3::Z))
.is_none());
assert!(ray
.intersect_plane(Vec3::NEG_Z, InfinitePlane3d::new(Vec3::NEG_Z))
.is_none());
// Diagonal
assert_eq!(
ray.intersect_plane(Vec3::Z, InfinitePlane3d::new(Vec3::ONE)),
Some(1.0)
);
assert!(ray
.intersect_plane(Vec3::NEG_Z, InfinitePlane3d::new(Vec3::ONE))
.is_none());
// Parallel
assert!(ray
.intersect_plane(Vec3::X, InfinitePlane3d::new(Vec3::X))
.is_none());
// Parallel with simulated rounding error
assert!(ray
.intersect_plane(
Vec3::X,
InfinitePlane3d::new(Vec3::X + Vec3::Z * f32::EPSILON)
)
.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_math/src/rotation2d.rs | crates/bevy_math/src/rotation2d.rs | use core::f32::consts::TAU;
use glam::FloatExt;
use crate::{
ops,
prelude::{Mat2, Vec2},
};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
#[cfg(all(feature = "serialize", feature = "bevy_reflect"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
/// A 2D rotation.
///
/// # Example
///
/// ```
/// # use approx::assert_relative_eq;
/// # use bevy_math::{Rot2, Vec2};
/// use std::f32::consts::PI;
///
/// // Create rotations from counterclockwise angles in radians or degrees
/// let rotation1 = Rot2::radians(PI / 2.0);
/// let rotation2 = Rot2::degrees(45.0);
///
/// // Get the angle back as radians or degrees
/// assert_eq!(rotation1.as_degrees(), 90.0);
/// assert_eq!(rotation2.as_radians(), PI / 4.0);
///
/// // "Add" rotations together using `*`
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(rotation1 * rotation2, Rot2::degrees(135.0));
///
/// // Rotate vectors
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(rotation1 * Vec2::X, Vec2::Y);
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
#[doc(alias = "rotation", alias = "rotation2d", alias = "rotation_2d")]
pub struct Rot2 {
/// The cosine of the rotation angle.
///
/// This is the real part of the unit complex number representing the rotation.
pub cos: f32,
/// The sine of the rotation angle.
///
/// This is the imaginary part of the unit complex number representing the rotation.
pub sin: f32,
}
impl Default for Rot2 {
fn default() -> Self {
Self::IDENTITY
}
}
impl Rot2 {
/// No rotation.
/// Also equals a full turn that returns back to its original position.
/// ```
/// # use approx::assert_relative_eq;
/// # use bevy_math::Rot2;
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(Rot2::IDENTITY, Rot2::degrees(360.0), epsilon = 2e-7);
/// ```
pub const IDENTITY: Self = Self { cos: 1.0, sin: 0.0 };
/// A rotation of π radians.
/// Corresponds to a half-turn.
pub const PI: Self = Self {
cos: -1.0,
sin: 0.0,
};
/// A counterclockwise rotation of π/2 radians.
/// Corresponds to a counterclockwise quarter-turn.
pub const FRAC_PI_2: Self = Self { cos: 0.0, sin: 1.0 };
/// A counterclockwise rotation of π/3 radians.
/// Corresponds to a counterclockwise turn by 60°.
pub const FRAC_PI_3: Self = Self {
cos: 0.5,
sin: 0.866_025_4,
};
/// A counterclockwise rotation of π/4 radians.
/// Corresponds to a counterclockwise turn by 45°.
pub const FRAC_PI_4: Self = Self {
cos: core::f32::consts::FRAC_1_SQRT_2,
sin: core::f32::consts::FRAC_1_SQRT_2,
};
/// A counterclockwise rotation of π/6 radians.
/// Corresponds to a counterclockwise turn by 30°.
pub const FRAC_PI_6: Self = Self {
cos: 0.866_025_4,
sin: 0.5,
};
/// A counterclockwise rotation of π/8 radians.
/// Corresponds to a counterclockwise turn by 22.5°.
pub const FRAC_PI_8: Self = Self {
cos: 0.923_879_5,
sin: 0.382_683_43,
};
/// Creates a [`Rot2`] from a counterclockwise angle in radians.
/// A negative argument corresponds to a clockwise rotation.
///
/// # Note
///
/// Angles larger than or equal to 2π (in either direction) loop around to smaller rotations, since a full rotation returns an object to its starting orientation.
///
/// # Example
///
/// ```
/// # use bevy_math::Rot2;
/// # use approx::assert_relative_eq;
/// # use std::f32::consts::{FRAC_PI_2, PI};
///
/// let rot1 = Rot2::radians(3.0 * FRAC_PI_2);
/// let rot2 = Rot2::radians(-FRAC_PI_2);
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(rot1, rot2);
///
/// let rot3 = Rot2::radians(PI);
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(rot1 * rot1, rot3);
///
/// // A rotation by 3π and 1π are the same
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(Rot2::radians(3.0 * PI), Rot2::radians(PI));
/// ```
#[inline]
pub fn radians(radians: f32) -> Self {
let (sin, cos) = ops::sin_cos(radians);
Self::from_sin_cos(sin, cos)
}
/// Creates a [`Rot2`] from a counterclockwise angle in degrees.
/// A negative argument corresponds to a clockwise rotation.
///
/// # Note
///
/// Angles larger than or equal to 360° (in either direction) loop around to smaller rotations, since a full rotation returns an object to its starting orientation.
///
/// # Example
///
/// ```
/// # use bevy_math::Rot2;
/// # use approx::{assert_relative_eq, assert_abs_diff_eq};
///
/// let rot1 = Rot2::degrees(270.0);
/// let rot2 = Rot2::degrees(-90.0);
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(rot1, rot2);
///
/// let rot3 = Rot2::degrees(180.0);
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(rot1 * rot1, rot3);
///
/// // A rotation by 365° and 5° are the same
/// #[cfg(feature = "approx")]
/// assert_abs_diff_eq!(Rot2::degrees(365.0), Rot2::degrees(5.0), epsilon = 2e-7);
/// ```
#[inline]
pub fn degrees(degrees: f32) -> Self {
Self::radians(degrees.to_radians())
}
/// Creates a [`Rot2`] from a counterclockwise fraction of a full turn of 360 degrees.
/// A negative argument corresponds to a clockwise rotation.
///
/// # Note
///
/// Angles larger than or equal to 1 turn (in either direction) loop around to smaller rotations, since a full rotation returns an object to its starting orientation.
///
/// # Example
///
/// ```
/// # use bevy_math::Rot2;
/// # use approx::assert_relative_eq;
///
/// let rot1 = Rot2::turn_fraction(0.75);
/// let rot2 = Rot2::turn_fraction(-0.25);
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(rot1, rot2);
///
/// let rot3 = Rot2::turn_fraction(0.5);
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(rot1 * rot1, rot3);
///
/// // A rotation by 1.5 turns and 0.5 turns are the same
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(Rot2::turn_fraction(1.5), Rot2::turn_fraction(0.5));
/// ```
#[inline]
pub fn turn_fraction(fraction: f32) -> Self {
Self::radians(TAU * fraction)
}
/// Creates a [`Rot2`] from the sine and cosine of an angle.
///
/// The rotation is only valid if `sin * sin + cos * cos == 1.0`.
///
/// # Panics
///
/// Panics if `sin * sin + cos * cos != 1.0` when the `glam_assert` feature is enabled.
#[inline]
pub fn from_sin_cos(sin: f32, cos: f32) -> Self {
let rotation = Self { sin, cos };
debug_assert!(
rotation.is_normalized(),
"the given sine and cosine produce an invalid rotation"
);
rotation
}
/// Returns a corresponding rotation angle in radians in the `(-pi, pi]` range.
#[inline]
pub fn as_radians(self) -> f32 {
ops::atan2(self.sin, self.cos)
}
/// Returns a corresponding rotation angle in degrees in the `(-180, 180]` range.
#[inline]
pub fn as_degrees(self) -> f32 {
self.as_radians().to_degrees()
}
/// Returns a corresponding rotation angle as a fraction of a full 360 degree turn in the `(-0.5, 0.5]` range.
#[inline]
pub fn as_turn_fraction(self) -> f32 {
self.as_radians() / TAU
}
/// Returns the sine and cosine of the rotation angle.
#[inline]
pub const fn sin_cos(self) -> (f32, f32) {
(self.sin, self.cos)
}
/// Computes the length or norm of the complex number used to represent the rotation.
///
/// The length is typically expected to be `1.0`. Unexpectedly denormalized rotations
/// can be a result of incorrect construction or floating point error caused by
/// successive operations.
#[inline]
#[doc(alias = "norm")]
pub fn length(self) -> f32 {
Vec2::new(self.sin, self.cos).length()
}
/// Computes the squared length or norm of the complex number used to represent the rotation.
///
/// This is generally faster than [`Rot2::length()`], as it avoids a square
/// root operation.
///
/// The length is typically expected to be `1.0`. Unexpectedly denormalized rotations
/// can be a result of incorrect construction or floating point error caused by
/// successive operations.
#[inline]
#[doc(alias = "norm2")]
pub fn length_squared(self) -> f32 {
Vec2::new(self.sin, self.cos).length_squared()
}
/// Computes `1.0 / self.length()`.
///
/// For valid results, `self` must _not_ have a length of zero.
#[inline]
pub fn length_recip(self) -> f32 {
Vec2::new(self.sin, self.cos).length_recip()
}
/// Returns `self` with a length of `1.0` if possible, and `None` otherwise.
///
/// `None` will be returned if the sine and cosine of `self` are both zero (or very close to zero),
/// or if either of them is NaN or infinite.
///
/// Note that [`Rot2`] should typically already be normalized by design.
/// Manual normalization is only needed when successive operations result in
/// accumulated floating point error, or if the rotation was constructed
/// with invalid values.
#[inline]
pub fn try_normalize(self) -> Option<Self> {
let recip = self.length_recip();
if recip.is_finite() && recip > 0.0 {
Some(Self::from_sin_cos(self.sin * recip, self.cos * recip))
} else {
None
}
}
/// Returns `self` with a length of `1.0`.
///
/// Note that [`Rot2`] should typically already be normalized by design.
/// Manual normalization is only needed when successive operations result in
/// accumulated floating point error, or if the rotation was constructed
/// with invalid values.
///
/// # Panics
///
/// Panics if `self` has a length of zero, NaN, or infinity when debug assertions are enabled.
#[inline]
pub fn normalize(self) -> Self {
let length_recip = self.length_recip();
Self::from_sin_cos(self.sin * length_recip, self.cos * length_recip)
}
/// Returns `self` after an approximate normalization, assuming the value is already nearly normalized.
/// Useful for preventing numerical error accumulation.
/// See [`Dir3::fast_renormalize`](crate::Dir3::fast_renormalize) for an example of when such error accumulation might occur.
#[inline]
pub fn fast_renormalize(self) -> Self {
let length_squared = self.length_squared();
// Based on a Taylor approximation of the inverse square root, see [`Dir3::fast_renormalize`](crate::Dir3::fast_renormalize) for more details.
let length_recip_approx = 0.5 * (3.0 - length_squared);
Rot2 {
sin: self.sin * length_recip_approx,
cos: self.cos * length_recip_approx,
}
}
/// Returns `true` if the rotation is neither infinite nor NaN.
#[inline]
pub const fn is_finite(self) -> bool {
self.sin.is_finite() && self.cos.is_finite()
}
/// Returns `true` if the rotation is NaN.
#[inline]
pub const fn is_nan(self) -> bool {
self.sin.is_nan() || self.cos.is_nan()
}
/// Returns whether `self` has a length of `1.0` or not.
///
/// Uses a precision threshold of approximately `1e-4`.
#[inline]
pub fn is_normalized(self) -> bool {
// The allowed length is 1 +/- 1e-4, so the largest allowed
// squared length is (1 + 1e-4)^2 = 1.00020001, which makes
// the threshold for the squared length approximately 2e-4.
ops::abs(self.length_squared() - 1.0) <= 2e-4
}
/// Returns `true` if the rotation is near [`Rot2::IDENTITY`].
#[inline]
pub fn is_near_identity(self) -> bool {
// Same as `Quat::is_near_identity`, but using sine and cosine
let threshold_angle_sin = 0.000_049_692_047; // let threshold_angle = 0.002_847_144_6;
self.cos > 0.0 && ops::abs(self.sin) < threshold_angle_sin
}
/// Returns the angle in radians needed to make `self` and `other` coincide.
#[inline]
pub fn angle_to(self, other: Self) -> f32 {
(other * self.inverse()).as_radians()
}
/// Returns the inverse of the rotation. This is also the conjugate
/// of the unit complex number representing the rotation.
#[inline]
#[must_use]
#[doc(alias = "conjugate")]
pub const fn inverse(self) -> Self {
Self {
cos: self.cos,
sin: -self.sin,
}
}
/// Performs a linear interpolation between `self` and `rhs` based on
/// the value `s`, and normalizes the rotation afterwards.
///
/// When `s == 0.0`, the result will be equal to `self`.
/// When `s == 1.0`, the result will be equal to `rhs`.
///
/// This is slightly more efficient than [`slerp`](Self::slerp), and produces a similar result
/// when the difference between the two rotations is small. At larger differences,
/// the result resembles a kind of ease-in-out effect.
///
/// If you would like the angular velocity to remain constant, consider using [`slerp`](Self::slerp) instead.
///
/// # Details
///
/// `nlerp` corresponds to computing an angle for a point at position `s` on a line drawn
/// between the endpoints of the arc formed by `self` and `rhs` on a unit circle,
/// and normalizing the result afterwards.
///
/// Note that if the angles are opposite like 0 and π, the line will pass through the origin,
/// and the resulting angle will always be either `self` or `rhs` depending on `s`.
/// If `s` happens to be `0.5` in this case, a valid rotation cannot be computed, and `self`
/// will be returned as a fallback.
///
/// # Example
///
/// ```
/// # use bevy_math::Rot2;
/// #
/// let rot1 = Rot2::IDENTITY;
/// let rot2 = Rot2::degrees(135.0);
///
/// let result1 = rot1.nlerp(rot2, 1.0 / 3.0);
/// assert_eq!(result1.as_degrees(), 28.675055);
///
/// let result2 = rot1.nlerp(rot2, 0.5);
/// assert_eq!(result2.as_degrees(), 67.5);
/// ```
#[inline]
pub fn nlerp(self, end: Self, s: f32) -> Self {
Self {
sin: self.sin.lerp(end.sin, s),
cos: self.cos.lerp(end.cos, s),
}
.try_normalize()
// Fall back to the start rotation.
// This can happen when `self` and `end` are opposite angles and `s == 0.5`,
// because the resulting rotation would be zero, which cannot be normalized.
.unwrap_or(self)
}
/// Performs a spherical linear interpolation between `self` and `end`
/// based on the value `s`.
///
/// This corresponds to interpolating between the two angles at a constant angular velocity.
///
/// When `s == 0.0`, the result will be equal to `self`.
/// When `s == 1.0`, the result will be equal to `rhs`.
///
/// If you would like the rotation to have a kind of ease-in-out effect, consider
/// using the slightly more efficient [`nlerp`](Self::nlerp) instead.
///
/// # Example
///
/// ```
/// # use bevy_math::Rot2;
/// #
/// let rot1 = Rot2::IDENTITY;
/// let rot2 = Rot2::degrees(135.0);
///
/// let result1 = rot1.slerp(rot2, 1.0 / 3.0);
/// assert_eq!(result1.as_degrees(), 45.0);
///
/// let result2 = rot1.slerp(rot2, 0.5);
/// assert_eq!(result2.as_degrees(), 67.5);
/// ```
#[inline]
pub fn slerp(self, end: Self, s: f32) -> Self {
self * Self::radians(self.angle_to(end) * s)
}
}
impl From<f32> for Rot2 {
/// Creates a [`Rot2`] from a counterclockwise angle in radians.
fn from(rotation: f32) -> Self {
Self::radians(rotation)
}
}
impl From<Rot2> for Mat2 {
/// Creates a [`Mat2`] rotation matrix from a [`Rot2`].
fn from(rot: Rot2) -> Self {
Mat2::from_cols_array(&[rot.cos, rot.sin, -rot.sin, rot.cos])
}
}
impl core::ops::Mul for Rot2 {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
Self {
cos: self.cos * rhs.cos - self.sin * rhs.sin,
sin: self.sin * rhs.cos + self.cos * rhs.sin,
}
}
}
impl core::ops::MulAssign for Rot2 {
fn mul_assign(&mut self, rhs: Self) {
*self = *self * rhs;
}
}
impl core::ops::Mul<Vec2> for Rot2 {
type Output = Vec2;
/// Rotates a [`Vec2`] by a [`Rot2`].
fn mul(self, rhs: Vec2) -> Self::Output {
Vec2::new(
rhs.x * self.cos - rhs.y * self.sin,
rhs.x * self.sin + rhs.y * self.cos,
)
}
}
#[cfg(any(feature = "approx", test))]
impl approx::AbsDiffEq for Rot2 {
type Epsilon = f32;
fn default_epsilon() -> f32 {
f32::EPSILON
}
fn abs_diff_eq(&self, other: &Self, epsilon: f32) -> bool {
self.cos.abs_diff_eq(&other.cos, epsilon) && self.sin.abs_diff_eq(&other.sin, epsilon)
}
}
#[cfg(any(feature = "approx", test))]
impl approx::RelativeEq for Rot2 {
fn default_max_relative() -> f32 {
f32::EPSILON
}
fn relative_eq(&self, other: &Self, epsilon: f32, max_relative: f32) -> bool {
self.cos.relative_eq(&other.cos, epsilon, max_relative)
&& self.sin.relative_eq(&other.sin, epsilon, max_relative)
}
}
#[cfg(any(feature = "approx", test))]
impl approx::UlpsEq for Rot2 {
fn default_max_ulps() -> u32 {
4
}
fn ulps_eq(&self, other: &Self, epsilon: f32, max_ulps: u32) -> bool {
self.cos.ulps_eq(&other.cos, epsilon, max_ulps)
&& self.sin.ulps_eq(&other.sin, epsilon, max_ulps)
}
}
#[cfg(test)]
mod tests {
use core::f32::consts::FRAC_PI_2;
use approx::assert_relative_eq;
use crate::{ops, Dir2, Mat2, Rot2, Vec2};
#[test]
fn creation() {
let rotation1 = Rot2::radians(FRAC_PI_2);
let rotation2 = Rot2::degrees(90.0);
let rotation3 = Rot2::from_sin_cos(1.0, 0.0);
let rotation4 = Rot2::turn_fraction(0.25);
// All three rotations should be equal
assert_relative_eq!(rotation1.sin, rotation2.sin);
assert_relative_eq!(rotation1.cos, rotation2.cos);
assert_relative_eq!(rotation1.sin, rotation3.sin);
assert_relative_eq!(rotation1.cos, rotation3.cos);
assert_relative_eq!(rotation1.sin, rotation4.sin);
assert_relative_eq!(rotation1.cos, rotation4.cos);
// The rotation should be 90 degrees
assert_relative_eq!(rotation1.as_radians(), FRAC_PI_2);
assert_relative_eq!(rotation1.as_degrees(), 90.0);
assert_relative_eq!(rotation1.as_turn_fraction(), 0.25);
}
#[test]
fn rotate() {
let rotation = Rot2::degrees(90.0);
assert_relative_eq!(rotation * Vec2::X, Vec2::Y);
assert_relative_eq!(rotation * Dir2::Y, Dir2::NEG_X);
}
#[test]
fn rotation_range() {
// the rotation range is `(-180, 180]` and the constructors
// normalize the rotations to that range
assert_relative_eq!(Rot2::radians(3.0 * FRAC_PI_2), Rot2::radians(-FRAC_PI_2));
assert_relative_eq!(Rot2::degrees(270.0), Rot2::degrees(-90.0));
assert_relative_eq!(Rot2::turn_fraction(0.75), Rot2::turn_fraction(-0.25));
}
#[test]
fn add() {
let rotation1 = Rot2::degrees(90.0);
let rotation2 = Rot2::degrees(180.0);
// 90 deg + 180 deg becomes -90 deg after it wraps around to be within the `(-180, 180]` range
assert_eq!((rotation1 * rotation2).as_degrees(), -90.0);
}
#[test]
fn subtract() {
let rotation1 = Rot2::degrees(90.0);
let rotation2 = Rot2::degrees(45.0);
assert_relative_eq!((rotation1 * rotation2.inverse()).as_degrees(), 45.0);
// This should be equivalent to the above
assert_relative_eq!(rotation2.angle_to(rotation1), core::f32::consts::FRAC_PI_4);
}
#[test]
fn length() {
let rotation = Rot2 {
sin: 10.0,
cos: 5.0,
};
assert_eq!(rotation.length_squared(), 125.0);
assert_eq!(rotation.length(), 11.18034);
assert!(ops::abs(rotation.normalize().length() - 1.0) < 10e-7);
}
#[test]
fn is_near_identity() {
assert!(!Rot2::radians(0.1).is_near_identity());
assert!(!Rot2::radians(-0.1).is_near_identity());
assert!(Rot2::radians(0.00001).is_near_identity());
assert!(Rot2::radians(-0.00001).is_near_identity());
assert!(Rot2::radians(0.0).is_near_identity());
}
#[test]
fn normalize() {
let rotation = Rot2 {
sin: 10.0,
cos: 5.0,
};
let normalized_rotation = rotation.normalize();
assert_eq!(normalized_rotation.sin, 0.89442724);
assert_eq!(normalized_rotation.cos, 0.44721362);
assert!(!rotation.is_normalized());
assert!(normalized_rotation.is_normalized());
}
#[test]
fn fast_renormalize() {
let rotation = Rot2 { sin: 1.0, cos: 0.5 };
let normalized_rotation = rotation.normalize();
let mut unnormalized_rot = rotation;
let mut renormalized_rot = rotation;
let mut initially_normalized_rot = normalized_rotation;
let mut fully_normalized_rot = normalized_rotation;
// Compute a 64x (=2⁶) multiple of the rotation.
for _ in 0..6 {
unnormalized_rot = unnormalized_rot * unnormalized_rot;
renormalized_rot = renormalized_rot * renormalized_rot;
initially_normalized_rot = initially_normalized_rot * initially_normalized_rot;
fully_normalized_rot = fully_normalized_rot * fully_normalized_rot;
renormalized_rot = renormalized_rot.fast_renormalize();
fully_normalized_rot = fully_normalized_rot.normalize();
}
assert!(!unnormalized_rot.is_normalized());
assert!(renormalized_rot.is_normalized());
assert!(fully_normalized_rot.is_normalized());
assert_relative_eq!(fully_normalized_rot, renormalized_rot, epsilon = 0.000001);
assert_relative_eq!(
fully_normalized_rot,
unnormalized_rot.normalize(),
epsilon = 0.000001
);
assert_relative_eq!(
fully_normalized_rot,
initially_normalized_rot.normalize(),
epsilon = 0.000001
);
}
#[test]
fn try_normalize() {
// Valid
assert!(Rot2 {
sin: 10.0,
cos: 5.0,
}
.try_normalize()
.is_some());
// NaN
assert!(Rot2 {
sin: f32::NAN,
cos: 5.0,
}
.try_normalize()
.is_none());
// Zero
assert!(Rot2 { sin: 0.0, cos: 0.0 }.try_normalize().is_none());
// Non-finite
assert!(Rot2 {
sin: f32::INFINITY,
cos: 5.0,
}
.try_normalize()
.is_none());
}
#[test]
fn nlerp() {
let rot1 = Rot2::IDENTITY;
let rot2 = Rot2::degrees(135.0);
assert_eq!(rot1.nlerp(rot2, 1.0 / 3.0).as_degrees(), 28.675055);
assert!(rot1.nlerp(rot2, 0.0).is_near_identity());
assert_eq!(rot1.nlerp(rot2, 0.5).as_degrees(), 67.5);
assert_eq!(rot1.nlerp(rot2, 1.0).as_degrees(), 135.0);
let rot1 = Rot2::IDENTITY;
let rot2 = Rot2::from_sin_cos(0.0, -1.0);
assert!(rot1.nlerp(rot2, 1.0 / 3.0).is_near_identity());
assert!(rot1.nlerp(rot2, 0.0).is_near_identity());
// At 0.5, there is no valid rotation, so the fallback is the original angle.
assert_eq!(rot1.nlerp(rot2, 0.5).as_degrees(), 0.0);
assert_eq!(ops::abs(rot1.nlerp(rot2, 1.0).as_degrees()), 180.0);
}
#[test]
fn slerp() {
let rot1 = Rot2::IDENTITY;
let rot2 = Rot2::degrees(135.0);
assert_eq!(rot1.slerp(rot2, 1.0 / 3.0).as_degrees(), 45.0);
assert!(rot1.slerp(rot2, 0.0).is_near_identity());
assert_eq!(rot1.slerp(rot2, 0.5).as_degrees(), 67.5);
assert_eq!(rot1.slerp(rot2, 1.0).as_degrees(), 135.0);
let rot1 = Rot2::IDENTITY;
let rot2 = Rot2::from_sin_cos(0.0, -1.0);
assert!(ops::abs(rot1.slerp(rot2, 1.0 / 3.0).as_degrees() - 60.0) < 10e-6);
assert!(rot1.slerp(rot2, 0.0).is_near_identity());
assert_eq!(rot1.slerp(rot2, 0.5).as_degrees(), 90.0);
assert_eq!(ops::abs(rot1.slerp(rot2, 1.0).as_degrees()), 180.0);
}
#[test]
fn rotation_matrix() {
let rotation = Rot2::degrees(90.0);
let matrix: Mat2 = rotation.into();
// Check that the matrix is correct.
assert_relative_eq!(matrix.x_axis, Vec2::Y);
assert_relative_eq!(matrix.y_axis, Vec2::NEG_X);
// Check that the matrix rotates vectors correctly.
assert_relative_eq!(matrix * Vec2::X, Vec2::Y);
assert_relative_eq!(matrix * Vec2::Y, Vec2::NEG_X);
assert_relative_eq!(matrix * Vec2::NEG_X, Vec2::NEG_Y);
assert_relative_eq!(matrix * Vec2::NEG_Y, Vec2::X);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/common_traits.rs | crates/bevy_math/src/common_traits.rs | //! This module contains abstract mathematical traits shared by types used in `bevy_math`.
use crate::{ops, DVec2, DVec3, DVec4, Dir2, Dir3, Dir3A, Quat, Rot2, Vec2, Vec3, Vec3A, Vec4};
use core::{
convert::Infallible,
fmt::Debug,
ops::{Add, Div, Mul, Neg, Sub},
};
use thiserror::Error;
use variadics_please::all_tuples_enumerated;
/// A type that supports the mathematical operations of a real vector space, irrespective of dimension.
/// In particular, this means that the implementing type supports:
/// - Scalar multiplication and division on the right by elements of `Self::Scalar`
/// - Negation
/// - Addition and subtraction
/// - Zero
///
/// Within the limitations of floating point arithmetic, all the following are required to hold:
/// - (Associativity of addition) For all `u, v, w: Self`, `(u + v) + w == u + (v + w)`.
/// - (Commutativity of addition) For all `u, v: Self`, `u + v == v + u`.
/// - (Additive identity) For all `v: Self`, `v + Self::ZERO == v`.
/// - (Additive inverse) For all `v: Self`, `v - v == v + (-v) == Self::ZERO`.
/// - (Compatibility of multiplication) For all `a, b: Self::Scalar`, `v: Self`, `v * (a * b) == (v * a) * b`.
/// - (Multiplicative identity) For all `v: Self`, `v * 1.0 == v`.
/// - (Distributivity for vector addition) For all `a: Self::Scalar`, `u, v: Self`, `(u + v) * a == u * a + v * a`.
/// - (Distributivity for scalar addition) For all `a, b: Self::Scalar`, `v: Self`, `v * (a + b) == v * a + v * b`.
///
/// Note that, because implementing types use floating point arithmetic, they are not required to actually
/// implement `PartialEq` or `Eq`.
pub trait VectorSpace:
Mul<Self::Scalar, Output = Self>
+ Div<Self::Scalar, Output = Self>
+ Add<Self, Output = Self>
+ Sub<Self, Output = Self>
+ Neg<Output = Self>
+ Default
+ Debug
+ Clone
+ Copy
{
/// The scalar type of this vector space.
type Scalar: ScalarField;
/// The zero vector, which is the identity of addition for the vector space type.
const ZERO: Self;
/// Perform vector space linear interpolation between this element and another, based
/// on the parameter `t`. When `t` is `0`, `self` is recovered. When `t` is `1`, `rhs`
/// is recovered.
///
/// Note that the value of `t` is not clamped by this function, so extrapolating outside
/// of the interval `[0,1]` is allowed.
#[inline]
fn lerp(self, rhs: Self, t: Self::Scalar) -> Self {
self * (Self::Scalar::ONE - t) + rhs * t
}
}
impl VectorSpace for Vec4 {
type Scalar = f32;
const ZERO: Self = Vec4::ZERO;
}
impl VectorSpace for Vec3 {
type Scalar = f32;
const ZERO: Self = Vec3::ZERO;
}
impl VectorSpace for Vec3A {
type Scalar = f32;
const ZERO: Self = Vec3A::ZERO;
}
impl VectorSpace for Vec2 {
type Scalar = f32;
const ZERO: Self = Vec2::ZERO;
}
impl VectorSpace for DVec4 {
type Scalar = f64;
const ZERO: Self = DVec4::ZERO;
}
impl VectorSpace for DVec3 {
type Scalar = f64;
const ZERO: Self = DVec3::ZERO;
}
impl VectorSpace for DVec2 {
type Scalar = f64;
const ZERO: Self = DVec2::ZERO;
}
// Every scalar field is a 1-dimensional vector space over itself.
impl<T: ScalarField> VectorSpace for T {
type Scalar = Self;
const ZERO: Self = Self::ZERO;
}
/// A type that supports the operations of a scalar field. An implementation should support:
/// - Addition and subtraction
/// - Multiplication and division
/// - Negation
/// - Zero (additive identity)
/// - One (multiplicative identity)
///
/// Within the limitations of floating point arithmetic, all the following are required to hold:
/// - (Associativity of addition) For all `u, v, w: Self`, `(u + v) + w == u + (v + w)`.
/// - (Commutativity of addition) For all `u, v: Self`, `u + v == v + u`.
/// - (Additive identity) For all `v: Self`, `v + Self::ZERO == v`.
/// - (Additive inverse) For all `v: Self`, `v - v == v + (-v) == Self::ZERO`.
/// - (Associativity of multiplication) For all `u, v, w: Self`, `(u * v) * w == u * (v * w)`.
/// - (Commutativity of multiplication) For all `u, v: Self`, `u * v == v * u`.
/// - (Multiplicative identity) For all `v: Self`, `v * Self::ONE == v`.
/// - (Multiplicative inverse) For all `v: Self`, `v / v == v * v.inverse() == Self::ONE`.
/// - (Distributivity over addition) For all `a, b: Self`, `u, v: Self`, `(u + v) * a == u * a + v * a`.
pub trait ScalarField:
Mul<Self, Output = Self>
+ Div<Self, Output = Self>
+ Add<Self, Output = Self>
+ Sub<Self, Output = Self>
+ Neg<Output = Self>
+ Default
+ Debug
+ Clone
+ Copy
{
/// The additive identity.
const ZERO: Self;
/// The multiplicative identity.
const ONE: Self;
/// The multiplicative inverse of this element. This is equivalent to `1.0 / self`.
fn recip(self) -> Self {
Self::ONE / self
}
}
impl ScalarField for f32 {
const ZERO: Self = 0.0;
const ONE: Self = 1.0;
}
impl ScalarField for f64 {
const ZERO: Self = 0.0;
const ONE: Self = 1.0;
}
/// A type consisting of formal sums of elements from `V` and `W`. That is,
/// each value `Sum(v, w)` is thought of as `v + w`, with no available
/// simplification. In particular, if `V` and `W` are [vector spaces], then
/// `Sum<V, W>` is a vector space whose dimension is the sum of those of `V`
/// and `W`, and the field accessors `.0` and `.1` are vector space projections.
///
/// [vector spaces]: VectorSpace
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
pub struct Sum<V, W>(pub V, pub W);
impl<F: ScalarField, V, W> Mul<F> for Sum<V, W>
where
V: VectorSpace<Scalar = F>,
W: VectorSpace<Scalar = F>,
{
type Output = Self;
fn mul(self, rhs: F) -> Self::Output {
Sum(self.0 * rhs, self.1 * rhs)
}
}
impl<F: ScalarField, V, W> Div<F> for Sum<V, W>
where
V: VectorSpace<Scalar = F>,
W: VectorSpace<Scalar = F>,
{
type Output = Self;
fn div(self, rhs: F) -> Self::Output {
Sum(self.0 / rhs, self.1 / rhs)
}
}
impl<V, W> Add<Self> for Sum<V, W>
where
V: VectorSpace,
W: VectorSpace,
{
type Output = Self;
fn add(self, other: Self) -> Self::Output {
Sum(self.0 + other.0, self.1 + other.1)
}
}
impl<V, W> Sub<Self> for Sum<V, W>
where
V: VectorSpace,
W: VectorSpace,
{
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
Sum(self.0 - other.0, self.1 - other.1)
}
}
impl<V, W> Neg for Sum<V, W>
where
V: VectorSpace,
W: VectorSpace,
{
type Output = Self;
fn neg(self) -> Self::Output {
Sum(-self.0, -self.1)
}
}
impl<V, W> Default for Sum<V, W>
where
V: VectorSpace,
W: VectorSpace,
{
fn default() -> Self {
Sum(V::default(), W::default())
}
}
impl<F: ScalarField, V, W> VectorSpace for Sum<V, W>
where
V: VectorSpace<Scalar = F>,
W: VectorSpace<Scalar = F>,
{
type Scalar = F;
const ZERO: Self = Sum(V::ZERO, W::ZERO);
}
/// A type that supports the operations of a normed vector space; i.e. a norm operation in addition
/// to those of [`VectorSpace`]. Specifically, the implementor must guarantee that the following
/// relationships hold, within the limitations of floating point arithmetic:
/// - (Nonnegativity) For all `v: Self`, `v.norm() >= 0.0`.
/// - (Positive definiteness) For all `v: Self`, `v.norm() == 0.0` implies `v == Self::ZERO`.
/// - (Absolute homogeneity) For all `c: Self::Scalar`, `v: Self`, `(v * c).norm() == v.norm() * c.abs()`.
/// - (Triangle inequality) For all `v, w: Self`, `(v + w).norm() <= v.norm() + w.norm()`.
///
/// Note that, because implementing types use floating point arithmetic, they are not required to actually
/// implement `PartialEq` or `Eq`.
pub trait NormedVectorSpace: VectorSpace {
/// The size of this element. The return value should always be nonnegative.
fn norm(self) -> Self::Scalar;
/// The squared norm of this element. Computing this is often faster than computing
/// [`NormedVectorSpace::norm`].
#[inline]
fn norm_squared(self) -> Self::Scalar {
self.norm() * self.norm()
}
/// The distance between this element and another, as determined by the norm.
#[inline]
fn distance(self, rhs: Self) -> Self::Scalar {
(rhs - self).norm()
}
/// The squared distance between this element and another, as determined by the norm. Note that
/// this is often faster to compute in practice than [`NormedVectorSpace::distance`].
#[inline]
fn distance_squared(self, rhs: Self) -> Self::Scalar {
(rhs - self).norm_squared()
}
}
impl NormedVectorSpace for Vec4 {
#[inline]
fn norm(self) -> f32 {
self.length()
}
#[inline]
fn norm_squared(self) -> f32 {
self.length_squared()
}
}
impl NormedVectorSpace for Vec3 {
#[inline]
fn norm(self) -> f32 {
self.length()
}
#[inline]
fn norm_squared(self) -> f32 {
self.length_squared()
}
}
impl NormedVectorSpace for Vec3A {
#[inline]
fn norm(self) -> f32 {
self.length()
}
#[inline]
fn norm_squared(self) -> f32 {
self.length_squared()
}
}
impl NormedVectorSpace for Vec2 {
#[inline]
fn norm(self) -> f32 {
self.length()
}
#[inline]
fn norm_squared(self) -> f32 {
self.length_squared()
}
}
impl NormedVectorSpace for f32 {
#[inline]
fn norm(self) -> f32 {
ops::abs(self)
}
}
impl NormedVectorSpace for DVec4 {
#[inline]
fn norm(self) -> f64 {
self.length()
}
#[inline]
fn norm_squared(self) -> f64 {
self.length_squared()
}
}
impl NormedVectorSpace for DVec3 {
#[inline]
fn norm(self) -> f64 {
self.length()
}
#[inline]
fn norm_squared(self) -> f64 {
self.length_squared()
}
}
impl NormedVectorSpace for DVec2 {
#[inline]
fn norm(self) -> f64 {
self.length()
}
#[inline]
fn norm_squared(self) -> f64 {
self.length_squared()
}
}
impl NormedVectorSpace for f64 {
#[inline]
#[cfg(feature = "std")]
fn norm(self) -> f64 {
f64::abs(self)
}
#[inline]
#[cfg(all(any(feature = "libm", feature = "nostd-libm"), not(feature = "std")))]
fn norm(self) -> f64 {
libm::fabs(self)
}
}
/// A type with a natural interpolation that provides strong subdivision guarantees.
///
/// Although the only required method is `interpolate_stable`, many things are expected of it:
///
/// 1. The notion of interpolation should follow naturally from the semantics of the type, so
/// that inferring the interpolation mode from the type alone is sensible.
///
/// 2. The interpolation recovers something equivalent to the starting value at `t = 0.0`
/// and likewise with the ending value at `t = 1.0`. They do not have to be data-identical, but
/// they should be semantically identical. For example, [`Quat::slerp`] doesn't always yield its
/// second rotation input exactly at `t = 1.0`, but it always returns an equivalent rotation.
///
/// 3. Importantly, the interpolation must be *subdivision-stable*: for any interpolation curve
/// between two (unnamed) values and any parameter-value pairs `(t0, p)` and `(t1, q)`, the
/// interpolation curve between `p` and `q` must be the *linear* reparameterization of the original
/// interpolation curve restricted to the interval `[t0, t1]`.
///
/// The last of these conditions is very strong and indicates something like constant speed. It
/// is called "subdivision stability" because it guarantees that breaking up the interpolation
/// into segments and joining them back together has no effect.
///
/// Here is a diagram depicting it:
/// ```text
/// top curve = u.interpolate_stable(v, t)
///
/// t0 => p t1 => q
/// |-------------|---------|-------------|
/// 0 => u / \ 1 => v
/// / \
/// / \
/// / linear \
/// / reparameterization \
/// / t = t0 * (1 - s) + t1 * s \
/// / \
/// |-------------------------------------|
/// 0 => p 1 => q
///
/// bottom curve = p.interpolate_stable(q, s)
/// ```
///
/// Note that some common forms of interpolation do not satisfy this criterion. For example,
/// [`Quat::lerp`] and [`Rot2::nlerp`] are not subdivision-stable.
///
/// Furthermore, this is not to be used as a general trait for abstract interpolation.
/// Consumers rely on the strong guarantees in order for behavior based on this trait to be
/// well-behaved.
///
/// [`Quat::slerp`]: crate::Quat::slerp
/// [`Quat::lerp`]: crate::Quat::lerp
/// [`Rot2::nlerp`]: crate::Rot2::nlerp
pub trait StableInterpolate: Clone {
/// Interpolate between this value and the `other` given value using the parameter `t`. At
/// `t = 0.0`, a value equivalent to `self` is recovered, while `t = 1.0` recovers a value
/// equivalent to `other`, with intermediate values interpolating between the two.
/// See the [trait-level documentation] for details.
///
/// [trait-level documentation]: StableInterpolate
fn interpolate_stable(&self, other: &Self, t: f32) -> Self;
/// A version of [`interpolate_stable`] that assigns the result to `self` for convenience.
///
/// [`interpolate_stable`]: StableInterpolate::interpolate_stable
fn interpolate_stable_assign(&mut self, other: &Self, t: f32) {
*self = self.interpolate_stable(other, t);
}
/// Smoothly nudge this value towards the `target` at a given decay rate. The `decay_rate`
/// parameter controls how fast the distance between `self` and `target` decays relative to
/// the units of `delta`; the intended usage is for `decay_rate` to generally remain fixed,
/// while `delta` is something like `delta_time` from an updating system. This produces a
/// smooth following of the target that is independent of framerate.
///
/// More specifically, when this is called repeatedly, the result is that the distance between
/// `self` and a fixed `target` attenuates exponentially, with the rate of this exponential
/// decay given by `decay_rate`.
///
/// For example, at `decay_rate = 0.0`, this has no effect.
/// At `decay_rate = f32::INFINITY`, `self` immediately snaps to `target`.
/// In general, higher rates mean that `self` moves more quickly towards `target`.
///
/// # Example
/// ```
/// # use bevy_math::{Vec3, StableInterpolate};
/// # let delta_time: f32 = 1.0 / 60.0;
/// let mut object_position: Vec3 = Vec3::ZERO;
/// let target_position: Vec3 = Vec3::new(2.0, 3.0, 5.0);
/// // Decay rate of ln(10) => after 1 second, remaining distance is 1/10th
/// let decay_rate = f32::ln(10.0);
/// // Calling this repeatedly will move `object_position` towards `target_position`:
/// object_position.smooth_nudge(&target_position, decay_rate, delta_time);
/// ```
fn smooth_nudge(&mut self, target: &Self, decay_rate: f32, delta: f32) {
self.interpolate_stable_assign(target, 1.0 - ops::exp(-decay_rate * delta));
}
}
// Conservatively, we presently only apply this for normed vector spaces, where the notion
// of being constant-speed is literally true. The technical axioms are satisfied for any
// VectorSpace type, but the "natural from the semantics" part is less clear in general.
impl<V> StableInterpolate for V
where
V: NormedVectorSpace<Scalar = f32>,
{
#[inline]
fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
self.lerp(*other, t)
}
}
impl StableInterpolate for Rot2 {
#[inline]
fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
self.slerp(*other, t)
}
}
impl StableInterpolate for Quat {
#[inline]
fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
self.slerp(*other, t)
}
}
impl StableInterpolate for Dir2 {
#[inline]
fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
self.slerp(*other, t)
}
}
impl StableInterpolate for Dir3 {
#[inline]
fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
self.slerp(*other, t)
}
}
impl StableInterpolate for Dir3A {
#[inline]
fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
self.slerp(*other, t)
}
}
macro_rules! impl_stable_interpolate_tuple {
($(#[$meta:meta])* $(($n:tt, $T:ident)),*) => {
$(#[$meta])*
impl<$($T: StableInterpolate),*> StableInterpolate for ($($T,)*) {
fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
(
$(
<$T as StableInterpolate>::interpolate_stable(&self.$n, &other.$n, t),
)*
)
}
}
};
}
all_tuples_enumerated!(
#[doc(fake_variadic)]
impl_stable_interpolate_tuple,
1,
11,
T
);
/// Error produced when the values to be interpolated are not in the same units.
#[derive(Clone, Debug, Error)]
#[error("cannot interpolate between two values of different units")]
pub struct MismatchedUnitsError;
/// A trait that indicates that a value _may_ be interpolable via [`StableInterpolate`]. An
/// interpolation may fail if the values have different units - for example, attempting to
/// interpolate between [`Val::Px`] and [`Val::Percent`] will fail,
/// even though they are the same Rust type.
///
/// Fallible interpolation can be used for animated transitions, which can be set up to fail
/// gracefully if the the values cannot be interpolated. For example, the a transition could smoothly
/// go from `Val::Px(10)` to `Val::Px(20)`, but if the user attempts to go from `Val::Px(10)` to
/// `Val::Percent(10)`, the animation player can detect the failure and simply snap to the new
/// value without interpolating.
///
/// An animation clip system can incorporate fallible interpolation to support a broad set of
/// sequenced parameter values. This can include numeric types, which always interpolate,
/// enum types, which may or may not interpolate depending on the units, and non-interpolable
/// types, which always jump immediately to the new value without interpolation. This meaas, for
/// example, that you can have an animation track whose value type is a boolean or a string.
///
/// Interpolation for simple number and coordinate types will always succeed, as will any type
/// that implements [`StableInterpolate`]. Types which have different variants such as
/// [`Val`] and [`Color`] will only fail if the units are different.
/// Note that [`Color`] has its own, non-fallible mixing methods, but those entail
/// automatically converting between different color spaces, and is both expensive and complex.
/// [`TryStableInterpolate`] is more conservative, and doesn't automatically convert between
/// color spaces. This produces a color interpolation that has more predictable performance.
///
/// [`Val::Px`]: https://docs.rs/bevy/latest/bevy/ui/enum.Val.html#variant.Px
/// [`Val::Percent`]: https://docs.rs/bevy/latest/bevy/ui/enum.Val.html#variant.Percent
/// [`Val`]: https://docs.rs/bevy/latest/bevy/ui/enum.Val.html
/// [`Color`]: https://docs.rs/bevy/latest/bevy/color/enum.Color.html
pub trait TryStableInterpolate: Clone {
/// Error produced when the value cannot be interpolated.
type Error;
/// Attempt to interpolate the value. This may fail if the two interpolation values have
/// different units, or if the type is not interpolable.
fn try_interpolate_stable(&self, other: &Self, t: f32) -> Result<Self, Self::Error>;
}
impl<T: StableInterpolate> TryStableInterpolate for T {
type Error = Infallible;
fn try_interpolate_stable(&self, other: &Self, t: f32) -> Result<Self, Self::Error> {
Ok(self.interpolate_stable(other, t))
}
}
/// A type that has tangents.
pub trait HasTangent {
/// The tangent type.
type Tangent: VectorSpace;
}
/// A value with its derivative.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
pub struct WithDerivative<T>
where
T: HasTangent,
{
/// The underlying value.
pub value: T,
/// The derivative at `value`.
pub derivative: T::Tangent,
}
/// A value together with its first and second derivatives.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
pub struct WithTwoDerivatives<T>
where
T: HasTangent,
{
/// The underlying value.
pub value: T,
/// The derivative at `value`.
pub derivative: T::Tangent,
/// The second derivative at `value`.
pub second_derivative: <T::Tangent as HasTangent>::Tangent,
}
impl<V: VectorSpace> HasTangent for V {
type Tangent = V;
}
impl<F, U, V, M, N> HasTangent for (M, N)
where
F: ScalarField,
U: VectorSpace<Scalar = F>,
V: VectorSpace<Scalar = F>,
M: HasTangent<Tangent = U>,
N: HasTangent<Tangent = V>,
{
type Tangent = Sum<M::Tangent, N::Tangent>;
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/aspect_ratio.rs | crates/bevy_math/src/aspect_ratio.rs | //! Provides a simple aspect ratio struct to help with calculations.
use crate::Vec2;
use derive_more::derive::Into;
use thiserror::Error;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
/// An `AspectRatio` is the ratio of width to height.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Into)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
pub struct AspectRatio(f32);
impl AspectRatio {
/// Standard 16:9 aspect ratio
pub const SIXTEEN_NINE: Self = Self(16.0 / 9.0);
/// Standard 4:3 aspect ratio
pub const FOUR_THREE: Self = Self(4.0 / 3.0);
/// Standard 21:9 ultrawide aspect ratio
pub const ULTRAWIDE: Self = Self(21.0 / 9.0);
/// Attempts to create a new [`AspectRatio`] from a given width and height.
///
/// # Errors
///
/// Returns an `Err` with `AspectRatioError` if:
/// - Either width or height is zero (`AspectRatioError::Zero`)
/// - Either width or height is infinite (`AspectRatioError::Infinite`)
/// - Either width or height is NaN (`AspectRatioError::NaN`)
#[inline]
pub const fn try_new(width: f32, height: f32) -> Result<Self, AspectRatioError> {
match (width, height) {
(w, h) if w == 0.0 || h == 0.0 => Err(AspectRatioError::Zero),
(w, h) if w.is_infinite() || h.is_infinite() => Err(AspectRatioError::Infinite),
(w, h) if w.is_nan() || h.is_nan() => Err(AspectRatioError::NaN),
_ => Ok(Self(width / height)),
}
}
/// Attempts to create a new [`AspectRatio`] from a given amount of x pixels and y pixels.
#[inline]
pub const fn try_from_pixels(x: u32, y: u32) -> Result<Self, AspectRatioError> {
Self::try_new(x as f32, y as f32)
}
/// Returns the aspect ratio as a f32 value.
#[inline]
pub const fn ratio(&self) -> f32 {
self.0
}
/// Returns the inverse of this aspect ratio (height/width).
#[inline]
pub const fn inverse(&self) -> Self {
Self(1.0 / self.0)
}
/// Returns true if the aspect ratio represents a landscape orientation.
#[inline]
pub const fn is_landscape(&self) -> bool {
self.0 > 1.0
}
/// Returns true if the aspect ratio represents a portrait orientation.
#[inline]
pub const fn is_portrait(&self) -> bool {
self.0 < 1.0
}
/// Returns true if the aspect ratio is exactly square.
#[inline]
pub const fn is_square(&self) -> bool {
self.0 == 1.0
}
}
impl TryFrom<Vec2> for AspectRatio {
type Error = AspectRatioError;
#[inline]
fn try_from(value: Vec2) -> Result<Self, Self::Error> {
Self::try_new(value.x, value.y)
}
}
/// An Error type for when [`AspectRatio`](`super::AspectRatio`) is provided invalid width or height values
#[derive(Error, Debug, PartialEq, Eq, Clone, Copy)]
pub enum AspectRatioError {
/// Error due to width or height having zero as a value.
#[error("AspectRatio error: width or height is zero")]
Zero,
/// Error due towidth or height being infinite.
#[error("AspectRatio error: width or height is infinite")]
Infinite,
/// Error due to width or height being Not a Number (NaN).
#[error("AspectRatio error: width or height is NaN")]
NaN,
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/direction.rs | crates/bevy_math/src/direction.rs | use crate::{
primitives::{Primitive2d, Primitive3d},
Quat, Rot2, Vec2, Vec3, Vec3A, Vec4,
};
use core::f32::consts::FRAC_1_SQRT_2;
use core::fmt;
use derive_more::derive::Into;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
#[cfg(all(feature = "serialize", feature = "bevy_reflect"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
#[cfg(all(debug_assertions, feature = "std"))]
use std::eprintln;
use thiserror::Error;
/// An error indicating that a direction is invalid.
#[derive(Debug, PartialEq, Error)]
pub enum InvalidDirectionError {
/// The length of the direction vector is zero or very close to zero.
#[error("The length of the direction vector is zero or very close to zero")]
Zero,
/// The length of the direction vector is `std::f32::INFINITY`.
#[error("The length of the direction vector is `std::f32::INFINITY`")]
Infinite,
/// The length of the direction vector is `NaN`.
#[error("The length of the direction vector is `NaN`")]
NaN,
}
impl InvalidDirectionError {
/// Creates an [`InvalidDirectionError`] from the length of an invalid direction vector.
pub fn from_length(length: f32) -> Self {
if length.is_nan() {
InvalidDirectionError::NaN
} else if !length.is_finite() {
// If the direction is non-finite but also not NaN, it must be infinite
InvalidDirectionError::Infinite
} else {
// If the direction is invalid but neither NaN nor infinite, it must be zero
InvalidDirectionError::Zero
}
}
}
/// Checks that a vector with the given squared length is normalized.
///
/// Warns for small error with a length threshold of approximately `1e-4`,
/// and panics for large error with a length threshold of approximately `1e-2`.
///
/// The format used for the logged warning is `"Warning: {warning} The length is {length}`,
/// and similarly for the error.
#[cfg(debug_assertions)]
fn assert_is_normalized(message: &str, length_squared: f32) {
use crate::ops;
let length_error_squared = ops::abs(length_squared - 1.0);
// Panic for large error and warn for slight error.
if length_error_squared > 2e-2 || length_error_squared.is_nan() {
// Length error is approximately 1e-2 or more.
panic!(
"Error: {message} The length is {}.",
ops::sqrt(length_squared)
);
} else if length_error_squared > 2e-4 {
// Length error is approximately 1e-4 or more.
#[cfg(feature = "std")]
#[expect(clippy::print_stderr, reason = "Allowed behind `std` feature gate.")]
{
eprintln!(
"Warning: {message} The length is {}.",
ops::sqrt(length_squared)
);
}
}
}
/// A normalized vector pointing in a direction in 2D space
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
#[doc(alias = "Direction2d")]
pub struct Dir2(Vec2);
impl Primitive2d for Dir2 {}
impl Dir2 {
/// A unit vector pointing along the positive X axis.
pub const X: Self = Self(Vec2::X);
/// A unit vector pointing along the positive Y axis.
pub const Y: Self = Self(Vec2::Y);
/// A unit vector pointing along the negative X axis.
pub const NEG_X: Self = Self(Vec2::NEG_X);
/// A unit vector pointing along the negative Y axis.
pub const NEG_Y: Self = Self(Vec2::NEG_Y);
/// The directional axes.
pub const AXES: [Self; 2] = [Self::X, Self::Y];
/// The "north" direction, equivalent to [`Dir2::Y`].
pub const NORTH: Self = Self(Vec2::Y);
/// The "south" direction, equivalent to [`Dir2::NEG_Y`].
pub const SOUTH: Self = Self(Vec2::NEG_Y);
/// The "east" direction, equivalent to [`Dir2::X`].
pub const EAST: Self = Self(Vec2::X);
/// The "west" direction, equivalent to [`Dir2::NEG_X`].
pub const WEST: Self = Self(Vec2::NEG_X);
/// The "north-east" direction, between [`Dir2::NORTH`] and [`Dir2::EAST`].
pub const NORTH_EAST: Self = Self(Vec2::new(FRAC_1_SQRT_2, FRAC_1_SQRT_2));
/// The "north-west" direction, between [`Dir2::NORTH`] and [`Dir2::WEST`].
pub const NORTH_WEST: Self = Self(Vec2::new(-FRAC_1_SQRT_2, FRAC_1_SQRT_2));
/// The "south-east" direction, between [`Dir2::SOUTH`] and [`Dir2::EAST`].
pub const SOUTH_EAST: Self = Self(Vec2::new(FRAC_1_SQRT_2, -FRAC_1_SQRT_2));
/// The "south-west" direction, between [`Dir2::SOUTH`] and [`Dir2::WEST`].
pub const SOUTH_WEST: Self = Self(Vec2::new(-FRAC_1_SQRT_2, -FRAC_1_SQRT_2));
/// Create a direction from a finite, nonzero [`Vec2`], normalizing it.
///
/// Returns [`Err(InvalidDirectionError)`](InvalidDirectionError) if the length
/// of the given vector is zero (or very close to zero), infinite, or `NaN`.
pub fn new(value: Vec2) -> Result<Self, InvalidDirectionError> {
Self::new_and_length(value).map(|(dir, _)| dir)
}
/// Create a [`Dir2`] from a [`Vec2`] that is already normalized.
///
/// # Warning
///
/// `value` must be normalized, i.e its length must be `1.0`.
pub fn new_unchecked(value: Vec2) -> Self {
#[cfg(debug_assertions)]
assert_is_normalized(
"The vector given to `Dir2::new_unchecked` is not normalized.",
value.length_squared(),
);
Self(value)
}
/// Create a direction from a finite, nonzero [`Vec2`], normalizing it and
/// also returning its original length.
///
/// Returns [`Err(InvalidDirectionError)`](InvalidDirectionError) if the length
/// of the given vector is zero (or very close to zero), infinite, or `NaN`.
pub fn new_and_length(value: Vec2) -> Result<(Self, f32), InvalidDirectionError> {
let length = value.length();
let direction = (length.is_finite() && length > 0.0).then_some(value / length);
direction
.map(|dir| (Self(dir), length))
.ok_or(InvalidDirectionError::from_length(length))
}
/// Create a direction from its `x` and `y` components.
///
/// Returns [`Err(InvalidDirectionError)`](InvalidDirectionError) if the length
/// of the vector formed by the components is zero (or very close to zero), infinite, or `NaN`.
pub fn from_xy(x: f32, y: f32) -> Result<Self, InvalidDirectionError> {
Self::new(Vec2::new(x, y))
}
/// Create a direction from its `x` and `y` components, assuming the resulting vector is normalized.
///
/// # Warning
///
/// The vector produced from `x` and `y` must be normalized, i.e its length must be `1.0`.
pub fn from_xy_unchecked(x: f32, y: f32) -> Self {
Self::new_unchecked(Vec2::new(x, y))
}
/// Creates a 2D direction containing `[angle.cos(), angle.sin()]`.
#[inline]
pub fn from_angle(angle: f32) -> Self {
Self(Vec2::from_angle(angle))
}
/// Returns the inner [`Vec2`]
pub const fn as_vec2(&self) -> Vec2 {
self.0
}
/// Performs a spherical linear interpolation between `self` and `rhs`
/// based on the value `s`.
///
/// This corresponds to interpolating between the two directions at a constant angular velocity.
///
/// When `s == 0.0`, the result will be equal to `self`.
/// When `s == 1.0`, the result will be equal to `rhs`.
///
/// # Example
///
/// ```
/// # use bevy_math::Dir2;
/// # use approx::{assert_relative_eq, RelativeEq};
/// #
/// let dir1 = Dir2::X;
/// let dir2 = Dir2::Y;
///
/// let result1 = dir1.slerp(dir2, 1.0 / 3.0);
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(result1, Dir2::from_xy(0.75_f32.sqrt(), 0.5).unwrap());
///
/// let result2 = dir1.slerp(dir2, 0.5);
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(result2, Dir2::from_xy(0.5_f32.sqrt(), 0.5_f32.sqrt()).unwrap());
/// ```
#[inline]
pub fn slerp(self, rhs: Self, s: f32) -> Self {
let angle = self.angle_to(rhs.0);
Rot2::radians(angle * s) * self
}
/// Get the rotation that rotates this direction to `other`.
#[inline]
pub fn rotation_to(self, other: Self) -> Rot2 {
// Rotate `self` to X-axis, then X-axis to `other`:
other.rotation_from_x() * self.rotation_to_x()
}
/// Get the rotation that rotates `other` to this direction.
#[inline]
pub fn rotation_from(self, other: Self) -> Rot2 {
other.rotation_to(self)
}
/// Get the rotation that rotates the X-axis to this direction.
#[inline]
pub fn rotation_from_x(self) -> Rot2 {
Rot2::from_sin_cos(self.0.y, self.0.x)
}
/// Get the rotation that rotates this direction to the X-axis.
#[inline]
pub fn rotation_to_x(self) -> Rot2 {
// (This is cheap, it just negates one component.)
self.rotation_from_x().inverse()
}
/// Get the rotation that rotates the Y-axis to this direction.
#[inline]
pub fn rotation_from_y(self) -> Rot2 {
// `x <- y`, `y <- -x` correspond to rotating clockwise by pi/2;
// this transforms the Y-axis into the X-axis, maintaining the relative position
// of our direction. Then we just use the same technique as `rotation_from_x`.
Rot2::from_sin_cos(-self.0.x, self.0.y)
}
/// Get the rotation that rotates this direction to the Y-axis.
#[inline]
pub fn rotation_to_y(self) -> Rot2 {
self.rotation_from_y().inverse()
}
/// Returns `self` after an approximate normalization, assuming the value is already nearly normalized.
/// Useful for preventing numerical error accumulation.
/// See [`Dir3::fast_renormalize`] for an example of when such error accumulation might occur.
#[inline]
pub fn fast_renormalize(self) -> Self {
let length_squared = self.0.length_squared();
// Based on a Taylor approximation of the inverse square root, see [`Dir3::fast_renormalize`] for more details.
Self(self * (0.5 * (3.0 - length_squared)))
}
}
impl TryFrom<Vec2> for Dir2 {
type Error = InvalidDirectionError;
fn try_from(value: Vec2) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl From<Dir2> for Vec2 {
fn from(value: Dir2) -> Self {
value.as_vec2()
}
}
impl core::ops::Deref for Dir2 {
type Target = Vec2;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::Neg for Dir2 {
type Output = Self;
fn neg(self) -> Self::Output {
Self(-self.0)
}
}
impl core::ops::Mul<f32> for Dir2 {
type Output = Vec2;
fn mul(self, rhs: f32) -> Self::Output {
self.0 * rhs
}
}
impl core::ops::Mul<Dir2> for f32 {
type Output = Vec2;
fn mul(self, rhs: Dir2) -> Self::Output {
self * rhs.0
}
}
impl core::ops::Mul<Dir2> for Rot2 {
type Output = Dir2;
/// Rotates the [`Dir2`] using a [`Rot2`].
fn mul(self, direction: Dir2) -> Self::Output {
let rotated = self * *direction;
#[cfg(debug_assertions)]
assert_is_normalized(
"`Dir2` is denormalized after rotation.",
rotated.length_squared(),
);
Dir2(rotated)
}
}
impl fmt::Display for Dir2 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[cfg(any(feature = "approx", test))]
impl approx::AbsDiffEq for Dir2 {
type Epsilon = f32;
fn default_epsilon() -> f32 {
f32::EPSILON
}
fn abs_diff_eq(&self, other: &Self, epsilon: f32) -> bool {
self.as_ref().abs_diff_eq(other.as_ref(), epsilon)
}
}
#[cfg(any(feature = "approx", test))]
impl approx::RelativeEq for Dir2 {
fn default_max_relative() -> f32 {
f32::EPSILON
}
fn relative_eq(&self, other: &Self, epsilon: f32, max_relative: f32) -> bool {
self.as_ref()
.relative_eq(other.as_ref(), epsilon, max_relative)
}
}
#[cfg(any(feature = "approx", test))]
impl approx::UlpsEq for Dir2 {
fn default_max_ulps() -> u32 {
4
}
fn ulps_eq(&self, other: &Self, epsilon: f32, max_ulps: u32) -> bool {
self.as_ref().ulps_eq(other.as_ref(), epsilon, max_ulps)
}
}
/// A normalized vector pointing in a direction in 3D space
#[derive(Clone, Copy, Debug, PartialEq, Into)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
#[doc(alias = "Direction3d")]
pub struct Dir3(Vec3);
impl Primitive3d for Dir3 {}
impl Dir3 {
/// A unit vector pointing along the positive X axis.
pub const X: Self = Self(Vec3::X);
/// A unit vector pointing along the positive Y axis.
pub const Y: Self = Self(Vec3::Y);
/// A unit vector pointing along the positive Z axis.
pub const Z: Self = Self(Vec3::Z);
/// A unit vector pointing along the negative X axis.
pub const NEG_X: Self = Self(Vec3::NEG_X);
/// A unit vector pointing along the negative Y axis.
pub const NEG_Y: Self = Self(Vec3::NEG_Y);
/// A unit vector pointing along the negative Z axis.
pub const NEG_Z: Self = Self(Vec3::NEG_Z);
/// The directional axes.
pub const AXES: [Self; 3] = [Self::X, Self::Y, Self::Z];
/// Create a direction from a finite, nonzero [`Vec3`], normalizing it.
///
/// Returns [`Err(InvalidDirectionError)`](InvalidDirectionError) if the length
/// of the given vector is zero (or very close to zero), infinite, or `NaN`.
pub fn new(value: Vec3) -> Result<Self, InvalidDirectionError> {
Self::new_and_length(value).map(|(dir, _)| dir)
}
/// Create a [`Dir3`] from a [`Vec3`] that is already normalized.
///
/// # Warning
///
/// `value` must be normalized, i.e its length must be `1.0`.
pub fn new_unchecked(value: Vec3) -> Self {
#[cfg(debug_assertions)]
assert_is_normalized(
"The vector given to `Dir3::new_unchecked` is not normalized.",
value.length_squared(),
);
Self(value)
}
/// Create a direction from a finite, nonzero [`Vec3`], normalizing it and
/// also returning its original length.
///
/// Returns [`Err(InvalidDirectionError)`](InvalidDirectionError) if the length
/// of the given vector is zero (or very close to zero), infinite, or `NaN`.
pub fn new_and_length(value: Vec3) -> Result<(Self, f32), InvalidDirectionError> {
let length = value.length();
let direction = (length.is_finite() && length > 0.0).then_some(value / length);
direction
.map(|dir| (Self(dir), length))
.ok_or(InvalidDirectionError::from_length(length))
}
/// Create a direction from its `x`, `y`, and `z` components.
///
/// Returns [`Err(InvalidDirectionError)`](InvalidDirectionError) if the length
/// of the vector formed by the components is zero (or very close to zero), infinite, or `NaN`.
pub fn from_xyz(x: f32, y: f32, z: f32) -> Result<Self, InvalidDirectionError> {
Self::new(Vec3::new(x, y, z))
}
/// Create a direction from its `x`, `y`, and `z` components, assuming the resulting vector is normalized.
///
/// # Warning
///
/// The vector produced from `x`, `y`, and `z` must be normalized, i.e its length must be `1.0`.
pub fn from_xyz_unchecked(x: f32, y: f32, z: f32) -> Self {
Self::new_unchecked(Vec3::new(x, y, z))
}
/// Returns the inner [`Vec3`]
pub const fn as_vec3(&self) -> Vec3 {
self.0
}
/// Performs a spherical linear interpolation between `self` and `rhs`
/// based on the value `s`.
///
/// This corresponds to interpolating between the two directions at a constant angular velocity.
///
/// When `s == 0.0`, the result will be equal to `self`.
/// When `s == 1.0`, the result will be equal to `rhs`.
///
/// # Example
///
/// ```
/// # use bevy_math::Dir3;
/// # use approx::{assert_relative_eq, RelativeEq};
/// #
/// let dir1 = Dir3::X;
/// let dir2 = Dir3::Y;
///
/// let result1 = dir1.slerp(dir2, 1.0 / 3.0);
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(
/// result1,
/// Dir3::from_xyz(0.75_f32.sqrt(), 0.5, 0.0).unwrap(),
/// epsilon = 0.000001
/// );
///
/// let result2 = dir1.slerp(dir2, 0.5);
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(result2, Dir3::from_xyz(0.5_f32.sqrt(), 0.5_f32.sqrt(), 0.0).unwrap());
/// ```
#[inline]
pub fn slerp(self, rhs: Self, s: f32) -> Self {
let quat = Quat::IDENTITY.slerp(Quat::from_rotation_arc(self.0, rhs.0), s);
Dir3(quat.mul_vec3(self.0))
}
/// Returns `self` after an approximate normalization, assuming the value is already nearly normalized.
/// Useful for preventing numerical error accumulation.
///
/// # Example
/// The following seemingly benign code would start accumulating errors over time,
/// leading to `dir` eventually not being normalized anymore.
/// ```
/// # use bevy_math::prelude::*;
/// # let N: usize = 200;
/// let mut dir = Dir3::X;
/// let quaternion = Quat::from_euler(EulerRot::XYZ, 1.0, 2.0, 3.0);
/// for i in 0..N {
/// dir = quaternion * dir;
/// }
/// ```
/// Instead, do the following.
/// ```
/// # use bevy_math::prelude::*;
/// # let N: usize = 200;
/// let mut dir = Dir3::X;
/// let quaternion = Quat::from_euler(EulerRot::XYZ, 1.0, 2.0, 3.0);
/// for i in 0..N {
/// dir = quaternion * dir;
/// dir = dir.fast_renormalize();
/// }
/// ```
#[inline]
pub fn fast_renormalize(self) -> Self {
// We numerically approximate the inverse square root by a Taylor series around 1
// As we expect the error (x := length_squared - 1) to be small
// inverse_sqrt(length_squared) = (1 + x)^(-1/2) = 1 - 1/2 x + O(x²)
// inverse_sqrt(length_squared) ≈ 1 - 1/2 (length_squared - 1) = 1/2 (3 - length_squared)
// Iterative calls to this method quickly converge to a normalized value,
// so long as the denormalization is not large ~ O(1/10).
// One iteration can be described as:
// l_sq <- l_sq * (1 - 1/2 (l_sq - 1))²;
// Rewriting in terms of the error x:
// 1 + x <- (1 + x) * (1 - 1/2 x)²
// 1 + x <- (1 + x) * (1 - x + 1/4 x²)
// 1 + x <- 1 - x + 1/4 x² + x - x² + 1/4 x³
// x <- -1/4 x² (3 - x)
// If the error is small, say in a range of (-1/2, 1/2), then:
// |-1/4 x² (3 - x)| <= (3/4 + 1/4 * |x|) * x² <= (3/4 + 1/4 * 1/2) * x² < x² < 1/2 x
// Therefore the sequence of iterates converges to 0 error as a second order method.
let length_squared = self.0.length_squared();
Self(self * (0.5 * (3.0 - length_squared)))
}
}
impl TryFrom<Vec3> for Dir3 {
type Error = InvalidDirectionError;
fn try_from(value: Vec3) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl core::ops::Deref for Dir3 {
type Target = Vec3;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::Neg for Dir3 {
type Output = Self;
fn neg(self) -> Self::Output {
Self(-self.0)
}
}
impl core::ops::Mul<f32> for Dir3 {
type Output = Vec3;
fn mul(self, rhs: f32) -> Self::Output {
self.0 * rhs
}
}
impl core::ops::Mul<Dir3> for f32 {
type Output = Vec3;
fn mul(self, rhs: Dir3) -> Self::Output {
self * rhs.0
}
}
impl core::ops::Mul<Dir3> for Quat {
type Output = Dir3;
/// Rotates the [`Dir3`] using a [`Quat`].
fn mul(self, direction: Dir3) -> Self::Output {
let rotated = self * *direction;
#[cfg(debug_assertions)]
assert_is_normalized(
"`Dir3` is denormalized after rotation.",
rotated.length_squared(),
);
Dir3(rotated)
}
}
impl fmt::Display for Dir3 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[cfg(feature = "approx")]
impl approx::AbsDiffEq for Dir3 {
type Epsilon = f32;
fn default_epsilon() -> f32 {
f32::EPSILON
}
fn abs_diff_eq(&self, other: &Self, epsilon: f32) -> bool {
self.as_ref().abs_diff_eq(other.as_ref(), epsilon)
}
}
#[cfg(feature = "approx")]
impl approx::RelativeEq for Dir3 {
fn default_max_relative() -> f32 {
f32::EPSILON
}
fn relative_eq(&self, other: &Self, epsilon: f32, max_relative: f32) -> bool {
self.as_ref()
.relative_eq(other.as_ref(), epsilon, max_relative)
}
}
#[cfg(feature = "approx")]
impl approx::UlpsEq for Dir3 {
fn default_max_ulps() -> u32 {
4
}
fn ulps_eq(&self, other: &Self, epsilon: f32, max_ulps: u32) -> bool {
self.as_ref().ulps_eq(other.as_ref(), epsilon, max_ulps)
}
}
/// A normalized SIMD vector pointing in a direction in 3D space.
///
/// This type stores a 16 byte aligned [`Vec3A`].
/// This may or may not be faster than [`Dir3`]: make sure to benchmark!
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
#[doc(alias = "Direction3dA")]
pub struct Dir3A(Vec3A);
impl Primitive3d for Dir3A {}
impl Dir3A {
/// A unit vector pointing along the positive X axis.
pub const X: Self = Self(Vec3A::X);
/// A unit vector pointing along the positive Y axis.
pub const Y: Self = Self(Vec3A::Y);
/// A unit vector pointing along the positive Z axis.
pub const Z: Self = Self(Vec3A::Z);
/// A unit vector pointing along the negative X axis.
pub const NEG_X: Self = Self(Vec3A::NEG_X);
/// A unit vector pointing along the negative Y axis.
pub const NEG_Y: Self = Self(Vec3A::NEG_Y);
/// A unit vector pointing along the negative Z axis.
pub const NEG_Z: Self = Self(Vec3A::NEG_Z);
/// The directional axes.
pub const AXES: [Self; 3] = [Self::X, Self::Y, Self::Z];
/// Create a direction from a finite, nonzero [`Vec3A`], normalizing it.
///
/// Returns [`Err(InvalidDirectionError)`](InvalidDirectionError) if the length
/// of the given vector is zero (or very close to zero), infinite, or `NaN`.
pub fn new(value: Vec3A) -> Result<Self, InvalidDirectionError> {
Self::new_and_length(value).map(|(dir, _)| dir)
}
/// Create a [`Dir3A`] from a [`Vec3A`] that is already normalized.
///
/// # Warning
///
/// `value` must be normalized, i.e its length must be `1.0`.
pub fn new_unchecked(value: Vec3A) -> Self {
#[cfg(debug_assertions)]
assert_is_normalized(
"The vector given to `Dir3A::new_unchecked` is not normalized.",
value.length_squared(),
);
Self(value)
}
/// Create a direction from a finite, nonzero [`Vec3A`], normalizing it and
/// also returning its original length.
///
/// Returns [`Err(InvalidDirectionError)`](InvalidDirectionError) if the length
/// of the given vector is zero (or very close to zero), infinite, or `NaN`.
pub fn new_and_length(value: Vec3A) -> Result<(Self, f32), InvalidDirectionError> {
let length = value.length();
let direction = (length.is_finite() && length > 0.0).then_some(value / length);
direction
.map(|dir| (Self(dir), length))
.ok_or(InvalidDirectionError::from_length(length))
}
/// Create a direction from its `x`, `y`, and `z` components.
///
/// Returns [`Err(InvalidDirectionError)`](InvalidDirectionError) if the length
/// of the vector formed by the components is zero (or very close to zero), infinite, or `NaN`.
pub fn from_xyz(x: f32, y: f32, z: f32) -> Result<Self, InvalidDirectionError> {
Self::new(Vec3A::new(x, y, z))
}
/// Create a direction from its `x`, `y`, and `z` components, assuming the resulting vector is normalized.
///
/// # Warning
///
/// The vector produced from `x`, `y`, and `z` must be normalized, i.e its length must be `1.0`.
pub fn from_xyz_unchecked(x: f32, y: f32, z: f32) -> Self {
Self::new_unchecked(Vec3A::new(x, y, z))
}
/// Returns the inner [`Vec3A`]
pub const fn as_vec3a(&self) -> Vec3A {
self.0
}
/// Performs a spherical linear interpolation between `self` and `rhs`
/// based on the value `s`.
///
/// This corresponds to interpolating between the two directions at a constant angular velocity.
///
/// When `s == 0.0`, the result will be equal to `self`.
/// When `s == 1.0`, the result will be equal to `rhs`.
///
/// # Example
///
/// ```
/// # use bevy_math::Dir3A;
/// # use approx::{assert_relative_eq, RelativeEq};
/// #
/// let dir1 = Dir3A::X;
/// let dir2 = Dir3A::Y;
///
/// let result1 = dir1.slerp(dir2, 1.0 / 3.0);
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(
/// result1,
/// Dir3A::from_xyz(0.75_f32.sqrt(), 0.5, 0.0).unwrap(),
/// epsilon = 0.000001
/// );
///
/// let result2 = dir1.slerp(dir2, 0.5);
/// #[cfg(feature = "approx")]
/// assert_relative_eq!(result2, Dir3A::from_xyz(0.5_f32.sqrt(), 0.5_f32.sqrt(), 0.0).unwrap());
/// ```
#[inline]
pub fn slerp(self, rhs: Self, s: f32) -> Self {
let quat = Quat::IDENTITY.slerp(
Quat::from_rotation_arc(Vec3::from(self.0), Vec3::from(rhs.0)),
s,
);
Dir3A(quat.mul_vec3a(self.0))
}
/// Returns `self` after an approximate normalization, assuming the value is already nearly normalized.
/// Useful for preventing numerical error accumulation.
///
/// See [`Dir3::fast_renormalize`] for an example of when such error accumulation might occur.
#[inline]
pub fn fast_renormalize(self) -> Self {
let length_squared = self.0.length_squared();
// Based on a Taylor approximation of the inverse square root, see [`Dir3::fast_renormalize`] for more details.
Self(self * (0.5 * (3.0 - length_squared)))
}
}
impl From<Dir3> for Dir3A {
fn from(value: Dir3) -> Self {
Self(value.0.into())
}
}
impl From<Dir3A> for Dir3 {
fn from(value: Dir3A) -> Self {
Self(value.0.into())
}
}
impl TryFrom<Vec3A> for Dir3A {
type Error = InvalidDirectionError;
fn try_from(value: Vec3A) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl From<Dir3A> for Vec3A {
fn from(value: Dir3A) -> Self {
value.0
}
}
impl core::ops::Deref for Dir3A {
type Target = Vec3A;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::Neg for Dir3A {
type Output = Self;
fn neg(self) -> Self::Output {
Self(-self.0)
}
}
impl core::ops::Mul<f32> for Dir3A {
type Output = Vec3A;
fn mul(self, rhs: f32) -> Self::Output {
self.0 * rhs
}
}
impl core::ops::Mul<Dir3A> for f32 {
type Output = Vec3A;
fn mul(self, rhs: Dir3A) -> Self::Output {
self * rhs.0
}
}
impl core::ops::Mul<Dir3A> for Quat {
type Output = Dir3A;
/// Rotates the [`Dir3A`] using a [`Quat`].
fn mul(self, direction: Dir3A) -> Self::Output {
let rotated = self * *direction;
#[cfg(debug_assertions)]
assert_is_normalized(
"`Dir3A` is denormalized after rotation.",
rotated.length_squared(),
);
Dir3A(rotated)
}
}
impl fmt::Display for Dir3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[cfg(feature = "approx")]
impl approx::AbsDiffEq for Dir3A {
type Epsilon = f32;
fn default_epsilon() -> f32 {
f32::EPSILON
}
fn abs_diff_eq(&self, other: &Self, epsilon: f32) -> bool {
self.as_ref().abs_diff_eq(other.as_ref(), epsilon)
}
}
#[cfg(feature = "approx")]
impl approx::RelativeEq for Dir3A {
fn default_max_relative() -> f32 {
f32::EPSILON
}
fn relative_eq(&self, other: &Self, epsilon: f32, max_relative: f32) -> bool {
self.as_ref()
.relative_eq(other.as_ref(), epsilon, max_relative)
}
}
#[cfg(feature = "approx")]
impl approx::UlpsEq for Dir3A {
fn default_max_ulps() -> u32 {
4
}
fn ulps_eq(&self, other: &Self, epsilon: f32, max_ulps: u32) -> bool {
self.as_ref().ulps_eq(other.as_ref(), epsilon, max_ulps)
}
}
/// A normalized vector pointing in a direction in 4D space
#[derive(Clone, Copy, Debug, PartialEq, Into)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
#[doc(alias = "Direction4d")]
pub struct Dir4(Vec4);
impl Dir4 {
/// A unit vector pointing along the positive X axis
pub const X: Self = Self(Vec4::X);
/// A unit vector pointing along the positive Y axis.
pub const Y: Self = Self(Vec4::Y);
/// A unit vector pointing along the positive Z axis.
pub const Z: Self = Self(Vec4::Z);
/// A unit vector pointing along the positive W axis.
pub const W: Self = Self(Vec4::W);
/// A unit vector pointing along the negative X axis.
pub const NEG_X: Self = Self(Vec4::NEG_X);
/// A unit vector pointing along the negative Y axis.
pub const NEG_Y: Self = Self(Vec4::NEG_Y);
/// A unit vector pointing along the negative Z axis.
pub const NEG_Z: Self = Self(Vec4::NEG_Z);
/// A unit vector pointing along the negative W axis.
pub const NEG_W: Self = Self(Vec4::NEG_W);
/// The directional axes.
pub const AXES: [Self; 4] = [Self::X, Self::Y, Self::Z, Self::W];
/// Create a direction from a finite, nonzero [`Vec4`], normalizing it.
///
/// Returns [`Err(InvalidDirectionError)`](InvalidDirectionError) if the length
/// of the given vector is zero (or very close to zero), infinite, or `NaN`.
pub fn new(value: Vec4) -> Result<Self, InvalidDirectionError> {
Self::new_and_length(value).map(|(dir, _)| dir)
}
/// Create a [`Dir4`] from a [`Vec4`] that is already normalized.
///
/// # Warning
///
/// `value` must be normalized, i.e its length must be `1.0`.
pub fn new_unchecked(value: Vec4) -> Self {
#[cfg(debug_assertions)]
assert_is_normalized(
"The vector given to `Dir4::new_unchecked` is not normalized.",
value.length_squared(),
);
Self(value)
}
/// Create a direction from a finite, nonzero [`Vec4`], normalizing it and
/// also returning its original length.
///
/// Returns [`Err(InvalidDirectionError)`](InvalidDirectionError) if the length
/// of the given vector is zero (or very close to zero), infinite, or `NaN`.
pub fn new_and_length(value: Vec4) -> Result<(Self, f32), InvalidDirectionError> {
let length = value.length();
let direction = (length.is_finite() && length > 0.0).then_some(value / length);
direction
.map(|dir| (Self(dir), length))
.ok_or(InvalidDirectionError::from_length(length))
}
/// Create a direction from its `x`, `y`, `z`, and `w` components.
///
/// Returns [`Err(InvalidDirectionError)`](InvalidDirectionError) if the length
/// of the vector formed by the components is zero (or very close to zero), infinite, or `NaN`.
pub fn from_xyzw(x: f32, y: f32, z: f32, w: f32) -> Result<Self, InvalidDirectionError> {
Self::new(Vec4::new(x, y, z, w))
}
/// Create a direction from its `x`, `y`, `z`, and `w` components, assuming the resulting vector is normalized.
///
/// # Warning
///
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/float_ord.rs | crates/bevy_math/src/float_ord.rs | use core::{
cmp::Ordering,
hash::{Hash, Hasher},
ops::Neg,
};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
/// A wrapper for floats that implements [`Ord`], [`Eq`], and [`Hash`] traits.
///
/// This is a work around for the fact that the IEEE 754-2008 standard,
/// implemented by Rust's [`f32`] type,
/// doesn't define an ordering for [`NaN`](f32::NAN),
/// and `NaN` is not considered equal to any other `NaN`.
///
/// Wrapping a float with `FloatOrd` breaks conformance with the standard
/// by sorting `NaN` as less than all other numbers and equal to any other `NaN`.
#[derive(Debug, Copy, Clone)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Hash, Clone)
)]
pub struct FloatOrd(pub f32);
impl PartialOrd for FloatOrd {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
fn lt(&self, other: &Self) -> bool {
!other.le(self)
}
// If `self` is NaN, it is equal to another NaN and less than all other floats, so return true.
// If `self` isn't NaN and `other` is, the float comparison returns false, which match the `FloatOrd` ordering.
// Otherwise, a standard float comparison happens.
fn le(&self, other: &Self) -> bool {
self.0.is_nan() || self.0 <= other.0
}
fn gt(&self, other: &Self) -> bool {
!self.le(other)
}
fn ge(&self, other: &Self) -> bool {
other.le(self)
}
}
impl Ord for FloatOrd {
#[expect(
clippy::comparison_chain,
reason = "This can't be rewritten with `match` and `cmp`, as this is `cmp` itself."
)]
fn cmp(&self, other: &Self) -> Ordering {
if self > other {
Ordering::Greater
} else if self < other {
Ordering::Less
} else {
Ordering::Equal
}
}
}
impl PartialEq for FloatOrd {
fn eq(&self, other: &Self) -> bool {
if self.0.is_nan() {
other.0.is_nan()
} else {
self.0 == other.0
}
}
}
impl Eq for FloatOrd {}
impl Hash for FloatOrd {
fn hash<H: Hasher>(&self, state: &mut H) {
if self.0.is_nan() {
// Ensure all NaN representations hash to the same value
state.write(&f32::to_ne_bytes(f32::NAN));
} else if self.0 == 0.0 {
// Ensure both zeroes hash to the same value
state.write(&f32::to_ne_bytes(0.0f32));
} else {
state.write(&f32::to_ne_bytes(self.0));
}
}
}
impl Neg for FloatOrd {
type Output = FloatOrd;
fn neg(self) -> Self::Output {
FloatOrd(-self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
const NAN: FloatOrd = FloatOrd(f32::NAN);
const ZERO: FloatOrd = FloatOrd(0.0);
const ONE: FloatOrd = FloatOrd(1.0);
#[test]
fn float_ord_eq() {
assert_eq!(NAN, NAN);
assert_ne!(NAN, ZERO);
assert_ne!(ZERO, NAN);
assert_eq!(ZERO, ZERO);
}
#[test]
fn float_ord_cmp() {
assert_eq!(NAN.cmp(&NAN), Ordering::Equal);
assert_eq!(NAN.cmp(&ZERO), Ordering::Less);
assert_eq!(ZERO.cmp(&NAN), Ordering::Greater);
assert_eq!(ZERO.cmp(&ZERO), Ordering::Equal);
assert_eq!(ONE.cmp(&ZERO), Ordering::Greater);
assert_eq!(ZERO.cmp(&ONE), Ordering::Less);
}
#[test]
#[expect(
clippy::nonminimal_bool,
reason = "This tests that all operators work as they should, and in the process requires some non-simplified boolean expressions."
)]
fn float_ord_cmp_operators() {
assert!(!(NAN < NAN));
assert!(NAN < ZERO);
assert!(!(ZERO < NAN));
assert!(!(ZERO < ZERO));
assert!(ZERO < ONE);
assert!(!(ONE < ZERO));
assert!(!(NAN > NAN));
assert!(!(NAN > ZERO));
assert!(ZERO > NAN);
assert!(!(ZERO > ZERO));
assert!(!(ZERO > ONE));
assert!(ONE > ZERO);
assert!(NAN <= NAN);
assert!(NAN <= ZERO);
assert!(!(ZERO <= NAN));
assert!(ZERO <= ZERO);
assert!(ZERO <= ONE);
assert!(!(ONE <= ZERO));
assert!(NAN >= NAN);
assert!(!(NAN >= ZERO));
assert!(ZERO >= NAN);
assert!(ZERO >= ZERO);
assert!(!(ZERO >= ONE));
assert!(ONE >= ZERO);
}
#[cfg(feature = "std")]
#[test]
fn float_ord_hash() {
let hash = |num| {
let mut h = std::hash::DefaultHasher::new();
FloatOrd(num).hash(&mut h);
h.finish()
};
assert_ne!((-0.0f32).to_bits(), 0.0f32.to_bits());
assert_eq!(hash(-0.0), hash(0.0));
let nan_1 = f32::from_bits(0b0111_1111_1000_0000_0000_0000_0000_0001);
assert!(nan_1.is_nan());
let nan_2 = f32::from_bits(0b0111_1111_1000_0000_0000_0000_0000_0010);
assert!(nan_2.is_nan());
assert_ne!(nan_1.to_bits(), nan_2.to_bits());
assert_eq!(hash(nan_1), hash(nan_2));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/ops.rs | crates/bevy_math/src/ops.rs | //! This mod re-exports the correct versions of floating-point operations with
//! unspecified precision in the standard library depending on whether the `libm`
//! crate feature is enabled.
//!
//! All the functions here are named according to their versions in the standard
//! library.
//!
//! It also provides `no_std` compatible alternatives to certain floating-point
//! operations which are not provided in the [`core`] library.
// Note: There are some Rust methods with unspecified precision without a `libm`
// equivalent:
// - `f32::powi` (integer powers)
// - `f32::log` (logarithm with specified base)
// - `f32::abs_sub` (actually unsure if `libm` has this, but don't use it regardless)
//
// Additionally, the following nightly API functions are not presently integrated
// into this, but they would be candidates once standardized:
// - `f32::gamma`
// - `f32::ln_gamma`
#[cfg(all(not(feature = "libm"), feature = "std"))]
#[expect(
clippy::disallowed_methods,
reason = "Many of the disallowed methods are disallowed to force code to use the feature-conditional re-exports from this module, but this module itself is exempt from that rule."
)]
mod std_ops {
/// Raises a number to a floating point power.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn powf(x: f32, y: f32) -> f32 {
f32::powf(x, y)
}
/// Returns `e^(self)`, (the exponential function).
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn exp(x: f32) -> f32 {
f32::exp(x)
}
/// Returns `2^(self)`.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn exp2(x: f32) -> f32 {
f32::exp2(x)
}
/// Returns the natural logarithm of the number.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn ln(x: f32) -> f32 {
f32::ln(x)
}
/// Returns the base 2 logarithm of the number.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn log2(x: f32) -> f32 {
f32::log2(x)
}
/// Returns the base 10 logarithm of the number.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn log10(x: f32) -> f32 {
f32::log10(x)
}
/// Returns the cube root of a number.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn cbrt(x: f32) -> f32 {
f32::cbrt(x)
}
/// Compute the distance between the origin and a point `(x, y)` on the Euclidean plane.
/// Equivalently, compute the length of the hypotenuse of a right-angle triangle with other sides having length `x.abs()` and `y.abs()`.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn hypot(x: f32, y: f32) -> f32 {
f32::hypot(x, y)
}
/// Computes the sine of a number (in radians).
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn sin(x: f32) -> f32 {
f32::sin(x)
}
/// Computes the cosine of a number (in radians).
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn cos(x: f32) -> f32 {
f32::cos(x)
}
/// Computes the tangent of a number (in radians).
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn tan(x: f32) -> f32 {
f32::tan(x)
}
/// Computes the arcsine of a number. Return value is in radians in
/// the range [-pi/2, pi/2] or NaN if the number is outside the range
/// [-1, 1].
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn asin(x: f32) -> f32 {
f32::asin(x)
}
/// Computes the arccosine of a number. Return value is in radians in
/// the range [0, pi] or NaN if the number is outside the range
/// [-1, 1].
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn acos(x: f32) -> f32 {
f32::acos(x)
}
/// Computes the arctangent of a number. Return value is in radians in the
/// range [-pi/2, pi/2];
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn atan(x: f32) -> f32 {
f32::atan(x)
}
/// Computes the four-quadrant arctangent of `y` and `x` in radians.
///
/// * `x = 0`, `y = 0`: `0`
/// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]`
/// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]`
/// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)`
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn atan2(y: f32, x: f32) -> f32 {
f32::atan2(y, x)
}
/// Simultaneously computes the sine and cosine of the number, `x`. Returns
/// `(sin(x), cos(x))`.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn sin_cos(x: f32) -> (f32, f32) {
f32::sin_cos(x)
}
/// Returns `e^(self) - 1` in a way that is accurate even if the
/// number is close to zero.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn exp_m1(x: f32) -> f32 {
f32::exp_m1(x)
}
/// Returns `ln(1+n)` (natural logarithm) more accurately than if
/// the operations were performed separately.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn ln_1p(x: f32) -> f32 {
f32::ln_1p(x)
}
/// Hyperbolic sine function.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn sinh(x: f32) -> f32 {
f32::sinh(x)
}
/// Hyperbolic cosine function.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn cosh(x: f32) -> f32 {
f32::cosh(x)
}
/// Hyperbolic tangent function.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn tanh(x: f32) -> f32 {
f32::tanh(x)
}
/// Inverse hyperbolic sine function.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn asinh(x: f32) -> f32 {
f32::asinh(x)
}
/// Inverse hyperbolic cosine function.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn acosh(x: f32) -> f32 {
f32::acosh(x)
}
/// Inverse hyperbolic tangent function.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn atanh(x: f32) -> f32 {
f32::atanh(x)
}
}
#[cfg(any(feature = "libm", all(feature = "nostd-libm", not(feature = "std"))))]
mod libm_ops {
/// Raises a number to a floating point power.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn powf(x: f32, y: f32) -> f32 {
libm::powf(x, y)
}
/// Returns `e^(self)`, (the exponential function).
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn exp(x: f32) -> f32 {
libm::expf(x)
}
/// Returns `2^(self)`.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn exp2(x: f32) -> f32 {
libm::exp2f(x)
}
/// Returns the natural logarithm of the number.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn ln(x: f32) -> f32 {
// This isn't documented in `libm` but this is actually the base e logarithm.
libm::logf(x)
}
/// Returns the base 2 logarithm of the number.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn log2(x: f32) -> f32 {
libm::log2f(x)
}
/// Returns the base 10 logarithm of the number.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn log10(x: f32) -> f32 {
libm::log10f(x)
}
/// Returns the cube root of a number.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn cbrt(x: f32) -> f32 {
libm::cbrtf(x)
}
/// Compute the distance between the origin and a point `(x, y)` on the Euclidean plane.
///
/// Equivalently, compute the length of the hypotenuse of a right-angle triangle with other sides having length `x.abs()` and `y.abs()`.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn hypot(x: f32, y: f32) -> f32 {
libm::hypotf(x, y)
}
/// Computes the sine of a number (in radians).
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn sin(x: f32) -> f32 {
libm::sinf(x)
}
/// Computes the cosine of a number (in radians).
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn cos(x: f32) -> f32 {
libm::cosf(x)
}
/// Computes the tangent of a number (in radians).
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn tan(x: f32) -> f32 {
libm::tanf(x)
}
/// Computes the arcsine of a number. Return value is in radians in
/// the range [-pi/2, pi/2] or NaN if the number is outside the range
/// [-1, 1].
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn asin(x: f32) -> f32 {
libm::asinf(x)
}
/// Computes the arccosine of a number. Return value is in radians in
/// Hyperbolic tangent function.
///
/// Precision is specified when the `libm` feature is enabled.
/// the range [0, pi] or NaN if the number is outside the range
/// [-1, 1].
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn acos(x: f32) -> f32 {
libm::acosf(x)
}
/// Computes the arctangent of a number. Return value is in radians in the
/// range [-pi/2, pi/2];
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn atan(x: f32) -> f32 {
libm::atanf(x)
}
/// Computes the four-quadrant arctangent of `y` and `x` in radians.
///
/// * `x = 0`, `y = 0`: `0`
/// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]`
/// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]`
/// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)`
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn atan2(y: f32, x: f32) -> f32 {
libm::atan2f(y, x)
}
/// Simultaneously computes the sine and cosine of the number, `x`. Returns
/// `(sin(x), cos(x))`.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn sin_cos(x: f32) -> (f32, f32) {
libm::sincosf(x)
}
/// Returns `e^(self) - 1` in a way that is accurate even if the
/// number is close to zero.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn exp_m1(x: f32) -> f32 {
libm::expm1f(x)
}
/// Returns `ln(1+n)` (natural logarithm) more accurately than if
/// the operations were performed separately.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn ln_1p(x: f32) -> f32 {
libm::log1pf(x)
}
/// Hyperbolic sine function.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn sinh(x: f32) -> f32 {
libm::sinhf(x)
}
/// Hyperbolic cosine function.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn cosh(x: f32) -> f32 {
libm::coshf(x)
}
/// Hyperbolic tangent function.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn tanh(x: f32) -> f32 {
libm::tanhf(x)
}
/// Inverse hyperbolic sine function.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn asinh(x: f32) -> f32 {
libm::asinhf(x)
}
/// Inverse hyperbolic cosine function.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn acosh(x: f32) -> f32 {
libm::acoshf(x)
}
/// Inverse hyperbolic tangent function.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn atanh(x: f32) -> f32 {
libm::atanhf(x)
}
}
#[cfg(all(any(feature = "libm", feature = "nostd-libm"), not(feature = "std")))]
mod libm_ops_for_no_std {
//! Provides standardized names for [`f32`] operations which may not be
//! supported on `no_std` platforms.
//! On `no_std` platforms, this forwards to the implementations provided
//! by [`libm`].
/// Calculates the least nonnegative remainder of `self (mod rhs)`.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn rem_euclid(x: f32, y: f32) -> f32 {
let result = libm::remainderf(x, y);
// libm::remainderf has a range of -y/2 to +y/2
if result < 0. {
result + y
} else {
result
}
}
/// Computes the absolute value of x.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn abs(x: f32) -> f32 {
libm::fabsf(x)
}
/// Returns the square root of a number.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn sqrt(x: f32) -> f32 {
libm::sqrtf(x)
}
/// Returns a number composed of the magnitude of `x` and the sign of `y`.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn copysign(x: f32, y: f32) -> f32 {
libm::copysignf(x, y)
}
/// Returns the nearest integer to `x`. If a value is half-way between two integers, round away from `0.0`.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn round(x: f32) -> f32 {
libm::roundf(x)
}
/// Returns the largest integer less than or equal to `x`.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn floor(x: f32) -> f32 {
libm::floorf(x)
}
/// Returns the smallest integer greater than or equal to `x`.
///
/// Precision is specified when the `libm` feature is enabled.
#[inline]
pub fn ceil(x: f32) -> f32 {
libm::ceilf(x)
}
/// Returns the fractional part of `x`.
///
/// This function always returns the precise result.
#[inline]
pub fn fract(x: f32) -> f32 {
libm::modff(x).0
}
}
#[cfg(feature = "std")]
#[expect(
clippy::disallowed_methods,
reason = "Many of the disallowed methods are disallowed to force code to use the feature-conditional re-exports from this module, but this module itself is exempt from that rule."
)]
mod std_ops_for_no_std {
//! Provides standardized names for [`f32`] operations which may not be
//! supported on `no_std` platforms.
//! On `std` platforms, this forwards directly to the implementations provided
//! by [`std`].
/// Calculates the least nonnegative remainder of `x (mod y)`.
///
/// The result of this operation is guaranteed to be the rounded infinite-precision result.
#[inline]
pub fn rem_euclid(x: f32, y: f32) -> f32 {
f32::rem_euclid(x, y)
}
/// Computes the absolute value of x.
///
/// This function always returns the precise result.
#[inline]
pub fn abs(x: f32) -> f32 {
f32::abs(x)
}
/// Returns the square root of a number.
///
/// The result of this operation is guaranteed to be the rounded infinite-precision result.
/// It is specified by IEEE 754 as `squareRoot` and guaranteed not to change.
#[inline]
pub fn sqrt(x: f32) -> f32 {
f32::sqrt(x)
}
/// Returns a number composed of the magnitude of `x` and the sign of `y`.
///
/// Equal to `x` if the sign of `x` and `y` are the same, otherwise equal to `-x`. If `x` is a
/// `NaN`, then a `NaN` with the sign bit of `y` is returned. Note, however, that conserving the
/// sign bit on `NaN` across arithmetical operations is not generally guaranteed.
#[inline]
pub fn copysign(x: f32, y: f32) -> f32 {
f32::copysign(x, y)
}
/// Returns the nearest integer to `x`. If a value is half-way between two integers, round away from `0.0`.
///
/// This function always returns the precise result.
#[inline]
pub fn round(x: f32) -> f32 {
f32::round(x)
}
/// Returns the largest integer less than or equal to `x`.
///
/// This function always returns the precise result.
#[inline]
pub fn floor(x: f32) -> f32 {
f32::floor(x)
}
/// Returns the smallest integer greater than or equal to `x`.
///
/// This function always returns the precise result.
#[inline]
pub fn ceil(x: f32) -> f32 {
f32::ceil(x)
}
/// Returns the fractional part of `x`.
///
/// This function always returns the precise result.
#[inline]
pub fn fract(x: f32) -> f32 {
f32::fract(x)
}
}
#[cfg(any(feature = "libm", all(feature = "nostd-libm", not(feature = "std"))))]
pub use libm_ops::*;
#[cfg(all(not(feature = "libm"), feature = "std"))]
pub use std_ops::*;
#[cfg(feature = "std")]
pub use std_ops_for_no_std::*;
#[cfg(all(any(feature = "libm", feature = "nostd-libm"), not(feature = "std")))]
pub use libm_ops_for_no_std::*;
#[cfg(all(
not(feature = "libm"),
not(feature = "std"),
not(feature = "nostd-libm")
))]
compile_error!("Either the `libm`, `std`, or `nostd-libm` feature must be enabled.");
/// This extension trait covers shortfall in determinacy from the lack of a `libm` counterpart
/// to `f32::powi`. Use this for the common small exponents.
pub trait FloatPow {
/// Squares the f32
fn squared(self) -> Self;
/// Cubes the f32
fn cubed(self) -> Self;
}
impl FloatPow for f32 {
#[inline]
fn squared(self) -> Self {
self * self
}
#[inline]
fn cubed(self) -> Self {
self * self * self
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/cubic_splines/mod.rs | crates/bevy_math/src/cubic_splines/mod.rs | //! Provides types for building cubic splines for rendering curves and use with animation easing.
#[cfg(feature = "curve")]
mod curve_impls;
use crate::{
ops::{self, FloatPow},
Vec2, VectorSpace,
};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use thiserror::Error;
#[cfg(feature = "alloc")]
use {alloc::vec, alloc::vec::Vec, core::iter::once, itertools::Itertools};
/// A spline composed of a single cubic Bezier curve.
///
/// Useful for user-drawn curves with local control, or animation easing. See
/// [`CubicSegment::new_bezier_easing`] for use in easing.
///
/// ### Interpolation
///
/// The curve only passes through the first and last control point in each set of four points. The curve
/// is divided into "segments" by every fourth control point.
///
/// ### Tangency
///
/// Tangents are manually defined by the two intermediate control points within each set of four points.
/// You can think of the control points the curve passes through as "anchors", and as the intermediate
/// control points as the anchors displaced along their tangent vectors
///
/// ### Continuity
///
/// A Bezier curve is at minimum C0 continuous, meaning it has no holes or jumps. Each curve segment is
/// C2, meaning the tangent vector changes smoothly between each set of four control points, but this
/// doesn't hold at the control points between segments. Making the whole curve C1 or C2 requires moving
/// the intermediate control points to align the tangent vectors between segments, and can result in a
/// loss of local control.
///
/// ### Usage
///
/// ```
/// # use bevy_math::{*, prelude::*};
/// let points = [[
/// vec2(-1.0, -20.0),
/// vec2(3.0, 2.0),
/// vec2(5.0, 3.0),
/// vec2(9.0, 8.0),
/// ]];
/// let bezier = CubicBezier::new(points).to_curve().unwrap();
/// let positions: Vec<_> = bezier.iter_positions(100).collect();
/// ```
#[derive(Clone, Debug)]
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
pub struct CubicBezier<P: VectorSpace> {
/// The control points of the Bezier curve.
pub control_points: Vec<[P; 4]>,
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace> CubicBezier<P> {
/// Create a new cubic Bezier curve from sets of control points.
pub fn new(control_points: impl IntoIterator<Item = [P; 4]>) -> Self {
Self {
control_points: control_points.into_iter().collect(),
}
}
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace<Scalar = f32>> CubicGenerator<P> for CubicBezier<P> {
type Error = CubicBezierError;
#[inline]
fn to_curve(&self) -> Result<CubicCurve<P>, Self::Error> {
let segments = self
.control_points
.iter()
.map(|p| CubicSegment::new_bezier(*p))
.collect_vec();
if segments.is_empty() {
Err(CubicBezierError)
} else {
Ok(CubicCurve { segments })
}
}
}
/// An error returned during cubic curve generation for cubic Bezier curves indicating that a
/// segment of control points was not present.
#[derive(Clone, Debug, Error)]
#[error("Unable to generate cubic curve: at least one set of control points is required")]
pub struct CubicBezierError;
/// A spline interpolated continuously between the nearest two control points, with the position and
/// velocity of the curve specified at both control points. This curve passes through all control
/// points, with the specified velocity which includes direction and parametric speed.
///
/// Useful for smooth interpolation when you know the position and velocity at two points in time,
/// such as network prediction.
///
/// ### Interpolation
///
/// The curve passes through every control point.
///
/// ### Tangency
///
/// Tangents are explicitly defined at each control point.
///
/// ### Continuity
///
/// The curve is at minimum C1 continuous, meaning that it has no holes or jumps and the tangent vector also
/// has no sudden jumps.
///
/// ### Parametrization
///
/// The first segment of the curve connects the first two control points, the second connects the second and
/// third, and so on. This remains true when a cyclic curve is formed with [`to_curve_cyclic`], in which case
/// the final curve segment connects the last control point to the first.
///
/// ### Usage
///
/// ```
/// # use bevy_math::{*, prelude::*};
/// let points = [
/// vec2(-1.0, -20.0),
/// vec2(3.0, 2.0),
/// vec2(5.0, 3.0),
/// vec2(9.0, 8.0),
/// ];
/// let tangents = [
/// vec2(0.0, 1.0),
/// vec2(0.0, 1.0),
/// vec2(0.0, 1.0),
/// vec2(0.0, 1.0),
/// ];
/// let hermite = CubicHermite::new(points, tangents).to_curve().unwrap();
/// let positions: Vec<_> = hermite.iter_positions(100).collect();
/// ```
///
/// [`to_curve_cyclic`]: CyclicCubicGenerator::to_curve_cyclic
#[derive(Clone, Debug)]
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
pub struct CubicHermite<P: VectorSpace> {
/// The control points of the Hermite curve.
pub control_points: Vec<(P, P)>,
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace> CubicHermite<P> {
/// Create a new Hermite curve from sets of control points.
pub fn new(
control_points: impl IntoIterator<Item = P>,
tangents: impl IntoIterator<Item = P>,
) -> Self {
Self {
control_points: control_points.into_iter().zip(tangents).collect(),
}
}
/// The characteristic matrix for this spline construction.
///
/// Each row of this matrix expresses the coefficients of a [`CubicSegment`] as a linear
/// combination of `p_i`, `v_i`, `p_{i+1}`, and `v_{i+1}`, where `(p_i, v_i)` and
/// `(p_{i+1}, v_{i+1})` are consecutive control points with tangents.
#[inline]
fn char_matrix(&self) -> [[f32; 4]; 4] {
[
[1., 0., 0., 0.],
[0., 1., 0., 0.],
[-3., -2., 3., -1.],
[2., 1., -2., 1.],
]
}
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace<Scalar = f32>> CubicGenerator<P> for CubicHermite<P> {
type Error = InsufficientDataError;
#[inline]
fn to_curve(&self) -> Result<CubicCurve<P>, Self::Error> {
let segments = self
.control_points
.windows(2)
.map(|p| {
let (p0, v0, p1, v1) = (p[0].0, p[0].1, p[1].0, p[1].1);
CubicSegment::coefficients([p0, v0, p1, v1], self.char_matrix())
})
.collect_vec();
if segments.is_empty() {
Err(InsufficientDataError {
expected: 2,
given: self.control_points.len(),
})
} else {
Ok(CubicCurve { segments })
}
}
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace<Scalar = f32>> CyclicCubicGenerator<P> for CubicHermite<P> {
type Error = InsufficientDataError;
#[inline]
fn to_curve_cyclic(&self) -> Result<CubicCurve<P>, Self::Error> {
let segments = self
.control_points
.iter()
.circular_tuple_windows()
.map(|(&j0, &j1)| {
let (p0, v0, p1, v1) = (j0.0, j0.1, j1.0, j1.1);
CubicSegment::coefficients([p0, v0, p1, v1], self.char_matrix())
})
.collect_vec();
if segments.is_empty() {
Err(InsufficientDataError {
expected: 2,
given: self.control_points.len(),
})
} else {
Ok(CubicCurve { segments })
}
}
}
/// A spline interpolated continuously across the nearest four control points, with the position of
/// the curve specified at every control point and the tangents computed automatically. The associated [`CubicCurve`]
/// has one segment between each pair of adjacent control points.
///
/// **Note** the Catmull-Rom spline is a special case of Cardinal spline where the tension is 0.5.
///
/// ### Interpolation
///
/// The curve passes through every control point.
///
/// ### Tangency
///
/// Tangents are automatically computed based on the positions of control points.
///
/// ### Continuity
///
/// The curve is at minimum C1, meaning that it is continuous (it has no holes or jumps), and its tangent
/// vector is also well-defined everywhere, without sudden jumps.
///
/// ### Parametrization
///
/// The first segment of the curve connects the first two control points, the second connects the second and
/// third, and so on. This remains true when a cyclic curve is formed with [`to_curve_cyclic`], in which case
/// the final curve segment connects the last control point to the first.
///
/// ### Usage
///
/// ```
/// # use bevy_math::{*, prelude::*};
/// let points = [
/// vec2(-1.0, -20.0),
/// vec2(3.0, 2.0),
/// vec2(5.0, 3.0),
/// vec2(9.0, 8.0),
/// ];
/// let cardinal = CubicCardinalSpline::new(0.3, points).to_curve().unwrap();
/// let positions: Vec<_> = cardinal.iter_positions(100).collect();
/// ```
///
/// [`to_curve_cyclic`]: CyclicCubicGenerator::to_curve_cyclic
#[derive(Clone, Debug)]
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
pub struct CubicCardinalSpline<P: VectorSpace> {
/// Tension
pub tension: f32,
/// The control points of the Cardinal spline
pub control_points: Vec<P>,
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace> CubicCardinalSpline<P> {
/// Build a new Cardinal spline.
pub fn new(tension: f32, control_points: impl IntoIterator<Item = P>) -> Self {
Self {
tension,
control_points: control_points.into_iter().collect(),
}
}
/// Build a new Catmull-Rom spline, the special case of a Cardinal spline where tension = 1/2.
pub fn new_catmull_rom(control_points: impl IntoIterator<Item = P>) -> Self {
Self {
tension: 0.5,
control_points: control_points.into_iter().collect(),
}
}
/// The characteristic matrix for this spline construction.
///
/// Each row of this matrix expresses the coefficients of a [`CubicSegment`] as a linear
/// combination of four consecutive control points.
#[inline]
fn char_matrix(&self) -> [[f32; 4]; 4] {
let s = self.tension;
[
[0., 1., 0., 0.],
[-s, 0., s, 0.],
[2. * s, s - 3., 3. - 2. * s, -s],
[-s, 2. - s, s - 2., s],
]
}
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace<Scalar = f32>> CubicGenerator<P> for CubicCardinalSpline<P> {
type Error = InsufficientDataError;
#[inline]
fn to_curve(&self) -> Result<CubicCurve<P>, Self::Error> {
let length = self.control_points.len();
// Early return to avoid accessing an invalid index
if length < 2 {
return Err(InsufficientDataError {
expected: 2,
given: self.control_points.len(),
});
}
// Extend the list of control points by mirroring the last second-to-last control points on each end;
// this allows tangents for the endpoints to be provided, and the overall effect is that the tangent
// at an endpoint is proportional to twice the vector between it and its adjacent control point.
//
// The expression used here is P_{-1} := P_0 - (P_1 - P_0) = 2P_0 - P_1. (Analogously at the other end.)
let mirrored_first = self.control_points[0] * 2. - self.control_points[1];
let mirrored_last = self.control_points[length - 1] * 2. - self.control_points[length - 2];
let extended_control_points = once(&mirrored_first)
.chain(self.control_points.iter())
.chain(once(&mirrored_last));
let segments = extended_control_points
.tuple_windows()
.map(|(&p0, &p1, &p2, &p3)| {
CubicSegment::coefficients([p0, p1, p2, p3], self.char_matrix())
})
.collect_vec();
Ok(CubicCurve { segments })
}
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace<Scalar = f32>> CyclicCubicGenerator<P> for CubicCardinalSpline<P> {
type Error = InsufficientDataError;
#[inline]
fn to_curve_cyclic(&self) -> Result<CubicCurve<P>, Self::Error> {
let len = self.control_points.len();
if len < 2 {
return Err(InsufficientDataError {
expected: 2,
given: self.control_points.len(),
});
}
// This would ordinarily be the last segment, but we pick it out so that we can make it first
// in order to get a desirable parametrization where the first segment connects the first two
// control points instead of the second and third.
let first_segment = {
// We take the indices mod `len` in case `len` is very small.
let p0 = self.control_points[len - 1];
let p1 = self.control_points[0];
let p2 = self.control_points[1 % len];
let p3 = self.control_points[2 % len];
CubicSegment::coefficients([p0, p1, p2, p3], self.char_matrix())
};
let later_segments = self
.control_points
.iter()
.circular_tuple_windows()
.map(|(&p0, &p1, &p2, &p3)| {
CubicSegment::coefficients([p0, p1, p2, p3], self.char_matrix())
})
.take(len - 1);
let mut segments = Vec::with_capacity(len);
segments.push(first_segment);
segments.extend(later_segments);
Ok(CubicCurve { segments })
}
}
/// A spline interpolated continuously across the nearest four control points. The curve does not
/// necessarily pass through any of the control points.
///
/// ### Interpolation
///
/// The curve does not necessarily pass through its control points.
///
/// ### Tangency
/// Tangents are automatically computed based on the positions of control points.
///
/// ### Continuity
///
/// The curve is C2 continuous, meaning it has no holes or jumps, the tangent vector changes smoothly along
/// the entire curve, and the acceleration also varies continuously. The acceleration continuity of this
/// spline makes it useful for camera paths.
///
/// ### Parametrization
///
/// Each curve segment is defined by a window of four control points taken in sequence. When [`to_curve_cyclic`]
/// is used to form a cyclic curve, the three additional segments used to close the curve come last.
///
/// ### Usage
///
/// ```
/// # use bevy_math::{*, prelude::*};
/// let points = [
/// vec2(-1.0, -20.0),
/// vec2(3.0, 2.0),
/// vec2(5.0, 3.0),
/// vec2(9.0, 8.0),
/// ];
/// let b_spline = CubicBSpline::new(points).to_curve().unwrap();
/// let positions: Vec<_> = b_spline.iter_positions(100).collect();
/// ```
///
/// [`to_curve_cyclic`]: CyclicCubicGenerator::to_curve_cyclic
#[derive(Clone, Debug)]
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
pub struct CubicBSpline<P: VectorSpace> {
/// The control points of the spline
pub control_points: Vec<P>,
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace> CubicBSpline<P> {
/// Build a new B-Spline.
pub fn new(control_points: impl IntoIterator<Item = P>) -> Self {
Self {
control_points: control_points.into_iter().collect(),
}
}
/// The characteristic matrix for this spline construction.
///
/// Each row of this matrix expresses the coefficients of a [`CubicSegment`] as a linear
/// combination of four consecutive control points.
#[inline]
fn char_matrix(&self) -> [[f32; 4]; 4] {
// A derivation for this matrix can be found in "General Matrix Representations for B-splines" by Kaihuai Qin.
// <https://xiaoxingchen.github.io/2020/03/02/bspline_in_so3/general_matrix_representation_for_bsplines.pdf>
// See section 4.1 and equations 7 and 8.
let mut char_matrix = [
[1.0, 4.0, 1.0, 0.0],
[-3.0, 0.0, 3.0, 0.0],
[3.0, -6.0, 3.0, 0.0],
[-1.0, 3.0, -3.0, 1.0],
];
char_matrix
.iter_mut()
.for_each(|r| r.iter_mut().for_each(|c| *c /= 6.0));
char_matrix
}
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace<Scalar = f32>> CubicGenerator<P> for CubicBSpline<P> {
type Error = InsufficientDataError;
#[inline]
fn to_curve(&self) -> Result<CubicCurve<P>, Self::Error> {
let segments = self
.control_points
.windows(4)
.map(|p| CubicSegment::coefficients([p[0], p[1], p[2], p[3]], self.char_matrix()))
.collect_vec();
if segments.is_empty() {
Err(InsufficientDataError {
expected: 4,
given: self.control_points.len(),
})
} else {
Ok(CubicCurve { segments })
}
}
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace<Scalar = f32>> CyclicCubicGenerator<P> for CubicBSpline<P> {
type Error = InsufficientDataError;
#[inline]
fn to_curve_cyclic(&self) -> Result<CubicCurve<P>, Self::Error> {
let segments = self
.control_points
.iter()
.circular_tuple_windows()
.map(|(&a, &b, &c, &d)| CubicSegment::coefficients([a, b, c, d], self.char_matrix()))
.collect_vec();
// Note that the parametrization is consistent with the one for `to_curve` but with
// the extra curve segments all tacked on at the end. This might be slightly counter-intuitive,
// since it means the first segment doesn't go "between" the first two control points, but
// between the second and third instead.
if segments.is_empty() {
Err(InsufficientDataError {
expected: 2,
given: self.control_points.len(),
})
} else {
Ok(CubicCurve { segments })
}
}
}
/// Error during construction of [`CubicNurbs`]
#[derive(Clone, Debug, Error)]
pub enum CubicNurbsError {
/// Provided the wrong number of knots.
#[error("Wrong number of knots: expected {expected}, provided {provided}")]
KnotsNumberMismatch {
/// Expected number of knots
expected: usize,
/// Provided number of knots
provided: usize,
},
/// The provided knots had a descending knot pair. Subsequent knots must
/// either increase or stay the same.
#[error("Invalid knots: contains descending knot pair")]
DescendingKnots,
/// The provided knots were all equal. Knots must contain at least one increasing pair.
#[error("Invalid knots: all knots are equal")]
ConstantKnots,
/// Provided a different number of weights and control points.
#[error("Incorrect number of weights: expected {expected}, provided {provided}")]
WeightsNumberMismatch {
/// Expected number of weights
expected: usize,
/// Provided number of weights
provided: usize,
},
/// The number of control points provided is less than 4.
#[error("Not enough control points, at least 4 are required, {provided} were provided")]
NotEnoughControlPoints {
/// The number of control points provided
provided: usize,
},
}
/// Non-uniform Rational B-Splines (NURBS) are a powerful generalization of the [`CubicBSpline`] which can
/// represent a much more diverse class of curves (like perfect circles and ellipses).
///
/// ### Non-uniformity
///
/// The 'NU' part of NURBS stands for "Non-Uniform". This has to do with a parameter called 'knots'.
/// The knots are a non-decreasing sequence of floating point numbers. The first and last three pairs of
/// knots control the behavior of the curve as it approaches its endpoints. The intermediate pairs
/// each control the length of one segment of the curve. Multiple repeated knot values are called
/// "knot multiplicity". Knot multiplicity in the intermediate knots causes a "zero-length" segment,
/// and can create sharp corners.
///
/// ### Rationality
///
/// The 'R' part of NURBS stands for "Rational". This has to do with NURBS allowing each control point to
/// be assigned a weighting, which controls how much it affects the curve compared to the other points.
///
/// ### Interpolation
///
/// The curve will not pass through the control points except where a knot has multiplicity four.
///
/// ### Tangency
///
/// Tangents are automatically computed based on the position of control points.
///
/// ### Continuity
///
/// When there is no knot multiplicity, the curve is C2 continuous, meaning it has no holes or jumps and the
/// tangent vector changes smoothly along the entire curve length. Like the [`CubicBSpline`], the acceleration
/// continuity makes it useful for camera paths. Knot multiplicity of 2 in intermediate knots reduces the
/// continuity to C1, and knot multiplicity of 3 reduces the continuity to C0. The curve is always at least
/// C0, meaning it has no jumps or holes.
///
/// ### Usage
///
/// ```
/// # use bevy_math::{*, prelude::*};
/// let points = [
/// vec2(-1.0, -20.0),
/// vec2(3.0, 2.0),
/// vec2(5.0, 3.0),
/// vec2(9.0, 8.0),
/// ];
/// let weights = [1.0, 1.0, 2.0, 1.0];
/// let knots = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0];
/// let nurbs = CubicNurbs::new(points, Some(weights), Some(knots))
/// .expect("NURBS construction failed!")
/// .to_curve()
/// .unwrap();
/// let positions: Vec<_> = nurbs.iter_positions(100).collect();
/// ```
#[derive(Clone, Debug)]
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
pub struct CubicNurbs<P: VectorSpace> {
/// The control points of the NURBS
pub control_points: Vec<P>,
/// Weights
pub weights: Vec<f32>,
/// Knots
pub knots: Vec<f32>,
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace<Scalar = f32>> CubicNurbs<P> {
/// Build a Non-Uniform Rational B-Spline.
///
/// If provided, weights must be the same length as the control points. Defaults to equal weights.
///
/// If provided, the number of knots must be n + 4 elements, where n is the amount of control
/// points. Defaults to open uniform knots: [`Self::open_uniform_knots`]. Knots cannot
/// all be equal.
///
/// At least 4 points must be provided, otherwise an error will be returned.
pub fn new(
control_points: impl IntoIterator<Item = P>,
weights: Option<impl IntoIterator<Item = f32>>,
knots: Option<impl IntoIterator<Item = f32>>,
) -> Result<Self, CubicNurbsError> {
let mut control_points: Vec<P> = control_points.into_iter().collect();
let control_points_len = control_points.len();
if control_points_len < 4 {
return Err(CubicNurbsError::NotEnoughControlPoints {
provided: control_points_len,
});
}
let weights: Vec<f32> = weights
.map(|ws| ws.into_iter().collect())
.unwrap_or_else(|| vec![1.0; control_points_len]);
let mut knots: Vec<f32> = knots.map(|ks| ks.into_iter().collect()).unwrap_or_else(|| {
Self::open_uniform_knots(control_points_len)
.expect("The amount of control points was checked")
});
let expected_knots_len = Self::knots_len(control_points_len);
// Check the number of knots is correct
if knots.len() != expected_knots_len {
return Err(CubicNurbsError::KnotsNumberMismatch {
expected: expected_knots_len,
provided: knots.len(),
});
}
// Ensure the knots are non-descending (previous element is less than or equal
// to the next)
if knots.windows(2).any(|win| win[0] > win[1]) {
return Err(CubicNurbsError::DescendingKnots);
}
// Ensure the knots are non-constant
if knots.windows(2).all(|win| win[0] == win[1]) {
return Err(CubicNurbsError::ConstantKnots);
}
// Check that the number of weights equals the number of control points
if weights.len() != control_points_len {
return Err(CubicNurbsError::WeightsNumberMismatch {
expected: control_points_len,
provided: weights.len(),
});
}
// To align the evaluation behavior of nurbs with the other splines,
// make the intervals between knots form an exact cover of [0, N], where N is
// the number of segments of the final curve.
let curve_length = (control_points.len() - 3) as f32;
let min = *knots.first().unwrap();
let max = *knots.last().unwrap();
let knot_delta = max - min;
knots = knots
.into_iter()
.map(|k| k - min)
.map(|k| k * curve_length / knot_delta)
.collect();
control_points
.iter_mut()
.zip(weights.iter())
.for_each(|(p, w)| *p = *p * *w);
Ok(Self {
control_points,
weights,
knots,
})
}
/// Generates uniform knots that will generate the same curve as [`CubicBSpline`].
///
/// "Uniform" means that the difference between two subsequent knots is the same.
///
/// Will return `None` if there are less than 4 control points.
pub fn uniform_knots(control_points: usize) -> Option<Vec<f32>> {
if control_points < 4 {
return None;
}
Some(
(0..Self::knots_len(control_points))
.map(|v| v as f32)
.collect(),
)
}
/// Generates open uniform knots, which makes the ends of the curve pass through the
/// start and end points.
///
/// The start and end knots have multiplicity 4, and intermediate knots have multiplicity 0 and
/// difference of 1.
///
/// Will return `None` if there are less than 4 control points.
pub fn open_uniform_knots(control_points: usize) -> Option<Vec<f32>> {
if control_points < 4 {
return None;
}
let last_knots_value = control_points - 3;
Some(
core::iter::repeat_n(0.0, 4)
.chain((1..last_knots_value).map(|v| v as f32))
.chain(core::iter::repeat_n(last_knots_value as f32, 4))
.collect(),
)
}
#[inline]
const fn knots_len(control_points_len: usize) -> usize {
control_points_len + 4
}
/// Generates a non-uniform B-spline characteristic matrix from a sequence of six knots. Each six
/// knots describe the relationship between four successive control points. For padding reasons,
/// this takes a vector of 8 knots, but only six are actually used.
fn generate_matrix(knots: &[f32; 8]) -> [[f32; 4]; 4] {
// A derivation for this matrix can be found in "General Matrix Representations for B-splines" by Kaihuai Qin.
// <https://xiaoxingchen.github.io/2020/03/02/bspline_in_so3/general_matrix_representation_for_bsplines.pdf>
// See section 3.1.
let t = knots;
// In the notation of the paper:
// t[1] := t_i-2
// t[2] := t_i-1
// t[3] := t_i (the lower extent of the current knot span)
// t[4] := t_i+1 (the upper extent of the current knot span)
// t[5] := t_i+2
// t[6] := t_i+3
let m00 = (t[4] - t[3]).squared() / ((t[4] - t[2]) * (t[4] - t[1]));
let m02 = (t[3] - t[2]).squared() / ((t[5] - t[2]) * (t[4] - t[2]));
let m12 = (3.0 * (t[4] - t[3]) * (t[3] - t[2])) / ((t[5] - t[2]) * (t[4] - t[2]));
let m22 = 3.0 * (t[4] - t[3]).squared() / ((t[5] - t[2]) * (t[4] - t[2]));
let m33 = (t[4] - t[3]).squared() / ((t[6] - t[3]) * (t[5] - t[3]));
let m32 = -m22 / 3.0 - m33 - (t[4] - t[3]).squared() / ((t[5] - t[3]) * (t[5] - t[2]));
[
[m00, 1.0 - m00 - m02, m02, 0.0],
[-3.0 * m00, 3.0 * m00 - m12, m12, 0.0],
[3.0 * m00, -3.0 * m00 - m22, m22, 0.0],
[-m00, m00 - m32 - m33, m32, m33],
]
}
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace<Scalar = f32>> RationalGenerator<P> for CubicNurbs<P> {
type Error = InsufficientDataError;
#[inline]
fn to_curve(&self) -> Result<RationalCurve<P>, Self::Error> {
let segments = self
.control_points
.windows(4)
.zip(self.weights.windows(4))
.zip(self.knots.windows(8))
.filter(|(_, knots)| knots[4] - knots[3] > 0.0)
.map(|((points, weights), knots)| {
// This is curve segment i. It uses control points P_i, P_i+2, P_i+2 and P_i+3,
// It is associated with knot span i+3 (which is the interval between knots i+3
// and i+4) and its characteristic matrix uses knots i+1 through i+6 (because
// those define the two knot spans on either side).
let span = knots[4] - knots[3];
let coefficient_knots = knots.try_into().expect("Knot windows are of length 6");
let matrix = Self::generate_matrix(coefficient_knots);
RationalSegment::coefficients(
points.try_into().expect("Point windows are of length 4"),
weights.try_into().expect("Weight windows are of length 4"),
span,
matrix,
)
})
.collect_vec();
if segments.is_empty() {
Err(InsufficientDataError {
expected: 4,
given: self.control_points.len(),
})
} else {
Ok(RationalCurve { segments })
}
}
}
/// A spline interpolated linearly between the nearest 2 points.
///
/// ### Interpolation
///
/// The curve passes through every control point.
///
/// ### Tangency
///
/// The curve is not generally differentiable at control points.
///
/// ### Continuity
///
/// The curve is C0 continuous, meaning it has no holes or jumps.
///
/// ### Parametrization
///
/// Each curve segment connects two adjacent control points in sequence. When a cyclic curve is
/// formed with [`to_curve_cyclic`], the final segment connects the last control point with the first.
///
/// [`to_curve_cyclic`]: CyclicCubicGenerator::to_curve_cyclic
#[derive(Clone, Debug)]
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
pub struct LinearSpline<P: VectorSpace> {
/// The control points of the linear spline.
pub points: Vec<P>,
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace> LinearSpline<P> {
/// Create a new linear spline from a list of points to be interpolated.
pub fn new(points: impl IntoIterator<Item = P>) -> Self {
Self {
points: points.into_iter().collect(),
}
}
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace> CubicGenerator<P> for LinearSpline<P> {
type Error = InsufficientDataError;
#[inline]
fn to_curve(&self) -> Result<CubicCurve<P>, Self::Error> {
let segments = self
.points
.windows(2)
.map(|points| {
let a = points[0];
let b = points[1];
CubicSegment {
coeff: [a, b - a, P::default(), P::default()],
}
})
.collect_vec();
if segments.is_empty() {
Err(InsufficientDataError {
expected: 2,
given: self.points.len(),
})
} else {
Ok(CubicCurve { segments })
}
}
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace> CyclicCubicGenerator<P> for LinearSpline<P> {
type Error = InsufficientDataError;
#[inline]
fn to_curve_cyclic(&self) -> Result<CubicCurve<P>, Self::Error> {
let segments = self
.points
.iter()
.circular_tuple_windows()
.map(|(&a, &b)| CubicSegment {
coeff: [a, b - a, P::default(), P::default()],
})
.collect_vec();
if segments.is_empty() {
Err(InsufficientDataError {
expected: 2,
given: self.points.len(),
})
} else {
Ok(CubicCurve { segments })
}
}
}
/// An error indicating that a spline construction didn't have enough control points to generate a curve.
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/cubic_splines/curve_impls.rs | crates/bevy_math/src/cubic_splines/curve_impls.rs | use super::{CubicSegment, RationalSegment};
use crate::common_traits::{VectorSpace, WithDerivative, WithTwoDerivatives};
use crate::curve::{
derivatives::{SampleDerivative, SampleTwoDerivatives},
Curve, Interval,
};
#[cfg(feature = "alloc")]
use super::{CubicCurve, RationalCurve};
// -- CubicSegment
impl<P: VectorSpace<Scalar = f32>> Curve<P> for CubicSegment<P> {
#[inline]
fn domain(&self) -> Interval {
Interval::UNIT
}
#[inline]
fn sample_unchecked(&self, t: f32) -> P {
self.position(t)
}
}
impl<P: VectorSpace<Scalar = f32>> SampleDerivative<P> for CubicSegment<P> {
#[inline]
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<P> {
WithDerivative {
value: self.position(t),
derivative: self.velocity(t),
}
}
}
impl<P: VectorSpace<Scalar = f32>> SampleTwoDerivatives<P> for CubicSegment<P> {
#[inline]
fn sample_with_two_derivatives_unchecked(&self, t: f32) -> WithTwoDerivatives<P> {
WithTwoDerivatives {
value: self.position(t),
derivative: self.velocity(t),
second_derivative: self.acceleration(t),
}
}
}
// -- CubicCurve
#[cfg(feature = "alloc")]
impl<P: VectorSpace<Scalar = f32>> Curve<P> for CubicCurve<P> {
#[inline]
fn domain(&self) -> Interval {
// The non-emptiness invariant guarantees that this succeeds.
Interval::new(0.0, self.segments.len() as f32)
.expect("CubicCurve is invalid because it has no segments")
}
#[inline]
fn sample_unchecked(&self, t: f32) -> P {
self.position(t)
}
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace<Scalar = f32>> SampleDerivative<P> for CubicCurve<P> {
#[inline]
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<P> {
WithDerivative {
value: self.position(t),
derivative: self.velocity(t),
}
}
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace<Scalar = f32>> SampleTwoDerivatives<P> for CubicCurve<P> {
#[inline]
fn sample_with_two_derivatives_unchecked(&self, t: f32) -> WithTwoDerivatives<P> {
WithTwoDerivatives {
value: self.position(t),
derivative: self.velocity(t),
second_derivative: self.acceleration(t),
}
}
}
// -- RationalSegment
impl<P: VectorSpace<Scalar = f32>> Curve<P> for RationalSegment<P> {
#[inline]
fn domain(&self) -> Interval {
Interval::UNIT
}
#[inline]
fn sample_unchecked(&self, t: f32) -> P {
self.position(t)
}
}
impl<P: VectorSpace<Scalar = f32>> SampleDerivative<P> for RationalSegment<P> {
#[inline]
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<P> {
WithDerivative {
value: self.position(t),
derivative: self.velocity(t),
}
}
}
impl<P: VectorSpace<Scalar = f32>> SampleTwoDerivatives<P> for RationalSegment<P> {
#[inline]
fn sample_with_two_derivatives_unchecked(&self, t: f32) -> WithTwoDerivatives<P> {
WithTwoDerivatives {
value: self.position(t),
derivative: self.velocity(t),
second_derivative: self.acceleration(t),
}
}
}
// -- RationalCurve
#[cfg(feature = "alloc")]
impl<P: VectorSpace<Scalar = f32>> Curve<P> for RationalCurve<P> {
#[inline]
fn domain(&self) -> Interval {
// The non-emptiness invariant guarantees the success of this.
Interval::new(0.0, self.length())
.expect("RationalCurve is invalid because it has zero length")
}
#[inline]
fn sample_unchecked(&self, t: f32) -> P {
self.position(t)
}
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace<Scalar = f32>> SampleDerivative<P> for RationalCurve<P> {
#[inline]
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<P> {
WithDerivative {
value: self.position(t),
derivative: self.velocity(t),
}
}
}
#[cfg(feature = "alloc")]
impl<P: VectorSpace<Scalar = f32>> SampleTwoDerivatives<P> for RationalCurve<P> {
#[inline]
fn sample_with_two_derivatives_unchecked(&self, t: f32) -> WithTwoDerivatives<P> {
WithTwoDerivatives {
value: self.position(t),
derivative: self.velocity(t),
second_derivative: self.acceleration(t),
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/primitives/dim2.rs | crates/bevy_math/src/primitives/dim2.rs | use core::f32::consts::{FRAC_1_SQRT_2, FRAC_PI_2, FRAC_PI_3, PI};
use derive_more::derive::From;
#[cfg(feature = "alloc")]
use thiserror::Error;
use super::{Measured2d, Primitive2d, WindingOrder};
use crate::{
ops::{self, FloatPow},
primitives::Inset,
Dir2, InvalidDirectionError, Isometry2d, Ray2d, Rot2, Vec2,
};
#[cfg(feature = "alloc")]
use super::polygon::is_polygon_simple;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
#[cfg(all(feature = "serialize", feature = "bevy_reflect"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
/// A circle primitive, representing the set of points some distance from the origin
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Circle {
/// The radius of the circle
pub radius: f32,
}
impl Primitive2d for Circle {}
impl Default for Circle {
/// Returns the default [`Circle`] with a radius of `0.5`.
fn default() -> Self {
Self { radius: 0.5 }
}
}
impl Circle {
/// Create a new [`Circle`] from a `radius`
#[inline]
pub const fn new(radius: f32) -> Self {
Self { radius }
}
/// Get the diameter of the circle
#[inline]
pub const fn diameter(&self) -> f32 {
2.0 * self.radius
}
/// Finds the point on the circle that is closest to the given `point`.
///
/// If the point is outside the circle, the returned point will be on the perimeter of the circle.
/// Otherwise, it will be inside the circle and returned as is.
#[inline]
pub fn closest_point(&self, point: Vec2) -> Vec2 {
let distance_squared = point.length_squared();
if distance_squared <= self.radius.squared() {
// The point is inside the circle.
point
} else {
// The point is outside the circle.
// Find the closest point on the perimeter of the circle.
let dir_to_point = point / ops::sqrt(distance_squared);
self.radius * dir_to_point
}
}
}
impl Measured2d for Circle {
/// Get the area of the circle
#[inline]
fn area(&self) -> f32 {
PI * self.radius.squared()
}
/// Get the perimeter or circumference of the circle
#[inline]
#[doc(alias = "circumference")]
fn perimeter(&self) -> f32 {
2.0 * PI * self.radius
}
}
/// A primitive representing an arc between two points on a circle.
///
/// An arc has no area.
/// If you want to include the portion of a circle's area swept out by the arc,
/// use the pie-shaped [`CircularSector`].
/// If you want to include only the space inside the convex hull of the arc,
/// use the bowl-shaped [`CircularSegment`].
///
/// The arc is drawn starting from [`Vec2::Y`], extending by `half_angle` radians on
/// either side. The center of the circle is the origin [`Vec2::ZERO`]. Note that this
/// means that the origin may not be within the `Arc2d`'s convex hull.
///
/// **Warning:** Arcs with negative angle or radius, or with angle greater than an entire circle, are not officially supported.
/// It is recommended to normalize arcs to have an angle in [0, 2π].
#[derive(Clone, Copy, Debug, PartialEq)]
#[doc(alias("CircularArc", "CircleArc"))]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Arc2d {
/// The radius of the circle
pub radius: f32,
/// Half the angle defining the arc
pub half_angle: f32,
}
impl Primitive2d for Arc2d {}
impl Default for Arc2d {
/// Returns the default [`Arc2d`] with radius `0.5`, covering one third of a circle
fn default() -> Self {
Self {
radius: 0.5,
half_angle: 2.0 * FRAC_PI_3,
}
}
}
impl Arc2d {
/// Create a new [`Arc2d`] from a `radius` and a `half_angle`
#[inline]
pub const fn new(radius: f32, half_angle: f32) -> Self {
Self { radius, half_angle }
}
/// Create a new [`Arc2d`] from a `radius` and an `angle` in radians
#[inline]
pub const fn from_radians(radius: f32, angle: f32) -> Self {
Self {
radius,
half_angle: angle / 2.0,
}
}
/// Create a new [`Arc2d`] from a `radius` and an `angle` in degrees.
#[inline]
pub const fn from_degrees(radius: f32, angle: f32) -> Self {
Self {
radius,
half_angle: angle.to_radians() / 2.0,
}
}
/// Create a new [`Arc2d`] from a `radius` and a `fraction` of a single turn.
///
/// For instance, `0.5` turns is a semicircle.
#[inline]
pub const fn from_turns(radius: f32, fraction: f32) -> Self {
Self {
radius,
half_angle: fraction * PI,
}
}
/// Get the angle of the arc
#[inline]
pub const fn angle(&self) -> f32 {
self.half_angle * 2.0
}
/// Get the length of the arc
#[inline]
pub const fn length(&self) -> f32 {
self.angle() * self.radius
}
/// Get the right-hand end point of the arc
#[inline]
pub fn right_endpoint(&self) -> Vec2 {
self.radius * Vec2::from_angle(FRAC_PI_2 - self.half_angle)
}
/// Get the left-hand end point of the arc
#[inline]
pub fn left_endpoint(&self) -> Vec2 {
self.radius * Vec2::from_angle(FRAC_PI_2 + self.half_angle)
}
/// Get the endpoints of the arc
#[inline]
pub fn endpoints(&self) -> [Vec2; 2] {
[self.left_endpoint(), self.right_endpoint()]
}
/// Get the midpoint of the arc
#[inline]
pub fn midpoint(&self) -> Vec2 {
self.radius * Vec2::Y
}
/// Get half the distance between the endpoints (half the length of the chord)
#[inline]
pub fn half_chord_length(&self) -> f32 {
self.radius * ops::sin(self.half_angle)
}
/// Get the distance between the endpoints (the length of the chord)
#[inline]
pub fn chord_length(&self) -> f32 {
2.0 * self.half_chord_length()
}
/// Get the midpoint of the two endpoints (the midpoint of the chord)
#[inline]
pub fn chord_midpoint(&self) -> Vec2 {
self.apothem() * Vec2::Y
}
/// Get the length of the apothem of this arc, that is,
/// the distance from the center of the circle to the midpoint of the chord, in the direction of the midpoint of the arc.
/// Equivalently, the [`radius`](Self::radius) minus the [`sagitta`](Self::sagitta).
///
/// Note that for a [`major`](Self::is_major) arc, the apothem will be negative.
#[inline]
// Naming note: Various sources are inconsistent as to whether the apothem is the segment between the center and the
// midpoint of a chord, or the length of that segment. Given this confusion, we've opted for the definition
// used by Wolfram MathWorld, which is the distance rather than the segment.
pub fn apothem(&self) -> f32 {
let sign = if self.is_minor() { 1.0 } else { -1.0 };
sign * ops::sqrt(self.radius.squared() - self.half_chord_length().squared())
}
/// Get the length of the sagitta of this arc, that is,
/// the length of the line between the midpoints of the arc and its chord.
/// Equivalently, the height of the triangle whose base is the chord and whose apex is the midpoint of the arc.
///
/// The sagitta is also the sum of the [`radius`](Self::radius) and the [`apothem`](Self::apothem).
pub fn sagitta(&self) -> f32 {
self.radius - self.apothem()
}
/// Produces true if the arc is at most half a circle.
///
/// **Note:** This is not the negation of [`is_major`](Self::is_major): an exact semicircle is both major and minor.
#[inline]
pub const fn is_minor(&self) -> bool {
self.half_angle <= FRAC_PI_2
}
/// Produces true if the arc is at least half a circle.
///
/// **Note:** This is not the negation of [`is_minor`](Self::is_minor): an exact semicircle is both major and minor.
#[inline]
pub const fn is_major(&self) -> bool {
self.half_angle >= FRAC_PI_2
}
}
/// A primitive representing a circular sector: a pie slice of a circle.
///
/// The segment is positioned so that it always includes [`Vec2::Y`] and is vertically symmetrical.
/// To orient the sector differently, apply a rotation.
/// The sector is drawn with the center of its circle at the origin [`Vec2::ZERO`].
///
/// **Warning:** Circular sectors with negative angle or radius, or with angle greater than an entire circle, are not officially supported.
/// We recommend normalizing circular sectors to have an angle in [0, 2π].
#[derive(Clone, Copy, Debug, PartialEq, From)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct CircularSector {
/// The arc defining the sector
#[cfg_attr(all(feature = "serialize", feature = "alloc"), serde(flatten))]
pub arc: Arc2d,
}
impl Primitive2d for CircularSector {}
impl Default for CircularSector {
/// Returns the default [`CircularSector`] with radius `0.5` and covering a third of a circle
fn default() -> Self {
Self::from(Arc2d::default())
}
}
impl Measured2d for CircularSector {
#[inline]
fn area(&self) -> f32 {
self.arc.radius.squared() * self.arc.half_angle
}
#[inline]
fn perimeter(&self) -> f32 {
if self.half_angle() >= PI {
self.arc.radius * 2.0 * PI
} else {
2.0 * self.radius() + self.arc_length()
}
}
}
impl CircularSector {
/// Create a new [`CircularSector`] from a `radius` and an `angle`
#[inline]
pub const fn new(radius: f32, angle: f32) -> Self {
Self {
arc: Arc2d::new(radius, angle),
}
}
/// Create a new [`CircularSector`] from a `radius` and an `angle` in radians.
#[inline]
pub const fn from_radians(radius: f32, angle: f32) -> Self {
Self {
arc: Arc2d::from_radians(radius, angle),
}
}
/// Create a new [`CircularSector`] from a `radius` and an `angle` in degrees.
#[inline]
pub const fn from_degrees(radius: f32, angle: f32) -> Self {
Self {
arc: Arc2d::from_degrees(radius, angle),
}
}
/// Create a new [`CircularSector`] from a `radius` and a number of `turns` of a circle.
///
/// For instance, `0.5` turns is a semicircle.
#[inline]
pub const fn from_turns(radius: f32, fraction: f32) -> Self {
Self {
arc: Arc2d::from_turns(radius, fraction),
}
}
/// Get half the angle of the sector
#[inline]
pub const fn half_angle(&self) -> f32 {
self.arc.half_angle
}
/// Get the angle of the sector
#[inline]
pub const fn angle(&self) -> f32 {
self.arc.angle()
}
/// Get the radius of the sector
#[inline]
pub const fn radius(&self) -> f32 {
self.arc.radius
}
/// Get the length of the arc defining the sector
#[inline]
pub const fn arc_length(&self) -> f32 {
self.arc.length()
}
/// Get half the length of the chord defined by the sector
///
/// See [`Arc2d::half_chord_length`]
#[inline]
pub fn half_chord_length(&self) -> f32 {
self.arc.half_chord_length()
}
/// Get the length of the chord defined by the sector
///
/// See [`Arc2d::chord_length`]
#[inline]
pub fn chord_length(&self) -> f32 {
self.arc.chord_length()
}
/// Get the midpoint of the chord defined by the sector
///
/// See [`Arc2d::chord_midpoint`]
#[inline]
pub fn chord_midpoint(&self) -> Vec2 {
self.arc.chord_midpoint()
}
/// Get the length of the apothem of this sector
///
/// See [`Arc2d::apothem`]
#[inline]
pub fn apothem(&self) -> f32 {
self.arc.apothem()
}
/// Get the length of the sagitta of this sector
///
/// See [`Arc2d::sagitta`]
#[inline]
pub fn sagitta(&self) -> f32 {
self.arc.sagitta()
}
}
/// A primitive representing a circular segment:
/// the area enclosed by the arc of a circle and its chord (the line between its endpoints).
///
/// The segment is drawn starting from [`Vec2::Y`], extending equally on either side.
/// To orient the segment differently, apply a rotation.
/// The segment is drawn with the center of its circle at the origin [`Vec2::ZERO`].
/// When positioning a segment, the [`apothem`](Self::apothem) function may be particularly useful.
///
/// **Warning:** Circular segments with negative angle or radius, or with angle greater than an entire circle, are not officially supported.
/// We recommend normalizing circular segments to have an angle in [0, 2π].
#[derive(Clone, Copy, Debug, PartialEq, From)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct CircularSegment {
/// The arc defining the segment
#[cfg_attr(all(feature = "serialize", feature = "alloc"), serde(flatten))]
pub arc: Arc2d,
}
impl Primitive2d for CircularSegment {}
impl Default for CircularSegment {
/// Returns the default [`CircularSegment`] with radius `0.5` and covering a third of a circle
fn default() -> Self {
Self::from(Arc2d::default())
}
}
impl Measured2d for CircularSegment {
#[inline]
fn area(&self) -> f32 {
0.5 * self.arc.radius.squared() * (self.arc.angle() - ops::sin(self.arc.angle()))
}
#[inline]
fn perimeter(&self) -> f32 {
self.chord_length() + self.arc_length()
}
}
impl CircularSegment {
/// Create a new [`CircularSegment`] from a `radius`, and a `half_angle` in radians.
#[inline]
pub const fn new(radius: f32, half_angle: f32) -> Self {
Self {
arc: Arc2d::new(radius, half_angle),
}
}
/// Create a new [`CircularSegment`] from a `radius` and an `angle` in radians.
#[inline]
pub const fn from_radians(radius: f32, angle: f32) -> Self {
Self {
arc: Arc2d::from_radians(radius, angle),
}
}
/// Create a new [`CircularSegment`] from a `radius` and an `angle` in degrees.
#[inline]
pub const fn from_degrees(radius: f32, angle: f32) -> Self {
Self {
arc: Arc2d::from_degrees(radius, angle),
}
}
/// Create a new [`CircularSegment`] from a `radius` and a number of `turns` of a circle.
///
/// For instance, `0.5` turns is a semicircle.
#[inline]
pub const fn from_turns(radius: f32, fraction: f32) -> Self {
Self {
arc: Arc2d::from_turns(radius, fraction),
}
}
/// Get the half-angle of the segment
#[inline]
pub const fn half_angle(&self) -> f32 {
self.arc.half_angle
}
/// Get the angle of the segment
#[inline]
pub const fn angle(&self) -> f32 {
self.arc.angle()
}
/// Get the radius of the segment
#[inline]
pub const fn radius(&self) -> f32 {
self.arc.radius
}
/// Get the length of the arc defining the segment
#[inline]
pub const fn arc_length(&self) -> f32 {
self.arc.length()
}
/// Get half the length of the segment's base, also known as its chord
#[inline]
#[doc(alias = "half_base_length")]
pub fn half_chord_length(&self) -> f32 {
self.arc.half_chord_length()
}
/// Get the length of the segment's base, also known as its chord
#[inline]
#[doc(alias = "base_length")]
#[doc(alias = "base")]
pub fn chord_length(&self) -> f32 {
self.arc.chord_length()
}
/// Get the midpoint of the segment's base, also known as its chord
#[inline]
#[doc(alias = "base_midpoint")]
pub fn chord_midpoint(&self) -> Vec2 {
self.arc.chord_midpoint()
}
/// Get the length of the apothem of this segment,
/// which is the signed distance between the segment and the center of its circle
///
/// See [`Arc2d::apothem`]
#[inline]
pub fn apothem(&self) -> f32 {
self.arc.apothem()
}
/// Get the length of the sagitta of this segment, also known as its height
///
/// See [`Arc2d::sagitta`]
#[inline]
#[doc(alias = "height")]
pub fn sagitta(&self) -> f32 {
self.arc.sagitta()
}
}
#[cfg(test)]
mod arc_tests {
use core::f32::consts::FRAC_PI_4;
use core::f32::consts::SQRT_2;
use approx::assert_abs_diff_eq;
use super::*;
struct ArcTestCase {
radius: f32,
half_angle: f32,
angle: f32,
length: f32,
right_endpoint: Vec2,
left_endpoint: Vec2,
endpoints: [Vec2; 2],
midpoint: Vec2,
half_chord_length: f32,
chord_length: f32,
chord_midpoint: Vec2,
apothem: f32,
sagitta: f32,
is_minor: bool,
is_major: bool,
sector_area: f32,
sector_perimeter: f32,
segment_area: f32,
segment_perimeter: f32,
}
impl ArcTestCase {
fn check_arc(&self, arc: Arc2d) {
assert_abs_diff_eq!(self.radius, arc.radius);
assert_abs_diff_eq!(self.half_angle, arc.half_angle);
assert_abs_diff_eq!(self.angle, arc.angle());
assert_abs_diff_eq!(self.length, arc.length());
assert_abs_diff_eq!(self.right_endpoint, arc.right_endpoint());
assert_abs_diff_eq!(self.left_endpoint, arc.left_endpoint());
assert_abs_diff_eq!(self.endpoints[0], arc.endpoints()[0]);
assert_abs_diff_eq!(self.endpoints[1], arc.endpoints()[1]);
assert_abs_diff_eq!(self.midpoint, arc.midpoint());
assert_abs_diff_eq!(self.half_chord_length, arc.half_chord_length());
assert_abs_diff_eq!(self.chord_length, arc.chord_length(), epsilon = 0.00001);
assert_abs_diff_eq!(self.chord_midpoint, arc.chord_midpoint());
assert_abs_diff_eq!(self.apothem, arc.apothem());
assert_abs_diff_eq!(self.sagitta, arc.sagitta());
assert_eq!(self.is_minor, arc.is_minor());
assert_eq!(self.is_major, arc.is_major());
}
fn check_sector(&self, sector: CircularSector) {
assert_abs_diff_eq!(self.radius, sector.radius());
assert_abs_diff_eq!(self.half_angle, sector.half_angle());
assert_abs_diff_eq!(self.angle, sector.angle());
assert_abs_diff_eq!(self.half_chord_length, sector.half_chord_length());
assert_abs_diff_eq!(self.chord_length, sector.chord_length(), epsilon = 0.00001);
assert_abs_diff_eq!(self.chord_midpoint, sector.chord_midpoint());
assert_abs_diff_eq!(self.apothem, sector.apothem());
assert_abs_diff_eq!(self.sagitta, sector.sagitta());
assert_abs_diff_eq!(self.sector_area, sector.area());
assert_abs_diff_eq!(self.sector_perimeter, sector.perimeter());
}
fn check_segment(&self, segment: CircularSegment) {
assert_abs_diff_eq!(self.radius, segment.radius());
assert_abs_diff_eq!(self.half_angle, segment.half_angle());
assert_abs_diff_eq!(self.angle, segment.angle());
assert_abs_diff_eq!(self.half_chord_length, segment.half_chord_length());
assert_abs_diff_eq!(self.chord_length, segment.chord_length(), epsilon = 0.00001);
assert_abs_diff_eq!(self.chord_midpoint, segment.chord_midpoint());
assert_abs_diff_eq!(self.apothem, segment.apothem());
assert_abs_diff_eq!(self.sagitta, segment.sagitta());
assert_abs_diff_eq!(self.segment_area, segment.area());
assert_abs_diff_eq!(self.segment_perimeter, segment.perimeter());
}
}
#[test]
fn zero_angle() {
let tests = ArcTestCase {
radius: 1.0,
half_angle: 0.0,
angle: 0.0,
length: 0.0,
left_endpoint: Vec2::Y,
right_endpoint: Vec2::Y,
endpoints: [Vec2::Y, Vec2::Y],
midpoint: Vec2::Y,
half_chord_length: 0.0,
chord_length: 0.0,
chord_midpoint: Vec2::Y,
apothem: 1.0,
sagitta: 0.0,
is_minor: true,
is_major: false,
sector_area: 0.0,
sector_perimeter: 2.0,
segment_area: 0.0,
segment_perimeter: 0.0,
};
tests.check_arc(Arc2d::new(1.0, 0.0));
tests.check_sector(CircularSector::new(1.0, 0.0));
tests.check_segment(CircularSegment::new(1.0, 0.0));
}
#[test]
fn zero_radius() {
let tests = ArcTestCase {
radius: 0.0,
half_angle: FRAC_PI_4,
angle: FRAC_PI_2,
length: 0.0,
left_endpoint: Vec2::ZERO,
right_endpoint: Vec2::ZERO,
endpoints: [Vec2::ZERO, Vec2::ZERO],
midpoint: Vec2::ZERO,
half_chord_length: 0.0,
chord_length: 0.0,
chord_midpoint: Vec2::ZERO,
apothem: 0.0,
sagitta: 0.0,
is_minor: true,
is_major: false,
sector_area: 0.0,
sector_perimeter: 0.0,
segment_area: 0.0,
segment_perimeter: 0.0,
};
tests.check_arc(Arc2d::new(0.0, FRAC_PI_4));
tests.check_sector(CircularSector::new(0.0, FRAC_PI_4));
tests.check_segment(CircularSegment::new(0.0, FRAC_PI_4));
}
#[test]
fn quarter_circle() {
let sqrt_half: f32 = ops::sqrt(0.5);
let tests = ArcTestCase {
radius: 1.0,
half_angle: FRAC_PI_4,
angle: FRAC_PI_2,
length: FRAC_PI_2,
left_endpoint: Vec2::new(-sqrt_half, sqrt_half),
right_endpoint: Vec2::splat(sqrt_half),
endpoints: [Vec2::new(-sqrt_half, sqrt_half), Vec2::splat(sqrt_half)],
midpoint: Vec2::Y,
half_chord_length: sqrt_half,
chord_length: ops::sqrt(2.0),
chord_midpoint: Vec2::new(0.0, sqrt_half),
apothem: sqrt_half,
sagitta: 1.0 - sqrt_half,
is_minor: true,
is_major: false,
sector_area: FRAC_PI_4,
sector_perimeter: FRAC_PI_2 + 2.0,
segment_area: FRAC_PI_4 - 0.5,
segment_perimeter: FRAC_PI_2 + SQRT_2,
};
tests.check_arc(Arc2d::from_turns(1.0, 0.25));
tests.check_sector(CircularSector::from_turns(1.0, 0.25));
tests.check_segment(CircularSegment::from_turns(1.0, 0.25));
}
#[test]
fn half_circle() {
let tests = ArcTestCase {
radius: 1.0,
half_angle: FRAC_PI_2,
angle: PI,
length: PI,
left_endpoint: Vec2::NEG_X,
right_endpoint: Vec2::X,
endpoints: [Vec2::NEG_X, Vec2::X],
midpoint: Vec2::Y,
half_chord_length: 1.0,
chord_length: 2.0,
chord_midpoint: Vec2::ZERO,
apothem: 0.0,
sagitta: 1.0,
is_minor: true,
is_major: true,
sector_area: FRAC_PI_2,
sector_perimeter: PI + 2.0,
segment_area: FRAC_PI_2,
segment_perimeter: PI + 2.0,
};
tests.check_arc(Arc2d::from_radians(1.0, PI));
tests.check_sector(CircularSector::from_radians(1.0, PI));
tests.check_segment(CircularSegment::from_radians(1.0, PI));
}
#[test]
fn full_circle() {
let tests = ArcTestCase {
radius: 1.0,
half_angle: PI,
angle: 2.0 * PI,
length: 2.0 * PI,
left_endpoint: Vec2::NEG_Y,
right_endpoint: Vec2::NEG_Y,
endpoints: [Vec2::NEG_Y, Vec2::NEG_Y],
midpoint: Vec2::Y,
half_chord_length: 0.0,
chord_length: 0.0,
chord_midpoint: Vec2::NEG_Y,
apothem: -1.0,
sagitta: 2.0,
is_minor: false,
is_major: true,
sector_area: PI,
sector_perimeter: 2.0 * PI,
segment_area: PI,
segment_perimeter: 2.0 * PI,
};
tests.check_arc(Arc2d::from_degrees(1.0, 360.0));
tests.check_sector(CircularSector::from_degrees(1.0, 360.0));
tests.check_segment(CircularSegment::from_degrees(1.0, 360.0));
}
}
/// An ellipse primitive, which is like a circle, but the width and height can be different
///
/// Ellipse does not implement [`Inset`] as concentric ellipses do not have parallel curves:
/// if the ellipse is not a circle, the inset shape is not actually an ellipse (although it may look like one) but can also be a lens-like shape.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Ellipse {
/// Half of the width and height of the ellipse.
///
/// This corresponds to the two perpendicular radii defining the ellipse.
pub half_size: Vec2,
}
impl Primitive2d for Ellipse {}
impl Default for Ellipse {
/// Returns the default [`Ellipse`] with a half-width of `1.0` and a half-height of `0.5`.
fn default() -> Self {
Self {
half_size: Vec2::new(1.0, 0.5),
}
}
}
impl Ellipse {
/// Create a new `Ellipse` from half of its width and height.
///
/// This corresponds to the two perpendicular radii defining the ellipse.
#[inline]
pub const fn new(half_width: f32, half_height: f32) -> Self {
Self {
half_size: Vec2::new(half_width, half_height),
}
}
/// Create a new `Ellipse` from a given full size.
///
/// `size.x` is the diameter along the X axis, and `size.y` is the diameter along the Y axis.
#[inline]
pub const fn from_size(size: Vec2) -> Self {
Self {
half_size: Vec2::new(size.x / 2.0, size.y / 2.0),
}
}
#[inline]
/// Returns the [eccentricity](https://en.wikipedia.org/wiki/Eccentricity_(mathematics)) of the ellipse.
/// It can be thought of as a measure of how "stretched" or elongated the ellipse is.
///
/// The value should be in the range [0, 1), where 0 represents a circle, and 1 represents a parabola.
pub fn eccentricity(&self) -> f32 {
let a = self.semi_major();
let b = self.semi_minor();
ops::sqrt(a * a - b * b) / a
}
#[inline]
/// Get the focal length of the ellipse. This corresponds to the distance between one of the foci and the center of the ellipse.
///
/// The focal length of an ellipse is related to its eccentricity by `eccentricity = focal_length / semi_major`
pub fn focal_length(&self) -> f32 {
let a = self.semi_major();
let b = self.semi_minor();
ops::sqrt(a * a - b * b)
}
/// Returns the length of the semi-major axis. This corresponds to the longest radius of the ellipse.
#[inline]
pub fn semi_major(&self) -> f32 {
self.half_size.max_element()
}
/// Returns the length of the semi-minor axis. This corresponds to the shortest radius of the ellipse.
#[inline]
pub fn semi_minor(&self) -> f32 {
self.half_size.min_element()
}
}
impl Measured2d for Ellipse {
/// Get the area of the ellipse
#[inline]
fn area(&self) -> f32 {
PI * self.half_size.x * self.half_size.y
}
#[inline]
/// Get an approximation for the perimeter or circumference of the ellipse.
///
/// The approximation is reasonably precise with a relative error less than 0.007%, getting more precise as the eccentricity of the ellipse decreases.
fn perimeter(&self) -> f32 {
let a = self.semi_major();
let b = self.semi_minor();
// In the case that `a == b`, the ellipse is a circle
if a / b - 1. < 1e-5 {
return PI * (a + b);
};
// In the case that `a` is much larger than `b`, the ellipse is a line
if a / b > 1e4 {
return 4. * a;
};
// These values are the result of (0.5 choose n)^2 where n is the index in the array
// They could be calculated on the fly but hardcoding them yields more accurate and faster results
// because the actual calculation for these values involves factorials and numbers > 10^23
const BINOMIAL_COEFFICIENTS: [f32; 21] = [
1.,
0.25,
0.015625,
0.00390625,
0.0015258789,
0.00074768066,
0.00042057037,
0.00025963783,
0.00017140154,
0.000119028846,
0.00008599834,
0.00006414339,
0.000049109784,
0.000038430585,
0.000030636627,
0.000024815668,
0.000020380836,
0.000016942893,
0.000014236736,
0.000012077564,
0.000010333865,
];
// The algorithm used here is the Gauss-Kummer infinite series expansion of the elliptic integral expression for the perimeter of ellipses
// For more information see https://www.wolframalpha.com/input/?i=gauss-kummer+series
// We only use the terms up to `i == 20` for this approximation
let h = ((a - b) / (a + b)).squared();
PI * (a + b)
* (0..=20)
.map(|i| BINOMIAL_COEFFICIENTS[i] * ops::powf(h, i as f32))
.sum::<f32>()
}
}
/// A primitive shape formed by the region between two circles, also known as a ring.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
#[doc(alias = "Ring")]
pub struct Annulus {
/// The inner circle of the annulus
pub inner_circle: Circle,
/// The outer circle of the annulus
pub outer_circle: Circle,
}
impl Primitive2d for Annulus {}
impl Default for Annulus {
/// Returns the default [`Annulus`] with radii of `0.5` and `1.0`.
fn default() -> Self {
Self {
inner_circle: Circle::new(0.5),
outer_circle: Circle::new(1.0),
}
}
}
impl Annulus {
/// Create a new [`Annulus`] from the radii of the inner and outer circle
#[inline]
pub const fn new(inner_radius: f32, outer_radius: f32) -> Self {
Self {
inner_circle: Circle::new(inner_radius),
outer_circle: Circle::new(outer_radius),
}
}
/// Get the diameter of the annulus
#[inline]
pub const fn diameter(&self) -> f32 {
self.outer_circle.diameter()
}
/// Get the thickness of the annulus
#[inline]
pub const fn thickness(&self) -> f32 {
self.outer_circle.radius - self.inner_circle.radius
}
/// Finds the point on the annulus that is closest to the given `point`:
///
/// - If the point is outside of the annulus completely, the returned point will be on the outer perimeter.
/// - If the point is inside of the inner circle (hole) of the annulus, the returned point will be on the inner perimeter.
/// - Otherwise, the returned point is overlapping the annulus and returned as is.
#[inline]
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/primitives/polygon.rs | crates/bevy_math/src/primitives/polygon.rs | #[cfg(feature = "alloc")]
use {
super::{Measured2d, Triangle2d},
alloc::{collections::BTreeMap, vec::Vec},
core::cmp::Ordering,
};
use crate::Vec2;
#[derive(Debug, Clone, Copy)]
#[cfg(feature = "alloc")]
enum Endpoint {
Left,
Right,
}
/// An event in the [`EventQueue`] is either the left or right vertex of an edge of the polygon.
///
/// Events are ordered so that any event `e1` which is to the left of another event `e2` is less than that event.
/// If `e1.position().x == e2.position().x` the events are ordered from bottom to top.
///
/// This is the order expected by the [`SweepLine`].
#[cfg(feature = "alloc")]
#[derive(Debug, Clone, Copy)]
struct SweepLineEvent {
segment: Segment,
/// Type of the vertex (left or right)
endpoint: Endpoint,
}
#[cfg(feature = "alloc")]
impl SweepLineEvent {
fn position(&self) -> Vec2 {
match self.endpoint {
Endpoint::Left => self.segment.left,
Endpoint::Right => self.segment.right,
}
}
}
#[cfg(feature = "alloc")]
impl PartialEq for SweepLineEvent {
fn eq(&self, other: &Self) -> bool {
self.position() == other.position()
}
}
#[cfg(feature = "alloc")]
impl Eq for SweepLineEvent {}
#[cfg(feature = "alloc")]
impl PartialOrd for SweepLineEvent {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[cfg(feature = "alloc")]
impl Ord for SweepLineEvent {
fn cmp(&self, other: &Self) -> Ordering {
xy_order(self.position(), other.position())
}
}
/// Orders 2D points according to the order expected by the sweep line and event queue from -X to +X and then -Y to Y.
#[cfg(feature = "alloc")]
fn xy_order(a: Vec2, b: Vec2) -> Ordering {
a.x.total_cmp(&b.x).then_with(|| a.y.total_cmp(&b.y))
}
/// The event queue holds an ordered list of all events the [`SweepLine`] will encounter when checking the current polygon.
#[cfg(feature = "alloc")]
#[derive(Debug, Clone)]
struct EventQueue {
events: Vec<SweepLineEvent>,
}
#[cfg(feature = "alloc")]
impl EventQueue {
/// Initialize a new `EventQueue` with all events from the polygon represented by `vertices`.
///
/// The events in the event queue will be ordered.
fn new(vertices: &[Vec2]) -> Self {
if vertices.is_empty() {
return Self { events: Vec::new() };
}
let mut events = Vec::with_capacity(vertices.len() * 2);
for i in 0..vertices.len() {
let v1 = vertices[i];
let v2 = *vertices.get(i + 1).unwrap_or(&vertices[0]);
let (left, right) = if xy_order(v1, v2) == Ordering::Less {
(v1, v2)
} else {
(v2, v1)
};
let segment = Segment {
edge_index: i,
left,
right,
};
events.push(SweepLineEvent {
segment,
endpoint: Endpoint::Left,
});
events.push(SweepLineEvent {
segment,
endpoint: Endpoint::Right,
});
}
events.sort();
Self { events }
}
}
/// Represents a segment or rather an edge of the polygon in the [`SweepLine`].
///
/// Segments are ordered from bottom to top based on their left vertices if possible.
/// If their y values are identical, the segments are ordered based on the y values of their right vertices.
#[derive(Debug, Clone, Copy)]
#[cfg(feature = "alloc")]
struct Segment {
edge_index: usize,
left: Vec2,
right: Vec2,
}
#[cfg(feature = "alloc")]
impl PartialEq for Segment {
fn eq(&self, other: &Self) -> bool {
self.edge_index == other.edge_index
}
}
#[cfg(feature = "alloc")]
impl Eq for Segment {}
#[cfg(feature = "alloc")]
impl PartialOrd for Segment {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[cfg(feature = "alloc")]
impl Ord for Segment {
fn cmp(&self, other: &Self) -> Ordering {
self.left
.y
.total_cmp(&other.left.y)
.then_with(|| self.right.y.total_cmp(&other.right.y))
}
}
/// Holds information about which segment is above and which is below a given [`Segment`]
#[cfg(feature = "alloc")]
#[derive(Debug, Clone, Copy)]
struct SegmentOrder {
above: Option<usize>,
below: Option<usize>,
}
/// A sweep line allows for an efficient search for intersections between [segments](`Segment`).
///
/// It can be thought of as a vertical line sweeping from -X to +X across the polygon that keeps track of the order of the segments
/// the sweep line is intersecting at any given moment.
#[derive(Debug, Clone)]
#[cfg(feature = "alloc")]
struct SweepLine<'a> {
vertices: &'a [Vec2],
tree: BTreeMap<Segment, SegmentOrder>,
}
#[cfg(feature = "alloc")]
impl<'a> SweepLine<'a> {
const fn new(vertices: &'a [Vec2]) -> Self {
Self {
vertices,
tree: BTreeMap::new(),
}
}
/// Determine whether the given edges of the polygon intersect.
fn intersects(&self, edge1: Option<usize>, edge2: Option<usize>) -> bool {
let Some(edge1) = edge1 else {
return false;
};
let Some(edge2) = edge2 else {
return false;
};
// All adjacent edges intersect at their shared vertex
// but these intersections do not count so we ignore them here.
// Likewise a segment will always intersect itself / an identical edge.
if edge1 == edge2
|| (edge1 + 1) % self.vertices.len() == edge2
|| (edge2 + 1) % self.vertices.len() == edge1
{
return false;
}
let s11 = self.vertices[edge1];
let s12 = *self.vertices.get(edge1 + 1).unwrap_or(&self.vertices[0]);
let s21 = self.vertices[edge2];
let s22 = *self.vertices.get(edge2 + 1).unwrap_or(&self.vertices[0]);
// When both points of the second edge are on the same side of the first edge, no intersection is possible.
if point_side(s11, s12, s21) * point_side(s11, s12, s22) > 0.0 {
return false;
}
if point_side(s21, s22, s11) * point_side(s21, s22, s12) > 0.0 {
return false;
}
true
}
/// Add a new segment to the sweep line
fn add(&mut self, s: Segment) -> SegmentOrder {
let above = if let Some((next_s, next_ord)) = self.tree.range_mut(s..).next() {
next_ord.below.replace(s.edge_index);
Some(next_s.edge_index)
} else {
None
};
let below = if let Some((prev_s, prev_ord)) = self.tree.range_mut(..s).next_back() {
prev_ord.above.replace(s.edge_index);
Some(prev_s.edge_index)
} else {
None
};
let s_ord = SegmentOrder { above, below };
self.tree.insert(s, s_ord);
s_ord
}
/// Get the segment order for the given segment.
///
/// If `s` has not been added to the [`SweepLine`] `None` will be returned.
fn find(&self, s: &Segment) -> Option<&SegmentOrder> {
self.tree.get(s)
}
/// Remove `s` from the [`SweepLine`].
fn remove(&mut self, s: &Segment) {
let Some(s_ord) = self.tree.get(s).copied() else {
return;
};
if let Some((_, above_ord)) = self.tree.range_mut(s..).next() {
above_ord.below = s_ord.below;
}
if let Some((_, below_ord)) = self.tree.range_mut(..s).next_back() {
below_ord.above = s_ord.above;
}
self.tree.remove(s);
}
}
/// Test what side of the line through `p1` and `p2` `q` is.
///
/// The result will be `0` if the `q` is on the segment, negative for one side and positive for the other.
#[cfg_attr(
not(feature = "alloc"),
expect(
dead_code,
reason = "this function is only used with the alloc feature"
)
)]
#[inline]
const fn point_side(p1: Vec2, p2: Vec2, q: Vec2) -> f32 {
(p2.x - p1.x) * (q.y - p1.y) - (q.x - p1.x) * (p2.y - p1.y)
}
/// Tests whether the `vertices` describe a simple polygon.
/// The last vertex must not be equal to the first vertex.
///
/// A polygon is simple if it is not self intersecting and not self tangent.
/// As such, no two edges of the polygon may cross each other and each vertex must not lie on another edge.
///
/// Any 'polygon' with less than three vertices is simple.
///
/// The algorithm used is the Shamos-Hoey algorithm, a version of the Bentley-Ottman algorithm adapted to only detect whether any intersections exist.
/// This function will run in O(n * log n)
#[cfg(feature = "alloc")]
pub fn is_polygon_simple(vertices: &[Vec2]) -> bool {
if vertices.len() < 3 {
return true;
}
if vertices.len() == 3 {
return Triangle2d::new(vertices[0], vertices[1], vertices[2]).area() > 0.0;
}
let event_queue = EventQueue::new(vertices);
let mut sweep_line = SweepLine::new(vertices);
for e in event_queue.events {
match e.endpoint {
Endpoint::Left => {
let s = sweep_line.add(e.segment);
if sweep_line.intersects(Some(e.segment.edge_index), s.above)
|| sweep_line.intersects(Some(e.segment.edge_index), s.below)
{
return false;
}
}
Endpoint::Right => {
if let Some(s) = sweep_line.find(&e.segment) {
if sweep_line.intersects(s.above, s.below) {
return false;
}
sweep_line.remove(&e.segment);
}
}
}
}
true
}
#[cfg(test)]
mod tests {
use crate::{primitives::polygon::is_polygon_simple, Vec2};
#[test]
fn complex_polygon() {
// A square with one side punching through the opposite side.
let verts = [Vec2::ZERO, Vec2::X, Vec2::ONE, Vec2::Y, Vec2::new(2.0, 0.5)];
assert!(!is_polygon_simple(&verts));
// A square with a vertex from one side touching the opposite side.
let verts = [Vec2::ZERO, Vec2::X, Vec2::ONE, Vec2::Y, Vec2::new(1.0, 0.5)];
assert!(!is_polygon_simple(&verts));
// A square with one side touching the opposite side.
let verts = [
Vec2::ZERO,
Vec2::X,
Vec2::ONE,
Vec2::Y,
Vec2::new(1.0, 0.6),
Vec2::new(1.0, 0.4),
];
assert!(!is_polygon_simple(&verts));
// Four points lying on a line
let verts = [Vec2::ONE, Vec2::new(3., 2.), Vec2::new(5., 3.), Vec2::NEG_X];
assert!(!is_polygon_simple(&verts));
// Three points lying on a line
let verts = [Vec2::ONE, Vec2::new(3., 2.), Vec2::NEG_X];
assert!(!is_polygon_simple(&verts));
// Two identical points and one other point
let verts = [Vec2::ONE, Vec2::ONE, Vec2::NEG_X];
assert!(!is_polygon_simple(&verts));
// Two triangles with one shared side
let verts = [Vec2::ZERO, Vec2::X, Vec2::Y, Vec2::ONE, Vec2::X, Vec2::Y];
assert!(!is_polygon_simple(&verts));
}
#[test]
fn simple_polygon() {
// A square
let verts = [Vec2::ZERO, Vec2::X, Vec2::ONE, Vec2::Y];
assert!(is_polygon_simple(&verts));
let verts = [];
assert!(is_polygon_simple(&verts));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/primitives/inset.rs | crates/bevy_math/src/primitives/inset.rs | use crate::{
ops,
primitives::{
Capsule2d, Circle, CircularSegment, Primitive2d, Rectangle, RegularPolygon, Rhombus,
Triangle2d,
},
Vec2,
};
/// A primitive that can be resized uniformly.
///
/// See documentation on [`Inset::inset`].
///
/// See also [`ToRing`](crate::primitives::ToRing).
pub trait Inset: Primitive2d {
/// Create a new version of this primitive that is resized uniformly.
/// That is, it resizes the shape inwards such that for the lines between vertices,
/// it creates new parallel lines that are `distance` inwards from the original lines.
///
/// This is useful for creating smaller shapes or making outlines of `distance` thickness with [`Ring`](crate::primitives::Ring).
///
/// See also [`ToRing::to_ring`](crate::primitives::ToRing::to_ring)
fn inset(self, distance: f32) -> Self;
}
impl Inset for Circle {
fn inset(mut self, distance: f32) -> Self {
self.radius -= distance;
self
}
}
impl Inset for Triangle2d {
fn inset(self, distance: f32) -> Self {
fn find_inset_point(a: Vec2, b: Vec2, c: Vec2, distance: f32) -> Vec2 {
let unit_vector_ab = (b - a).normalize();
let unit_vector_ac = (c - a).normalize();
let half_angle_bac = unit_vector_ab.angle_to(unit_vector_ac) / 2.0;
let mean = (unit_vector_ab + unit_vector_ac) / 2.0;
let direction = mean.normalize();
let magnitude = distance / ops::sin(half_angle_bac);
a + direction * magnitude
}
let [a, b, c] = self.vertices;
let new_a = find_inset_point(a, b, c, distance);
let new_b = find_inset_point(b, c, a, distance);
let new_c = find_inset_point(c, a, b, distance);
Self::new(new_a, new_b, new_c)
}
}
impl Inset for Rhombus {
fn inset(mut self, distance: f32) -> Self {
let [half_width, half_height] = self.half_diagonals.into();
let angle = ops::atan(half_height / half_width);
let x_offset = distance / ops::sin(angle);
let y_offset = distance / ops::cos(angle);
self.half_diagonals -= Vec2::new(x_offset, y_offset);
self
}
}
impl Inset for Capsule2d {
fn inset(mut self, distance: f32) -> Self {
self.radius -= distance;
self
}
}
impl Inset for Rectangle {
fn inset(mut self, distance: f32) -> Self {
self.half_size -= Vec2::splat(distance);
self
}
}
impl Inset for CircularSegment {
fn inset(self, distance: f32) -> Self {
let old_arc = self.arc;
let radius = old_arc.radius - distance;
let apothem = old_arc.apothem() + distance;
// https://en.wikipedia.org/wiki/Circular_segment
let half_angle = ops::acos(apothem / radius);
Self::new(radius, half_angle)
}
}
impl Inset for RegularPolygon {
fn inset(mut self, distance: f32) -> Self {
let half_angle = self.internal_angle_radians() / 2.0;
let offset = distance / ops::sin(half_angle);
self.circumcircle.radius -= offset;
self
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/primitives/mod.rs | crates/bevy_math/src/primitives/mod.rs | //! This module defines primitive shapes.
//! The origin is (0, 0) for 2D primitives and (0, 0, 0) for 3D primitives,
//! unless stated otherwise.
mod dim2;
pub use dim2::*;
mod dim3;
pub use dim3::*;
mod inset;
pub use inset::*;
mod polygon;
/// A marker trait for 2D primitives
pub trait Primitive2d {}
/// A marker trait for 3D primitives
pub trait Primitive3d {}
/// The winding order for a set of points
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[doc(alias = "Orientation")]
pub enum WindingOrder {
/// A clockwise winding order
Clockwise,
/// A counterclockwise winding order
#[doc(alias = "AntiClockwise")]
CounterClockwise,
/// An invalid winding order indicating that it could not be computed reliably.
/// This often happens in *degenerate cases* where the points lie on the same line
#[doc(alias("Degenerate", "Collinear"))]
Invalid,
}
/// A trait for getting measurements of 2D shapes
pub trait Measured2d {
/// Get the perimeter of the shape
fn perimeter(&self) -> f32;
/// Get the area of the shape
fn area(&self) -> f32;
}
/// A trait for getting measurements of 3D shapes
pub trait Measured3d {
/// Get the surface area of the shape
fn area(&self) -> f32;
/// Get the volume of the shape
fn volume(&self) -> f32;
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/primitives/dim3.rs | crates/bevy_math/src/primitives/dim3.rs | use core::f32::consts::{FRAC_PI_3, PI};
use super::{Circle, Measured2d, Measured3d, Primitive2d, Primitive3d};
use crate::{
ops::{self, FloatPow},
Dir3, InvalidDirectionError, Isometry3d, Mat3, Ray3d, Vec2, Vec3,
};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
#[cfg(all(feature = "serialize", feature = "bevy_reflect"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
use glam::Quat;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
/// A sphere primitive, representing the set of all points some distance from the origin
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Sphere {
/// The radius of the sphere
pub radius: f32,
}
impl Primitive3d for Sphere {}
impl Default for Sphere {
/// Returns the default [`Sphere`] with a radius of `0.5`.
fn default() -> Self {
Self { radius: 0.5 }
}
}
impl Sphere {
/// Create a new [`Sphere`] from a `radius`
#[inline]
pub const fn new(radius: f32) -> Self {
Self { radius }
}
/// Get the diameter of the sphere
#[inline]
pub const fn diameter(&self) -> f32 {
2.0 * self.radius
}
/// Finds the point on the sphere that is closest to the given `point`.
///
/// If the point is outside the sphere, the returned point will be on the surface of the sphere.
/// Otherwise, it will be inside the sphere and returned as is.
#[inline]
pub fn closest_point(&self, point: Vec3) -> Vec3 {
let distance_squared = point.length_squared();
if distance_squared <= self.radius.squared() {
// The point is inside the sphere.
point
} else {
// The point is outside the sphere.
// Find the closest point on the surface of the sphere.
let dir_to_point = point / ops::sqrt(distance_squared);
self.radius * dir_to_point
}
}
}
impl Measured3d for Sphere {
/// Get the surface area of the sphere
#[inline]
fn area(&self) -> f32 {
4.0 * PI * self.radius.squared()
}
/// Get the volume of the sphere
#[inline]
fn volume(&self) -> f32 {
4.0 * FRAC_PI_3 * self.radius.cubed()
}
}
/// A bounded plane in 3D space. It forms a surface starting from the origin with a defined height and width.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Plane3d {
/// The normal of the plane. The plane will be placed perpendicular to this direction
pub normal: Dir3,
/// Half of the width and height of the plane
pub half_size: Vec2,
}
impl Primitive3d for Plane3d {}
impl Default for Plane3d {
/// Returns the default [`Plane3d`] with a normal pointing in the `+Y` direction, width and height of `1.0`.
fn default() -> Self {
Self {
normal: Dir3::Y,
half_size: Vec2::splat(0.5),
}
}
}
impl Plane3d {
/// Create a new `Plane3d` from a normal and a half size
///
/// # Panics
///
/// Panics if the given `normal` is zero (or very close to zero), or non-finite.
#[inline]
pub fn new(normal: Vec3, half_size: Vec2) -> Self {
Self {
normal: Dir3::new(normal).expect("normal must be nonzero and finite"),
half_size,
}
}
/// Create a new `Plane3d` based on three points and compute the geometric center
/// of those points.
///
/// The direction of the plane normal is determined by the winding order
/// of the triangular shape formed by the points.
///
/// # Panics
///
/// Panics if a valid normal can not be computed, for example when the points
/// are *collinear* and lie on the same line.
#[inline]
pub fn from_points(a: Vec3, b: Vec3, c: Vec3) -> (Self, Vec3) {
let normal = Dir3::new((b - a).cross(c - a)).expect(
"finite plane must be defined by three finite points that don't lie on the same line",
);
let translation = (a + b + c) / 3.0;
(
Self {
normal,
..Default::default()
},
translation,
)
}
}
impl Measured2d for Plane3d {
#[inline]
fn area(&self) -> f32 {
self.half_size.element_product() * 4.0
}
#[inline]
fn perimeter(&self) -> f32 {
self.half_size.element_sum() * 4.0
}
}
/// An unbounded plane in 3D space. It forms a separating surface through the origin,
/// stretching infinitely far
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct InfinitePlane3d {
/// The normal of the plane. The plane will be placed perpendicular to this direction
pub normal: Dir3,
}
impl Primitive3d for InfinitePlane3d {}
impl Default for InfinitePlane3d {
/// Returns the default [`InfinitePlane3d`] with a normal pointing in the `+Y` direction.
fn default() -> Self {
Self { normal: Dir3::Y }
}
}
impl InfinitePlane3d {
/// Create a new `InfinitePlane3d` from a normal
///
/// # Panics
///
/// Panics if the given `normal` is zero (or very close to zero), or non-finite.
#[inline]
pub fn new<T: TryInto<Dir3>>(normal: T) -> Self
where
<T as TryInto<Dir3>>::Error: core::fmt::Debug,
{
Self {
normal: normal
.try_into()
.expect("normal must be nonzero and finite"),
}
}
/// Create a new `InfinitePlane3d` based on three points and compute the geometric center
/// of those points.
///
/// The direction of the plane normal is determined by the winding order
/// of the triangular shape formed by the points.
///
/// # Panics
///
/// Panics if a valid normal can not be computed, for example when the points
/// are *collinear* and lie on the same line.
#[inline]
pub fn from_points(a: Vec3, b: Vec3, c: Vec3) -> (Self, Vec3) {
let normal = Dir3::new((b - a).cross(c - a)).expect(
"infinite plane must be defined by three finite points that don't lie on the same line",
);
let translation = (a + b + c) / 3.0;
(Self { normal }, translation)
}
/// Computes the shortest distance between a plane transformed with the given `isometry` and a
/// `point`. The result is a signed value; it's positive if the point lies in the half-space
/// that the plane's normal vector points towards.
#[inline]
pub fn signed_distance(&self, isometry: impl Into<Isometry3d>, point: Vec3) -> f32 {
let isometry = isometry.into();
self.normal.dot(isometry.inverse() * point)
}
/// Injects the `point` into this plane transformed with the given `isometry`.
///
/// This projects the point orthogonally along the shortest path onto the plane.
#[inline]
pub fn project_point(&self, isometry: impl Into<Isometry3d>, point: Vec3) -> Vec3 {
point - self.normal * self.signed_distance(isometry, point)
}
/// Computes an [`Isometry3d`] which transforms points from the plane in 3D space with the given
/// `origin` to the XY-plane.
///
/// ## Guarantees
///
/// * the transformation is a [congruence] meaning it will preserve all distances and angles of
/// the transformed geometry
/// * uses the least rotation possible to transform the geometry
/// * if two geometries are transformed with the same isometry, then the relations between
/// them, like distances, are also preserved
/// * compared to projections, the transformation is lossless (up to floating point errors)
/// reversible
///
/// ## Non-Guarantees
///
/// * the rotation used is generally not unique
/// * the orientation of the transformed geometry in the XY plane might be arbitrary, to
/// enforce some kind of alignment the user has to use an extra transformation ontop of this
/// one
///
/// See [`isometries_xy`] for example usescases.
///
/// [congruence]: https://en.wikipedia.org/wiki/Congruence_(geometry)
/// [`isometries_xy`]: `InfinitePlane3d::isometries_xy`
#[inline]
pub fn isometry_into_xy(&self, origin: Vec3) -> Isometry3d {
let rotation = Quat::from_rotation_arc(self.normal.as_vec3(), Vec3::Z);
let transformed_origin = rotation * origin;
Isometry3d::new(-Vec3::Z * transformed_origin.z, rotation)
}
/// Computes an [`Isometry3d`] which transforms points from the XY-plane to this plane with the
/// given `origin`.
///
/// ## Guarantees
///
/// * the transformation is a [congruence] meaning it will preserve all distances and angles of
/// the transformed geometry
/// * uses the least rotation possible to transform the geometry
/// * if two geometries are transformed with the same isometry, then the relations between
/// them, like distances, are also preserved
/// * compared to projections, the transformation is lossless (up to floating point errors)
/// reversible
///
/// ## Non-Guarantees
///
/// * the rotation used is generally not unique
/// * the orientation of the transformed geometry in the XY plane might be arbitrary, to
/// enforce some kind of alignment the user has to use an extra transformation ontop of this
/// one
///
/// See [`isometries_xy`] for example usescases.
///
/// [congruence]: https://en.wikipedia.org/wiki/Congruence_(geometry)
/// [`isometries_xy`]: `InfinitePlane3d::isometries_xy`
#[inline]
pub fn isometry_from_xy(&self, origin: Vec3) -> Isometry3d {
self.isometry_into_xy(origin).inverse()
}
/// Computes both [isometries] which transforms points from the plane in 3D space with the
/// given `origin` to the XY-plane and back.
///
/// [isometries]: `Isometry3d`
///
/// # Example
///
/// The projection and its inverse can be used to run 2D algorithms on flat shapes in 3D. The
/// workflow would usually look like this:
///
/// ```
/// # use bevy_math::{Vec3, Dir3};
/// # use bevy_math::primitives::InfinitePlane3d;
///
/// let triangle_3d @ [a, b, c] = [Vec3::X, Vec3::Y, Vec3::Z];
/// let center = (a + b + c) / 3.0;
///
/// let plane = InfinitePlane3d::new(Vec3::ONE);
///
/// let (to_xy, from_xy) = plane.isometries_xy(center);
///
/// let triangle_2d = triangle_3d.map(|vec3| to_xy * vec3).map(|vec3| vec3.truncate());
///
/// // apply some algorithm to `triangle_2d`
///
/// let triangle_3d = triangle_2d.map(|vec2| vec2.extend(0.0)).map(|vec3| from_xy * vec3);
/// ```
#[inline]
pub fn isometries_xy(&self, origin: Vec3) -> (Isometry3d, Isometry3d) {
let projection = self.isometry_into_xy(origin);
(projection, projection.inverse())
}
}
/// An infinite line going through the origin along a direction in 3D space.
///
/// For a finite line: [`Segment3d`]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Line3d {
/// The direction of the line
pub direction: Dir3,
}
impl Primitive3d for Line3d {}
/// A line segment defined by two endpoints in 3D space.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
#[doc(alias = "LineSegment3d")]
pub struct Segment3d {
/// The endpoints of the line segment.
pub vertices: [Vec3; 2],
}
impl Primitive3d for Segment3d {}
impl Default for Segment3d {
fn default() -> Self {
Self {
vertices: [Vec3::new(-0.5, 0.0, 0.0), Vec3::new(0.5, 0.0, 0.0)],
}
}
}
impl Segment3d {
/// Create a new `Segment3d` from its endpoints.
#[inline]
pub const fn new(point1: Vec3, point2: Vec3) -> Self {
Self {
vertices: [point1, point2],
}
}
/// Create a new `Segment3d` centered at the origin with the given direction and length.
///
/// The endpoints will be at `-direction * length / 2.0` and `direction * length / 2.0`.
#[inline]
pub fn from_direction_and_length(direction: Dir3, length: f32) -> Self {
let endpoint = 0.5 * length * direction;
Self {
vertices: [-endpoint, endpoint],
}
}
/// Create a new `Segment3d` centered at the origin from a vector representing
/// the direction and length of the line segment.
///
/// The endpoints will be at `-scaled_direction / 2.0` and `scaled_direction / 2.0`.
#[inline]
pub fn from_scaled_direction(scaled_direction: Vec3) -> Self {
let endpoint = 0.5 * scaled_direction;
Self {
vertices: [-endpoint, endpoint],
}
}
/// Create a new `Segment3d` starting from the origin of the given `ray`,
/// going in the direction of the ray for the given `length`.
///
/// The endpoints will be at `ray.origin` and `ray.origin + length * ray.direction`.
#[inline]
pub fn from_ray_and_length(ray: Ray3d, length: f32) -> Self {
Self {
vertices: [ray.origin, ray.get_point(length)],
}
}
/// Get the position of the first endpoint of the line segment.
#[inline]
pub const fn point1(&self) -> Vec3 {
self.vertices[0]
}
/// Get the position of the second endpoint of the line segment.
#[inline]
pub const fn point2(&self) -> Vec3 {
self.vertices[1]
}
/// Compute the midpoint between the two endpoints of the line segment.
#[inline]
#[doc(alias = "midpoint")]
pub fn center(&self) -> Vec3 {
self.point1().midpoint(self.point2())
}
/// Compute the length of the line segment.
#[inline]
pub fn length(&self) -> f32 {
self.point1().distance(self.point2())
}
/// Compute the squared length of the line segment.
#[inline]
pub fn length_squared(&self) -> f32 {
self.point1().distance_squared(self.point2())
}
/// Compute the normalized direction pointing from the first endpoint to the second endpoint.
///
/// For the non-panicking version, see [`Segment3d::try_direction`].
///
/// # Panics
///
/// Panics if a valid direction could not be computed, for example when the endpoints are coincident, NaN, or infinite.
#[inline]
pub fn direction(&self) -> Dir3 {
self.try_direction().unwrap_or_else(|err| {
panic!("Failed to compute the direction of a line segment: {err}")
})
}
/// Try to compute the normalized direction pointing from the first endpoint to the second endpoint.
///
/// Returns [`Err(InvalidDirectionError)`](InvalidDirectionError) if a valid direction could not be computed,
/// for example when the endpoints are coincident, NaN, or infinite.
#[inline]
pub fn try_direction(&self) -> Result<Dir3, InvalidDirectionError> {
Dir3::new(self.scaled_direction())
}
/// Compute the vector from the first endpoint to the second endpoint.
#[inline]
pub fn scaled_direction(&self) -> Vec3 {
self.point2() - self.point1()
}
/// Compute the segment transformed by the given [`Isometry3d`].
#[inline]
pub fn transformed(&self, isometry: impl Into<Isometry3d>) -> Self {
let isometry: Isometry3d = isometry.into();
Self::new(
isometry.transform_point(self.point1()).into(),
isometry.transform_point(self.point2()).into(),
)
}
/// Compute the segment translated by the given vector.
#[inline]
pub fn translated(&self, translation: Vec3) -> Segment3d {
Self::new(self.point1() + translation, self.point2() + translation)
}
/// Compute the segment rotated around the origin by the given rotation.
#[inline]
pub fn rotated(&self, rotation: Quat) -> Segment3d {
Segment3d::new(rotation * self.point1(), rotation * self.point2())
}
/// Compute the segment rotated around the given point by the given rotation.
#[inline]
pub fn rotated_around(&self, rotation: Quat, point: Vec3) -> Segment3d {
// We offset our segment so that our segment is rotated as if from the origin, then we can apply the offset back
let offset = self.translated(-point);
let rotated = offset.rotated(rotation);
rotated.translated(point)
}
/// Compute the segment rotated around its own center.
#[inline]
pub fn rotated_around_center(&self, rotation: Quat) -> Segment3d {
self.rotated_around(rotation, self.center())
}
/// Compute the segment with its center at the origin, keeping the same direction and length.
#[inline]
pub fn centered(&self) -> Segment3d {
let center = self.center();
self.translated(-center)
}
/// Compute the segment with a new length, keeping the same direction and center.
#[inline]
pub fn resized(&self, length: f32) -> Segment3d {
let offset_from_origin = self.center();
let centered = self.translated(-offset_from_origin);
let ratio = length / self.length();
let segment = Segment3d::new(centered.point1() * ratio, centered.point2() * ratio);
segment.translated(offset_from_origin)
}
/// Reverses the direction of the line segment by swapping the endpoints.
#[inline]
pub fn reverse(&mut self) {
let [point1, point2] = &mut self.vertices;
core::mem::swap(point1, point2);
}
/// Returns the line segment with its direction reversed by swapping the endpoints.
#[inline]
#[must_use]
pub fn reversed(mut self) -> Self {
self.reverse();
self
}
/// Returns the point on the [`Segment3d`] that is closest to the specified `point`.
#[inline]
pub fn closest_point(&self, point: Vec3) -> Vec3 {
// `point`
// x
// ^|
// / |
//`offset`/ |
// / | `segment_vector`
// x----.-------------->x
// 0 t 1
let segment_vector = self.vertices[1] - self.vertices[0];
let offset = point - self.vertices[0];
// The signed projection of `offset` onto `segment_vector`, scaled by the length of the segment.
let projection_scaled = segment_vector.dot(offset);
// `point` is too far "left" in the picture
if projection_scaled <= 0.0 {
return self.vertices[0];
}
let length_squared = segment_vector.length_squared();
// `point` is too far "right" in the picture
if projection_scaled >= length_squared {
return self.vertices[1];
}
// Point lies somewhere in the middle, we compute the closest point by finding the parameter along the line.
let t = projection_scaled / length_squared;
self.vertices[0] + t * segment_vector
}
}
impl From<[Vec3; 2]> for Segment3d {
#[inline]
fn from(vertices: [Vec3; 2]) -> Self {
Self { vertices }
}
}
impl From<(Vec3, Vec3)> for Segment3d {
#[inline]
fn from((point1, point2): (Vec3, Vec3)) -> Self {
Self::new(point1, point2)
}
}
/// A series of connected line segments in 3D space.
#[cfg(feature = "alloc")]
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Polyline3d {
/// The vertices of the polyline
pub vertices: Vec<Vec3>,
}
#[cfg(feature = "alloc")]
impl Primitive3d for Polyline3d {}
#[cfg(feature = "alloc")]
impl FromIterator<Vec3> for Polyline3d {
fn from_iter<I: IntoIterator<Item = Vec3>>(iter: I) -> Self {
Self {
vertices: iter.into_iter().collect(),
}
}
}
#[cfg(feature = "alloc")]
impl Default for Polyline3d {
fn default() -> Self {
Self::new([Vec3::new(-0.5, 0.0, 0.0), Vec3::new(0.5, 0.0, 0.0)])
}
}
#[cfg(feature = "alloc")]
impl Polyline3d {
/// Create a new `Polyline3d` from its vertices
pub fn new(vertices: impl IntoIterator<Item = Vec3>) -> Self {
Self::from_iter(vertices)
}
/// Create a new `Polyline3d` from two endpoints with subdivision points.
/// `subdivisions = 0` creates a simple line with just start and end points.
/// `subdivisions = 1` adds one point in the middle, creating 2 segments, etc.
pub fn with_subdivisions(start: Vec3, end: Vec3, subdivisions: usize) -> Self {
let total_vertices = subdivisions + 2;
let mut vertices = Vec::with_capacity(total_vertices);
let step = (end - start) / (subdivisions + 1) as f32;
for i in 0..total_vertices {
vertices.push(start + step * i as f32);
}
Self { vertices }
}
}
/// A cuboid primitive, which is like a cube, except that the x, y, and z dimensions are not
/// required to be the same.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Cuboid {
/// Half of the width, height and depth of the cuboid
pub half_size: Vec3,
}
impl Primitive3d for Cuboid {}
impl Default for Cuboid {
/// Returns the default [`Cuboid`] with a width, height, and depth of `1.0`.
fn default() -> Self {
Self {
half_size: Vec3::splat(0.5),
}
}
}
impl Cuboid {
/// Create a new `Cuboid` from a full x, y, and z length
#[inline]
pub const fn new(x_length: f32, y_length: f32, z_length: f32) -> Self {
Self::from_size(Vec3::new(x_length, y_length, z_length))
}
/// Create a new `Cuboid` from a given full size
#[inline]
pub const fn from_size(size: Vec3) -> Self {
Self {
half_size: Vec3::new(size.x / 2.0, size.y / 2.0, size.z / 2.0),
}
}
/// Create a new `Cuboid` from two corner points
#[inline]
pub fn from_corners(point1: Vec3, point2: Vec3) -> Self {
Self {
half_size: (point2 - point1).abs() / 2.0,
}
}
/// Create a `Cuboid` from a single length.
/// The resulting `Cuboid` will be the same size in every direction.
#[inline]
pub const fn from_length(length: f32) -> Self {
Self {
half_size: Vec3::splat(length / 2.0),
}
}
/// Get the size of the cuboid
#[inline]
pub fn size(&self) -> Vec3 {
2.0 * self.half_size
}
/// Finds the point on the cuboid that is closest to the given `point`.
///
/// If the point is outside the cuboid, the returned point will be on the surface of the cuboid.
/// Otherwise, it will be inside the cuboid and returned as is.
#[inline]
pub fn closest_point(&self, point: Vec3) -> Vec3 {
// Clamp point coordinates to the cuboid
point.clamp(-self.half_size, self.half_size)
}
}
impl Measured3d for Cuboid {
/// Get the surface area of the cuboid
#[inline]
fn area(&self) -> f32 {
8.0 * (self.half_size.x * self.half_size.y
+ self.half_size.y * self.half_size.z
+ self.half_size.x * self.half_size.z)
}
/// Get the volume of the cuboid
#[inline]
fn volume(&self) -> f32 {
8.0 * self.half_size.x * self.half_size.y * self.half_size.z
}
}
/// A cylinder primitive centered on the origin
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Cylinder {
/// The radius of the cylinder
pub radius: f32,
/// The half height of the cylinder
pub half_height: f32,
}
impl Primitive3d for Cylinder {}
impl Default for Cylinder {
/// Returns the default [`Cylinder`] with a radius of `0.5` and a height of `1.0`.
fn default() -> Self {
Self {
radius: 0.5,
half_height: 0.5,
}
}
}
impl Cylinder {
/// Create a new `Cylinder` from a radius and full height
#[inline]
pub const fn new(radius: f32, height: f32) -> Self {
Self {
radius,
half_height: height / 2.0,
}
}
/// Get the base of the cylinder as a [`Circle`]
#[inline]
pub const fn base(&self) -> Circle {
Circle {
radius: self.radius,
}
}
/// Get the surface area of the side of the cylinder,
/// also known as the lateral area
#[inline]
#[doc(alias = "side_area")]
pub const fn lateral_area(&self) -> f32 {
4.0 * PI * self.radius * self.half_height
}
/// Get the surface area of one base of the cylinder
#[inline]
pub fn base_area(&self) -> f32 {
PI * self.radius.squared()
}
}
impl Measured3d for Cylinder {
/// Get the total surface area of the cylinder
#[inline]
fn area(&self) -> f32 {
2.0 * PI * self.radius * (self.radius + 2.0 * self.half_height)
}
/// Get the volume of the cylinder
#[inline]
fn volume(&self) -> f32 {
self.base_area() * 2.0 * self.half_height
}
}
/// A 3D capsule primitive centered on the origin
/// A three-dimensional capsule is defined as a surface at a distance (radius) from a line
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Capsule3d {
/// The radius of the capsule
pub radius: f32,
/// Half the height of the capsule, excluding the hemispheres
pub half_length: f32,
}
impl Primitive3d for Capsule3d {}
impl Default for Capsule3d {
/// Returns the default [`Capsule3d`] with a radius of `0.5` and a segment length of `1.0`.
/// The total height is `2.0`.
fn default() -> Self {
Self {
radius: 0.5,
half_length: 0.5,
}
}
}
impl Capsule3d {
/// Create a new `Capsule3d` from a radius and length
pub const fn new(radius: f32, length: f32) -> Self {
Self {
radius,
half_length: length / 2.0,
}
}
/// Get the part connecting the hemispherical ends
/// of the capsule as a [`Cylinder`]
#[inline]
pub const fn to_cylinder(&self) -> Cylinder {
Cylinder {
radius: self.radius,
half_height: self.half_length,
}
}
}
impl Measured3d for Capsule3d {
/// Get the surface area of the capsule
#[inline]
fn area(&self) -> f32 {
// Modified version of 2pi * r * (2r + h)
4.0 * PI * self.radius * (self.radius + self.half_length)
}
/// Get the volume of the capsule
#[inline]
fn volume(&self) -> f32 {
// Modified version of pi * r^2 * (4/3 * r + a)
let diameter = self.radius * 2.0;
PI * self.radius * diameter * (diameter / 3.0 + self.half_length)
}
}
/// A cone primitive centered on the midpoint between the tip of the cone and the center of its base.
///
/// The cone is oriented with its tip pointing towards the Y axis.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Cone {
/// The radius of the base
pub radius: f32,
/// The height of the cone
pub height: f32,
}
impl Primitive3d for Cone {}
impl Default for Cone {
/// Returns the default [`Cone`] with a base radius of `0.5` and a height of `1.0`.
fn default() -> Self {
Self {
radius: 0.5,
height: 1.0,
}
}
}
impl Cone {
/// Create a new [`Cone`] from a radius and height.
pub const fn new(radius: f32, height: f32) -> Self {
Self { radius, height }
}
/// Get the base of the cone as a [`Circle`]
#[inline]
pub const fn base(&self) -> Circle {
Circle {
radius: self.radius,
}
}
/// Get the slant height of the cone, the length of the line segment
/// connecting a point on the base to the apex
#[inline]
#[doc(alias = "side_length")]
pub fn slant_height(&self) -> f32 {
ops::hypot(self.radius, self.height)
}
/// Get the surface area of the side of the cone,
/// also known as the lateral area
#[inline]
#[doc(alias = "side_area")]
pub fn lateral_area(&self) -> f32 {
PI * self.radius * self.slant_height()
}
/// Get the surface area of the base of the cone
#[inline]
pub fn base_area(&self) -> f32 {
PI * self.radius.squared()
}
}
impl Measured3d for Cone {
/// Get the total surface area of the cone
#[inline]
fn area(&self) -> f32 {
self.base_area() + self.lateral_area()
}
/// Get the volume of the cone
#[inline]
fn volume(&self) -> f32 {
(self.base_area() * self.height) / 3.0
}
}
/// A conical frustum primitive.
/// A conical frustum can be created
/// by slicing off a section of a cone.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct ConicalFrustum {
/// The radius of the top of the frustum
pub radius_top: f32,
/// The radius of the base of the frustum
pub radius_bottom: f32,
/// The height of the frustum
pub height: f32,
}
impl Primitive3d for ConicalFrustum {}
impl Default for ConicalFrustum {
/// Returns the default [`ConicalFrustum`] with a top radius of `0.25`, bottom radius of `0.5`, and a height of `0.5`.
fn default() -> Self {
Self {
radius_top: 0.25,
radius_bottom: 0.5,
height: 0.5,
}
}
}
impl ConicalFrustum {
/// Get the bottom base of the conical frustum as a [`Circle`]
#[inline]
pub const fn bottom_base(&self) -> Circle {
Circle {
radius: self.radius_bottom,
}
}
/// Get the top base of the conical frustum as a [`Circle`]
#[inline]
pub const fn top_base(&self) -> Circle {
Circle {
radius: self.radius_top,
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/curve/easing.rs | crates/bevy_math/src/curve/easing.rs | //! Module containing different easing functions.
//!
//! An easing function is a [`Curve`] that's used to transition between two
//! values. It takes a time parameter, where a time of zero means the start of
//! the transition and a time of one means the end.
//!
//! Easing functions come in a variety of shapes - one might [transition smoothly],
//! while another might have a [bouncing motion].
//!
//! There are several ways to use easing functions. The simplest option is a
//! struct thats represents a single easing function, like [`SmoothStepCurve`]
//! and [`StepsCurve`]. These structs can only transition from a value of zero
//! to a value of one.
//!
//! ```
//! # use bevy_math::prelude::*;
//! # let time = 0.0;
//! let smoothed_value = SmoothStepCurve.sample(time);
//! ```
//!
//! ```
//! # use bevy_math::prelude::*;
//! # let time = 0.0;
//! let stepped_value = StepsCurve(5, JumpAt::Start).sample(time);
//! ```
//!
//! Another option is [`EaseFunction`]. Unlike the single function structs,
//! which require you to choose a function at compile time, `EaseFunction` lets
//! you choose at runtime. It can also be serialized.
//!
//! ```
//! # use bevy_math::prelude::*;
//! # let time = 0.0;
//! # let make_it_smooth = false;
//! let mut curve = EaseFunction::Linear;
//!
//! if make_it_smooth {
//! curve = EaseFunction::SmoothStep;
//! }
//!
//! let value = curve.sample(time);
//! ```
//!
//! The final option is [`EasingCurve`]. This lets you transition between any
//! two values - not just zero to one. `EasingCurve` can use any value that
//! implements the [`Ease`] trait, including vectors and directions.
//!
//! ```
//! # use bevy_math::prelude::*;
//! # let time = 0.0;
//! // Make a curve that smoothly transitions between two positions.
//! let start_position = vec2(1.0, 2.0);
//! let end_position = vec2(5.0, 10.0);
//! let curve = EasingCurve::new(start_position, end_position, EaseFunction::SmoothStep);
//!
//! let smoothed_position = curve.sample(time);
//! ```
//!
//! Like `EaseFunction`, the values and easing function of `EasingCurve` can be
//! chosen at runtime and serialized.
//!
//! [transition smoothly]: `SmoothStepCurve`
//! [bouncing motion]: `BounceInCurve`
//! [`sample`]: `Curve::sample`
//! [`sample_clamped`]: `Curve::sample_clamped`
//! [`sample_unchecked`]: `Curve::sample_unchecked`
//!
use crate::{
curve::{Curve, CurveExt, FunctionCurve, Interval},
Dir2, Dir3, Dir3A, Isometry2d, Isometry3d, Quat, Rot2, VectorSpace,
};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::std_traits::ReflectDefault;
use variadics_please::all_tuples_enumerated;
// TODO: Think about merging `Ease` with `StableInterpolate`
/// A type whose values can be eased between.
///
/// This requires the construction of an interpolation curve that actually extends
/// beyond the curve segment that connects two values, because an easing curve may
/// extrapolate before the starting value and after the ending value. This is
/// especially common in easing functions that mimic elastic or springlike behavior.
pub trait Ease: Sized {
/// Given `start` and `end` values, produce a curve with [unlimited domain]
/// that:
/// - takes a value equivalent to `start` at `t = 0`
/// - takes a value equivalent to `end` at `t = 1`
/// - has constant speed everywhere, including outside of `[0, 1]`
///
/// [unlimited domain]: Interval::EVERYWHERE
fn interpolating_curve_unbounded(start: Self, end: Self) -> impl Curve<Self>;
}
impl<V: VectorSpace<Scalar = f32>> Ease for V {
fn interpolating_curve_unbounded(start: Self, end: Self) -> impl Curve<Self> {
FunctionCurve::new(Interval::EVERYWHERE, move |t| V::lerp(start, end, t))
}
}
impl Ease for Rot2 {
fn interpolating_curve_unbounded(start: Self, end: Self) -> impl Curve<Self> {
FunctionCurve::new(Interval::EVERYWHERE, move |t| Rot2::slerp(start, end, t))
}
}
impl Ease for Quat {
fn interpolating_curve_unbounded(start: Self, end: Self) -> impl Curve<Self> {
let dot = start.dot(end);
let end_adjusted = if dot < 0.0 { -end } else { end };
let difference = end_adjusted * start.inverse();
let (axis, angle) = difference.to_axis_angle();
FunctionCurve::new(Interval::EVERYWHERE, move |s| {
Quat::from_axis_angle(axis, angle * s) * start
})
}
}
impl Ease for Dir2 {
fn interpolating_curve_unbounded(start: Self, end: Self) -> impl Curve<Self> {
FunctionCurve::new(Interval::EVERYWHERE, move |t| Dir2::slerp(start, end, t))
}
}
impl Ease for Dir3 {
fn interpolating_curve_unbounded(start: Self, end: Self) -> impl Curve<Self> {
let difference_quat = Quat::from_rotation_arc(start.as_vec3(), end.as_vec3());
Quat::interpolating_curve_unbounded(Quat::IDENTITY, difference_quat).map(move |q| q * start)
}
}
impl Ease for Dir3A {
fn interpolating_curve_unbounded(start: Self, end: Self) -> impl Curve<Self> {
let difference_quat =
Quat::from_rotation_arc(start.as_vec3a().into(), end.as_vec3a().into());
Quat::interpolating_curve_unbounded(Quat::IDENTITY, difference_quat).map(move |q| q * start)
}
}
impl Ease for Isometry3d {
fn interpolating_curve_unbounded(start: Self, end: Self) -> impl Curve<Self> {
FunctionCurve::new(Interval::EVERYWHERE, move |t| {
// we can use sample_unchecked here, since both interpolating_curve_unbounded impls
// used are defined on the whole domain
Isometry3d {
rotation: Quat::interpolating_curve_unbounded(start.rotation, end.rotation)
.sample_unchecked(t),
translation: crate::Vec3A::interpolating_curve_unbounded(
start.translation,
end.translation,
)
.sample_unchecked(t),
}
})
}
}
impl Ease for Isometry2d {
fn interpolating_curve_unbounded(start: Self, end: Self) -> impl Curve<Self> {
FunctionCurve::new(Interval::EVERYWHERE, move |t| {
// we can use sample_unchecked here, since both interpolating_curve_unbounded impls
// used are defined on the whole domain
Isometry2d {
rotation: Rot2::interpolating_curve_unbounded(start.rotation, end.rotation)
.sample_unchecked(t),
translation: crate::Vec2::interpolating_curve_unbounded(
start.translation,
end.translation,
)
.sample_unchecked(t),
}
})
}
}
macro_rules! impl_ease_tuple {
($(#[$meta:meta])* $(($n:tt, $T:ident)),*) => {
$(#[$meta])*
impl<$($T: Ease),*> Ease for ($($T,)*) {
fn interpolating_curve_unbounded(start: Self, end: Self) -> impl Curve<Self> {
let curve_tuple =
(
$(
<$T as Ease>::interpolating_curve_unbounded(start.$n, end.$n),
)*
);
FunctionCurve::new(Interval::EVERYWHERE, move |t|
(
$(
curve_tuple.$n.sample_unchecked(t),
)*
)
)
}
}
};
}
all_tuples_enumerated!(
#[doc(fake_variadic)]
impl_ease_tuple,
1,
11,
T
);
/// A [`Curve`] that is defined by
///
/// - an initial `start` sample value at `t = 0`
/// - a final `end` sample value at `t = 1`
/// - an [easing function] to interpolate between the two values.
///
/// The resulting curve's domain is always [the unit interval].
///
/// # Example
///
/// Create a linear curve that interpolates between `2.0` and `4.0`.
///
/// ```
/// # use bevy_math::prelude::*;
/// let c = EasingCurve::new(2.0, 4.0, EaseFunction::Linear);
/// ```
///
/// [`sample`] the curve at various points. This will return `None` if the parameter
/// is outside the unit interval.
///
/// ```
/// # use bevy_math::prelude::*;
/// # let c = EasingCurve::new(2.0, 4.0, EaseFunction::Linear);
/// assert_eq!(c.sample(-1.0), None);
/// assert_eq!(c.sample(0.0), Some(2.0));
/// assert_eq!(c.sample(0.5), Some(3.0));
/// assert_eq!(c.sample(1.0), Some(4.0));
/// assert_eq!(c.sample(2.0), None);
/// ```
///
/// [`sample_clamped`] will clamp the parameter to the unit interval, so it
/// always returns a value.
///
/// ```
/// # use bevy_math::prelude::*;
/// # let c = EasingCurve::new(2.0, 4.0, EaseFunction::Linear);
/// assert_eq!(c.sample_clamped(-1.0), 2.0);
/// assert_eq!(c.sample_clamped(0.0), 2.0);
/// assert_eq!(c.sample_clamped(0.5), 3.0);
/// assert_eq!(c.sample_clamped(1.0), 4.0);
/// assert_eq!(c.sample_clamped(2.0), 4.0);
/// ```
///
/// `EasingCurve` can be used with any type that implements the [`Ease`] trait.
/// This includes many math types, like vectors and rotations.
///
/// ```
/// # use bevy_math::prelude::*;
/// let c = EasingCurve::new(
/// Vec2::new(0.0, 4.0),
/// Vec2::new(2.0, 8.0),
/// EaseFunction::Linear,
/// );
///
/// assert_eq!(c.sample_clamped(0.5), Vec2::new(1.0, 6.0));
/// ```
///
/// ```
/// # use bevy_math::prelude::*;
/// # use approx::assert_abs_diff_eq;
/// let c = EasingCurve::new(
/// Rot2::degrees(10.0),
/// Rot2::degrees(20.0),
/// EaseFunction::Linear,
/// );
///
/// assert_abs_diff_eq!(c.sample_clamped(0.5), Rot2::degrees(15.0));
/// ```
///
/// As a shortcut, an `EasingCurve` between `0.0` and `1.0` can be replaced by
/// [`EaseFunction`].
///
/// ```
/// # use bevy_math::prelude::*;
/// # let t = 0.5;
/// let f = EaseFunction::SineIn;
/// let c = EasingCurve::new(0.0, 1.0, EaseFunction::SineIn);
///
/// assert_eq!(f.sample(t), c.sample(t));
/// ```
///
/// [easing function]: EaseFunction
/// [the unit interval]: Interval::UNIT
/// [`sample`]: EasingCurve::sample
/// [`sample_clamped`]: EasingCurve::sample_clamped
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
pub struct EasingCurve<T> {
start: T,
end: T,
ease_fn: EaseFunction,
}
impl<T> EasingCurve<T> {
/// Given a `start` and `end` value, create a curve parametrized over [the unit interval]
/// that connects them, using the given [ease function] to determine the form of the
/// curve in between.
///
/// [the unit interval]: Interval::UNIT
/// [ease function]: EaseFunction
pub fn new(start: T, end: T, ease_fn: EaseFunction) -> Self {
Self {
start,
end,
ease_fn,
}
}
}
impl<T> Curve<T> for EasingCurve<T>
where
T: Ease + Clone,
{
#[inline]
fn domain(&self) -> Interval {
Interval::UNIT
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
let remapped_t = self.ease_fn.eval(t);
T::interpolating_curve_unbounded(self.start.clone(), self.end.clone())
.sample_unchecked(remapped_t)
}
}
/// Configuration options for the [`EaseFunction::Steps`] curves. This closely replicates the
/// [CSS step function specification].
///
/// [CSS step function specification]: https://developer.mozilla.org/en-US/docs/Web/CSS/easing-function/steps#description
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(bevy_reflect::Reflect),
reflect(Clone, Default, PartialEq)
)]
pub enum JumpAt {
/// Indicates that the first step happens when the animation begins.
///
#[doc = include_str!("../../images/easefunction/StartSteps.svg")]
Start,
/// Indicates that the last step happens when the animation ends.
///
#[doc = include_str!("../../images/easefunction/EndSteps.svg")]
#[default]
End,
/// Indicates neither early nor late jumps happen.
///
#[doc = include_str!("../../images/easefunction/NoneSteps.svg")]
None,
/// Indicates both early and late jumps happen.
///
#[doc = include_str!("../../images/easefunction/BothSteps.svg")]
Both,
}
impl JumpAt {
#[inline]
pub(crate) fn eval(self, num_steps: usize, t: f32) -> f32 {
use crate::ops;
let (a, b) = match self {
JumpAt::Start => (1.0, 0),
JumpAt::End => (0.0, 0),
JumpAt::None => (0.0, -1),
JumpAt::Both => (1.0, 1),
};
let current_step = ops::floor(t * num_steps as f32) + a;
let step_size = (num_steps as isize + b).max(1) as f32;
(current_step / step_size).clamp(0.0, 1.0)
}
}
/// Curve functions over the [unit interval], commonly used for easing transitions.
///
/// `EaseFunction` can be used on its own to interpolate between `0.0` and `1.0`.
/// It can also be combined with [`EasingCurve`] to interpolate between other
/// intervals and types, including vectors and rotations.
///
/// # Example
///
/// [`sample`] the smoothstep function at various points. This will return `None`
/// if the parameter is outside the unit interval.
///
/// ```
/// # use bevy_math::prelude::*;
/// let f = EaseFunction::SmoothStep;
///
/// assert_eq!(f.sample(-1.0), None);
/// assert_eq!(f.sample(0.0), Some(0.0));
/// assert_eq!(f.sample(0.5), Some(0.5));
/// assert_eq!(f.sample(1.0), Some(1.0));
/// assert_eq!(f.sample(2.0), None);
/// ```
///
/// [`sample_clamped`] will clamp the parameter to the unit interval, so it
/// always returns a value.
///
/// ```
/// # use bevy_math::prelude::*;
/// # let f = EaseFunction::SmoothStep;
/// assert_eq!(f.sample_clamped(-1.0), 0.0);
/// assert_eq!(f.sample_clamped(0.0), 0.0);
/// assert_eq!(f.sample_clamped(0.5), 0.5);
/// assert_eq!(f.sample_clamped(1.0), 1.0);
/// assert_eq!(f.sample_clamped(2.0), 1.0);
/// ```
///
/// [`sample`]: EaseFunction::sample
/// [`sample_clamped`]: EaseFunction::sample_clamped
/// [unit interval]: `Interval::UNIT`
#[non_exhaustive]
#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(bevy_reflect::Reflect),
reflect(Clone, PartialEq)
)]
// Note: Graphs are auto-generated via `tools/build-easefunction-graphs`.
pub enum EaseFunction {
/// `f(t) = t`
///
#[doc = include_str!("../../images/easefunction/Linear.svg")]
Linear,
/// `f(t) = t²`
///
/// This is the Hermite interpolator for
/// - f(0) = 0
/// - f(1) = 1
/// - f′(0) = 0
///
#[doc = include_str!("../../images/easefunction/QuadraticIn.svg")]
QuadraticIn,
/// `f(t) = -(t * (t - 2.0))`
///
/// This is the Hermite interpolator for
/// - f(0) = 0
/// - f(1) = 1
/// - f′(1) = 0
///
#[doc = include_str!("../../images/easefunction/QuadraticOut.svg")]
QuadraticOut,
/// Behaves as `EaseFunction::QuadraticIn` for t < 0.5 and as `EaseFunction::QuadraticOut` for t >= 0.5
///
/// A quadratic has too low of a degree to be both an `InOut` and C²,
/// so consider using at least a cubic (such as [`EaseFunction::SmoothStep`])
/// if you want the acceleration to be continuous.
///
#[doc = include_str!("../../images/easefunction/QuadraticInOut.svg")]
QuadraticInOut,
/// `f(t) = t³`
///
/// This is the Hermite interpolator for
/// - f(0) = 0
/// - f(1) = 1
/// - f′(0) = 0
/// - f″(0) = 0
///
#[doc = include_str!("../../images/easefunction/CubicIn.svg")]
CubicIn,
/// `f(t) = (t - 1.0)³ + 1.0`
///
#[doc = include_str!("../../images/easefunction/CubicOut.svg")]
CubicOut,
/// Behaves as `EaseFunction::CubicIn` for t < 0.5 and as `EaseFunction::CubicOut` for t >= 0.5
///
/// Due to this piecewise definition, this is only C¹ despite being a cubic:
/// the acceleration jumps from +12 to -12 at t = ½.
///
/// Consider using [`EaseFunction::SmoothStep`] instead, which is also cubic,
/// or [`EaseFunction::SmootherStep`] if you picked this because you wanted
/// the acceleration at the endpoints to also be zero.
///
#[doc = include_str!("../../images/easefunction/CubicInOut.svg")]
CubicInOut,
/// `f(t) = t⁴`
///
#[doc = include_str!("../../images/easefunction/QuarticIn.svg")]
QuarticIn,
/// `f(t) = (t - 1.0)³ * (1.0 - t) + 1.0`
///
#[doc = include_str!("../../images/easefunction/QuarticOut.svg")]
QuarticOut,
/// Behaves as `EaseFunction::QuarticIn` for t < 0.5 and as `EaseFunction::QuarticOut` for t >= 0.5
///
#[doc = include_str!("../../images/easefunction/QuarticInOut.svg")]
QuarticInOut,
/// `f(t) = t⁵`
///
#[doc = include_str!("../../images/easefunction/QuinticIn.svg")]
QuinticIn,
/// `f(t) = (t - 1.0)⁵ + 1.0`
///
#[doc = include_str!("../../images/easefunction/QuinticOut.svg")]
QuinticOut,
/// Behaves as `EaseFunction::QuinticIn` for t < 0.5 and as `EaseFunction::QuinticOut` for t >= 0.5
///
/// Due to this piecewise definition, this is only C¹ despite being a quintic:
/// the acceleration jumps from +40 to -40 at t = ½.
///
/// Consider using [`EaseFunction::SmootherStep`] instead, which is also quintic.
///
#[doc = include_str!("../../images/easefunction/QuinticInOut.svg")]
QuinticInOut,
/// Behaves as the first half of [`EaseFunction::SmoothStep`].
///
/// This has f″(1) = 0, unlike [`EaseFunction::QuadraticIn`] which starts similarly.
///
#[doc = include_str!("../../images/easefunction/SmoothStepIn.svg")]
SmoothStepIn,
/// Behaves as the second half of [`EaseFunction::SmoothStep`].
///
/// This has f″(0) = 0, unlike [`EaseFunction::QuadraticOut`] which ends similarly.
///
#[doc = include_str!("../../images/easefunction/SmoothStepOut.svg")]
SmoothStepOut,
/// `f(t) = 3t² - 2t³`
///
/// This is the Hermite interpolator for
/// - f(0) = 0
/// - f(1) = 1
/// - f′(0) = 0
/// - f′(1) = 0
///
/// See also [`smoothstep` in GLSL][glss].
///
/// [glss]: https://registry.khronos.org/OpenGL-Refpages/gl4/html/smoothstep.xhtml
///
#[doc = include_str!("../../images/easefunction/SmoothStep.svg")]
SmoothStep,
/// Behaves as the first half of [`EaseFunction::SmootherStep`].
///
/// This has f″(1) = 0, unlike [`EaseFunction::CubicIn`] which starts similarly.
///
#[doc = include_str!("../../images/easefunction/SmootherStepIn.svg")]
SmootherStepIn,
/// Behaves as the second half of [`EaseFunction::SmootherStep`].
///
/// This has f″(0) = 0, unlike [`EaseFunction::CubicOut`] which ends similarly.
///
#[doc = include_str!("../../images/easefunction/SmootherStepOut.svg")]
SmootherStepOut,
/// `f(t) = 6t⁵ - 15t⁴ + 10t³`
///
/// This is the Hermite interpolator for
/// - f(0) = 0
/// - f(1) = 1
/// - f′(0) = 0
/// - f′(1) = 0
/// - f″(0) = 0
/// - f″(1) = 0
///
#[doc = include_str!("../../images/easefunction/SmootherStep.svg")]
SmootherStep,
/// `f(t) = 1.0 - cos(t * π / 2.0)`
///
#[doc = include_str!("../../images/easefunction/SineIn.svg")]
SineIn,
/// `f(t) = sin(t * π / 2.0)`
///
#[doc = include_str!("../../images/easefunction/SineOut.svg")]
SineOut,
/// Behaves as `EaseFunction::SineIn` for t < 0.5 and as `EaseFunction::SineOut` for t >= 0.5
///
#[doc = include_str!("../../images/easefunction/SineInOut.svg")]
SineInOut,
/// `f(t) = 1.0 - sqrt(1.0 - t²)`
///
#[doc = include_str!("../../images/easefunction/CircularIn.svg")]
CircularIn,
/// `f(t) = sqrt((2.0 - t) * t)`
///
#[doc = include_str!("../../images/easefunction/CircularOut.svg")]
CircularOut,
/// Behaves as `EaseFunction::CircularIn` for t < 0.5 and as `EaseFunction::CircularOut` for t >= 0.5
///
#[doc = include_str!("../../images/easefunction/CircularInOut.svg")]
CircularInOut,
/// `f(t) ≈ 2.0^(10.0 * (t - 1.0))`
///
/// The precise definition adjusts it slightly so it hits both `(0, 0)` and `(1, 1)`:
/// `f(t) = 2.0^(10.0 * t - A) - B`, where A = log₂(2¹⁰-1) and B = 1/(2¹⁰-1).
///
#[doc = include_str!("../../images/easefunction/ExponentialIn.svg")]
ExponentialIn,
/// `f(t) ≈ 1.0 - 2.0^(-10.0 * t)`
///
/// As with `EaseFunction::ExponentialIn`, the precise definition adjusts it slightly
// so it hits both `(0, 0)` and `(1, 1)`.
///
#[doc = include_str!("../../images/easefunction/ExponentialOut.svg")]
ExponentialOut,
/// Behaves as `EaseFunction::ExponentialIn` for t < 0.5 and as `EaseFunction::ExponentialOut` for t >= 0.5
///
#[doc = include_str!("../../images/easefunction/ExponentialInOut.svg")]
ExponentialInOut,
/// `f(t) = -2.0^(10.0 * t - 10.0) * sin((t * 10.0 - 10.75) * 2.0 * π / 3.0)`
///
#[doc = include_str!("../../images/easefunction/ElasticIn.svg")]
ElasticIn,
/// `f(t) = 2.0^(-10.0 * t) * sin((t * 10.0 - 0.75) * 2.0 * π / 3.0) + 1.0`
///
#[doc = include_str!("../../images/easefunction/ElasticOut.svg")]
ElasticOut,
/// Behaves as `EaseFunction::ElasticIn` for t < 0.5 and as `EaseFunction::ElasticOut` for t >= 0.5
///
#[doc = include_str!("../../images/easefunction/ElasticInOut.svg")]
ElasticInOut,
/// `f(t) = 2.70158 * t³ - 1.70158 * t²`
///
#[doc = include_str!("../../images/easefunction/BackIn.svg")]
BackIn,
/// `f(t) = 1.0 + 2.70158 * (t - 1.0)³ - 1.70158 * (t - 1.0)²`
///
#[doc = include_str!("../../images/easefunction/BackOut.svg")]
BackOut,
/// Behaves as `EaseFunction::BackIn` for t < 0.5 and as `EaseFunction::BackOut` for t >= 0.5
///
#[doc = include_str!("../../images/easefunction/BackInOut.svg")]
BackInOut,
/// bouncy at the start!
///
#[doc = include_str!("../../images/easefunction/BounceIn.svg")]
BounceIn,
/// bouncy at the end!
///
#[doc = include_str!("../../images/easefunction/BounceOut.svg")]
BounceOut,
/// Behaves as `EaseFunction::BounceIn` for t < 0.5 and as `EaseFunction::BounceOut` for t >= 0.5
///
#[doc = include_str!("../../images/easefunction/BounceInOut.svg")]
BounceInOut,
/// `n` steps connecting the start and the end. Jumping behavior is customizable via
/// [`JumpAt`]. See [`JumpAt`] for all the options and visual examples.
Steps(usize, JumpAt),
/// `f(omega,t) = 1 - (1 - t)²(2sin(omega * t) / omega + cos(omega * t))`, parametrized by `omega`
///
#[doc = include_str!("../../images/easefunction/Elastic.svg")]
Elastic(f32),
}
/// `f(t) = t`
///
#[doc = include_str!("../../images/easefunction/Linear.svg")]
#[derive(Copy, Clone)]
pub struct LinearCurve;
/// `f(t) = t²`
///
/// This is the Hermite interpolator for
/// - f(0) = 0
/// - f(1) = 1
/// - f′(0) = 0
///
#[doc = include_str!("../../images/easefunction/QuadraticIn.svg")]
#[derive(Copy, Clone)]
pub struct QuadraticInCurve;
/// `f(t) = -(t * (t - 2.0))`
///
/// This is the Hermite interpolator for
/// - f(0) = 0
/// - f(1) = 1
/// - f′(1) = 0
///
#[doc = include_str!("../../images/easefunction/QuadraticOut.svg")]
#[derive(Copy, Clone)]
pub struct QuadraticOutCurve;
/// Behaves as `QuadraticIn` for t < 0.5 and as `QuadraticOut` for t >= 0.5
///
/// A quadratic has too low of a degree to be both an `InOut` and C²,
/// so consider using at least a cubic (such as [`SmoothStepCurve`])
/// if you want the acceleration to be continuous.
///
#[doc = include_str!("../../images/easefunction/QuadraticInOut.svg")]
#[derive(Copy, Clone)]
pub struct QuadraticInOutCurve;
/// `f(t) = t³`
///
/// This is the Hermite interpolator for
/// - f(0) = 0
/// - f(1) = 1
/// - f′(0) = 0
/// - f″(0) = 0
///
#[doc = include_str!("../../images/easefunction/CubicIn.svg")]
#[derive(Copy, Clone)]
pub struct CubicInCurve;
/// `f(t) = (t - 1.0)³ + 1.0`
///
#[doc = include_str!("../../images/easefunction/CubicOut.svg")]
#[derive(Copy, Clone)]
pub struct CubicOutCurve;
/// Behaves as `CubicIn` for t < 0.5 and as `CubicOut` for t >= 0.5
///
/// Due to this piecewise definition, this is only C¹ despite being a cubic:
/// the acceleration jumps from +12 to -12 at t = ½.
///
/// Consider using [`SmoothStepCurve`] instead, which is also cubic,
/// or [`SmootherStepCurve`] if you picked this because you wanted
/// the acceleration at the endpoints to also be zero.
///
#[doc = include_str!("../../images/easefunction/CubicInOut.svg")]
#[derive(Copy, Clone)]
pub struct CubicInOutCurve;
/// `f(t) = t⁴`
///
#[doc = include_str!("../../images/easefunction/QuarticIn.svg")]
#[derive(Copy, Clone)]
pub struct QuarticInCurve;
/// `f(t) = (t - 1.0)³ * (1.0 - t) + 1.0`
///
#[doc = include_str!("../../images/easefunction/QuarticOut.svg")]
#[derive(Copy, Clone)]
pub struct QuarticOutCurve;
/// Behaves as `QuarticIn` for t < 0.5 and as `QuarticOut` for t >= 0.5
///
#[doc = include_str!("../../images/easefunction/QuarticInOut.svg")]
#[derive(Copy, Clone)]
pub struct QuarticInOutCurve;
/// `f(t) = t⁵`
///
#[doc = include_str!("../../images/easefunction/QuinticIn.svg")]
#[derive(Copy, Clone)]
pub struct QuinticInCurve;
/// `f(t) = (t - 1.0)⁵ + 1.0`
///
#[doc = include_str!("../../images/easefunction/QuinticOut.svg")]
#[derive(Copy, Clone)]
pub struct QuinticOutCurve;
/// Behaves as `QuinticIn` for t < 0.5 and as `QuinticOut` for t >= 0.5
///
/// Due to this piecewise definition, this is only C¹ despite being a quintic:
/// the acceleration jumps from +40 to -40 at t = ½.
///
/// Consider using [`SmootherStepCurve`] instead, which is also quintic.
///
#[doc = include_str!("../../images/easefunction/QuinticInOut.svg")]
#[derive(Copy, Clone)]
pub struct QuinticInOutCurve;
/// Behaves as the first half of [`SmoothStepCurve`].
///
/// This has f″(1) = 0, unlike [`QuadraticInCurve`] which starts similarly.
///
#[doc = include_str!("../../images/easefunction/SmoothStepIn.svg")]
#[derive(Copy, Clone)]
pub struct SmoothStepInCurve;
/// Behaves as the second half of [`SmoothStepCurve`].
///
/// This has f″(0) = 0, unlike [`QuadraticOutCurve`] which ends similarly.
///
#[doc = include_str!("../../images/easefunction/SmoothStepOut.svg")]
#[derive(Copy, Clone)]
pub struct SmoothStepOutCurve;
/// `f(t) = 3t² - 2t³`
///
/// This is the Hermite interpolator for
/// - f(0) = 0
/// - f(1) = 1
/// - f′(0) = 0
/// - f′(1) = 0
///
/// See also [`smoothstep` in GLSL][glss].
///
/// [glss]: https://registry.khronos.org/OpenGL-Refpages/gl4/html/smoothstep.xhtml
///
#[doc = include_str!("../../images/easefunction/SmoothStep.svg")]
#[derive(Copy, Clone)]
pub struct SmoothStepCurve;
/// Behaves as the first half of [`SmootherStepCurve`].
///
/// This has f″(1) = 0, unlike [`CubicInCurve`] which starts similarly.
///
#[doc = include_str!("../../images/easefunction/SmootherStepIn.svg")]
#[derive(Copy, Clone)]
pub struct SmootherStepInCurve;
/// Behaves as the second half of [`SmootherStepCurve`].
///
/// This has f″(0) = 0, unlike [`CubicOutCurve`] which ends similarly.
///
#[doc = include_str!("../../images/easefunction/SmootherStepOut.svg")]
#[derive(Copy, Clone)]
pub struct SmootherStepOutCurve;
/// `f(t) = 6t⁵ - 15t⁴ + 10t³`
///
/// This is the Hermite interpolator for
/// - f(0) = 0
/// - f(1) = 1
/// - f′(0) = 0
/// - f′(1) = 0
/// - f″(0) = 0
/// - f″(1) = 0
///
#[doc = include_str!("../../images/easefunction/SmootherStep.svg")]
#[derive(Copy, Clone)]
pub struct SmootherStepCurve;
/// `f(t) = 1.0 - cos(t * π / 2.0)`
///
#[doc = include_str!("../../images/easefunction/SineIn.svg")]
#[derive(Copy, Clone)]
pub struct SineInCurve;
/// `f(t) = sin(t * π / 2.0)`
///
#[doc = include_str!("../../images/easefunction/SineOut.svg")]
#[derive(Copy, Clone)]
pub struct SineOutCurve;
/// Behaves as `SineIn` for t < 0.5 and as `SineOut` for t >= 0.5
///
#[doc = include_str!("../../images/easefunction/SineInOut.svg")]
#[derive(Copy, Clone)]
pub struct SineInOutCurve;
/// `f(t) = 1.0 - sqrt(1.0 - t²)`
///
#[doc = include_str!("../../images/easefunction/CircularIn.svg")]
#[derive(Copy, Clone)]
pub struct CircularInCurve;
/// `f(t) = sqrt((2.0 - t) * t)`
///
#[doc = include_str!("../../images/easefunction/CircularOut.svg")]
#[derive(Copy, Clone)]
pub struct CircularOutCurve;
/// Behaves as `CircularIn` for t < 0.5 and as `CircularOut` for t >= 0.5
///
#[doc = include_str!("../../images/easefunction/CircularInOut.svg")]
#[derive(Copy, Clone)]
pub struct CircularInOutCurve;
/// `f(t) ≈ 2.0^(10.0 * (t - 1.0))`
///
/// The precise definition adjusts it slightly so it hits both `(0, 0)` and `(1, 1)`:
/// `f(t) = 2.0^(10.0 * t - A) - B`, where A = log₂(2¹⁰-1) and B = 1/(2¹⁰-1).
///
#[doc = include_str!("../../images/easefunction/ExponentialIn.svg")]
#[derive(Copy, Clone)]
pub struct ExponentialInCurve;
/// `f(t) ≈ 1.0 - 2.0^(-10.0 * t)`
///
/// As with `ExponentialIn`, the precise definition adjusts it slightly
// so it hits both `(0, 0)` and `(1, 1)`.
///
#[doc = include_str!("../../images/easefunction/ExponentialOut.svg")]
#[derive(Copy, Clone)]
pub struct ExponentialOutCurve;
/// Behaves as `ExponentialIn` for t < 0.5 and as `ExponentialOut` for t >= 0.5
///
#[doc = include_str!("../../images/easefunction/ExponentialInOut.svg")]
#[derive(Copy, Clone)]
pub struct ExponentialInOutCurve;
/// `f(t) = -2.0^(10.0 * t - 10.0) * sin((t * 10.0 - 10.75) * 2.0 * π / 3.0)`
///
#[doc = include_str!("../../images/easefunction/ElasticIn.svg")]
#[derive(Copy, Clone)]
pub struct ElasticInCurve;
/// `f(t) = 2.0^(-10.0 * t) * sin((t * 10.0 - 0.75) * 2.0 * π / 3.0) + 1.0`
///
#[doc = include_str!("../../images/easefunction/ElasticOut.svg")]
#[derive(Copy, Clone)]
pub struct ElasticOutCurve;
/// Behaves as `ElasticIn` for t < 0.5 and as `ElasticOut` for t >= 0.5
///
#[doc = include_str!("../../images/easefunction/ElasticInOut.svg")]
#[derive(Copy, Clone)]
pub struct ElasticInOutCurve;
/// `f(t) = 2.70158 * t³ - 1.70158 * t²`
///
#[doc = include_str!("../../images/easefunction/BackIn.svg")]
#[derive(Copy, Clone)]
pub struct BackInCurve;
/// `f(t) = 1.0 + 2.70158 * (t - 1.0)³ - 1.70158 * (t - 1.0)²`
///
#[doc = include_str!("../../images/easefunction/BackOut.svg")]
#[derive(Copy, Clone)]
pub struct BackOutCurve;
/// Behaves as `BackIn` for t < 0.5 and as `BackOut` for t >= 0.5
///
#[doc = include_str!("../../images/easefunction/BackInOut.svg")]
#[derive(Copy, Clone)]
pub struct BackInOutCurve;
/// bouncy at the start!
///
#[doc = include_str!("../../images/easefunction/BounceIn.svg")]
#[derive(Copy, Clone)]
pub struct BounceInCurve;
/// bouncy at the end!
///
#[doc = include_str!("../../images/easefunction/BounceOut.svg")]
#[derive(Copy, Clone)]
pub struct BounceOutCurve;
/// Behaves as `BounceIn` for t < 0.5 and as `BounceOut` for t >= 0.5
///
#[doc = include_str!("../../images/easefunction/BounceInOut.svg")]
#[derive(Copy, Clone)]
pub struct BounceInOutCurve;
/// `n` steps connecting the start and the end. Jumping behavior is customizable via
/// [`JumpAt`]. See [`JumpAt`] for all the options and visual examples.
#[derive(Copy, Clone)]
pub struct StepsCurve(pub usize, pub JumpAt);
/// `f(omega,t) = 1 - (1 - t)²(2sin(omega * t) / omega + cos(omega * t))`, parametrized by `omega`
///
#[doc = include_str!("../../images/easefunction/Elastic.svg")]
#[derive(Copy, Clone)]
pub struct ElasticCurve(pub f32);
/// Implements `Curve<f32>` for a unit struct using a function in `easing_functions`.
macro_rules! impl_ease_unit_struct {
($ty: ty, $fn: ident) => {
impl Curve<f32> for $ty {
#[inline]
fn domain(&self) -> Interval {
Interval::UNIT
}
#[inline]
fn sample_unchecked(&self, t: f32) -> f32 {
easing_functions::$fn(t)
}
}
};
}
impl_ease_unit_struct!(LinearCurve, linear);
impl_ease_unit_struct!(QuadraticInCurve, quadratic_in);
impl_ease_unit_struct!(QuadraticOutCurve, quadratic_out);
impl_ease_unit_struct!(QuadraticInOutCurve, quadratic_in_out);
impl_ease_unit_struct!(CubicInCurve, cubic_in);
impl_ease_unit_struct!(CubicOutCurve, cubic_out);
impl_ease_unit_struct!(CubicInOutCurve, cubic_in_out);
impl_ease_unit_struct!(QuarticInCurve, quartic_in);
impl_ease_unit_struct!(QuarticOutCurve, quartic_out);
impl_ease_unit_struct!(QuarticInOutCurve, quartic_in_out);
impl_ease_unit_struct!(QuinticInCurve, quintic_in);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/curve/iterable.rs | crates/bevy_math/src/curve/iterable.rs | //! Iterable curves, which sample in the form of an iterator in order to support `Vec`-like
//! output whose length cannot be known statically.
use super::Interval;
#[cfg(feature = "alloc")]
use {super::ConstantCurve, alloc::vec::Vec};
/// A curve which provides samples in the form of [`Iterator`]s.
///
/// This is an abstraction that provides an interface for curves which look like `Curve<Vec<T>>`
/// but side-stepping issues with allocation on sampling. This happens when the size of an output
/// array cannot be known statically.
pub trait IterableCurve<T> {
/// The interval over which this curve is parametrized.
fn domain(&self) -> Interval;
/// Sample a point on this curve at the parameter value `t`, producing an iterator over values.
/// This is the unchecked version of sampling, which should only be used if the sample time `t`
/// is already known to lie within the curve's domain.
///
/// Values sampled from outside of a curve's domain are generally considered invalid; data which
/// is nonsensical or otherwise useless may be returned in such a circumstance, and extrapolation
/// beyond a curve's domain should not be relied upon.
fn sample_iter_unchecked(&self, t: f32) -> impl Iterator<Item = T>;
/// Sample this curve at a specified time `t`, producing an iterator over sampled values.
/// The parameter `t` is clamped to the domain of the curve.
fn sample_iter_clamped(&self, t: f32) -> impl Iterator<Item = T> {
let t_clamped = self.domain().clamp(t);
self.sample_iter_unchecked(t_clamped)
}
/// Sample this curve at a specified time `t`, producing an iterator over sampled values.
/// If the parameter `t` does not lie in the curve's domain, `None` is returned.
fn sample_iter(&self, t: f32) -> Option<impl Iterator<Item = T>> {
if self.domain().contains(t) {
Some(self.sample_iter_unchecked(t))
} else {
None
}
}
}
#[cfg(feature = "alloc")]
impl<T> IterableCurve<T> for ConstantCurve<Vec<T>>
where
T: Clone,
{
fn domain(&self) -> Interval {
self.domain
}
fn sample_iter_unchecked(&self, _t: f32) -> impl Iterator<Item = T> {
self.value.iter().cloned()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/curve/mod.rs | crates/bevy_math/src/curve/mod.rs | //! The [`Curve`] trait, providing a domain-agnostic description of curves.
//!
//! ## Overview
//!
//! At a high level, [`Curve`] is a trait that abstracts away the implementation details of curves,
//! which comprise any kind of data parametrized by a single continuous variable. For example, that
//! variable could represent time, in which case a curve would represent a value that changes over
//! time, as in animation; on the other hand, it could represent something like displacement or
//! distance, as in graphs, gradients, and curves in space.
//!
//! The trait itself has two fundamental components: a curve must have a [domain], which is a nonempty
//! range of `f32` values, and it must be able to be [sampled] on every one of those values, producing
//! output of some fixed type.
//!
//! A primary goal of the trait is to allow interfaces to simply accept `impl Curve<T>` as input
//! rather than requiring for input curves to be defined in data in any particular way. This is
//! supported by a number of interface methods which allow [changing parametrizations], [mapping output],
//! and [rasterization].
//!
//! ## Analogy with `Iterator`
//!
//! The `Curve` API behaves, in many ways, like a continuous counterpart to [`Iterator`]. The analogy
//! looks something like this with some of the common methods:
//!
//! | Iterators | Curves |
//! | :--------------- | :-------------- |
//! | `map` | `map` |
//! | `skip`/`step_by` | `reparametrize` |
//! | `enumerate` | `graph` |
//! | `chain` | `chain` |
//! | `zip` | `zip` |
//! | `rev` | `reverse` |
//! | `by_ref` | `by_ref` |
//!
//! Of course, there are very important differences, as well. For instance, the continuous nature of
//! curves means that many iterator methods make little sense in the context of curves, or at least
//! require numerical techniques. For example, the analogue of `sum` would be an integral, approximated
//! by something like Riemann summation.
//!
//! Furthermore, the two also differ greatly in their orientation to borrowing and mutation:
//! iterators are mutated by being iterated, and by contrast, all curve methods are immutable. More
//! information on the implications of this can be found [below](self#Ownership-and-borrowing).
//!
//! ## Defining curves
//!
//! Curves may be defined in a number of ways. The following are common:
//! - using [functions];
//! - using [sample interpolation];
//! - using [splines];
//! - using [easings].
//!
//! Among these, the first is the most versatile[^footnote]: the domain and the sampling output are just
//! specified directly in the construction. For this reason, function curves are a reliable go-to for
//! simple one-off constructions and procedural uses, where flexibility is desirable. For example:
//! ```rust
//! # use bevy_math::vec3;
//! # use bevy_math::curve::*;
//! // A sinusoid:
//! let sine_curve = FunctionCurve::new(Interval::EVERYWHERE, f32::sin);
//!
//! // A sawtooth wave:
//! let sawtooth_curve = FunctionCurve::new(Interval::EVERYWHERE, |t| t % 1.0);
//!
//! // A helix:
//! let helix_curve = FunctionCurve::new(Interval::EVERYWHERE, |theta| vec3(theta.sin(), theta, theta.cos()));
//! ```
//!
//! Sample-interpolated curves commonly arises in both rasterization and in animation, and this library
//! has support for producing them in both fashions. See [below](self#Resampling-and-rasterization) for
//! more information about rasterization. Here is what an explicit sample-interpolated curve might look like:
//! ```rust
//! # use bevy_math::prelude::*;
//! # use std::f32::consts::FRAC_PI_2;
//! // A list of angles that we want to traverse:
//! let angles = [
//! 0.0,
//! -FRAC_PI_2,
//! 0.0,
//! FRAC_PI_2,
//! 0.0
//! ];
//!
//! // Make each angle into a rotation by that angle:
//! let rotations = angles.map(|angle| Rot2::radians(angle));
//!
//! // Interpolate these rotations with a `Rot2`-valued curve:
//! let rotation_curve = SampleAutoCurve::new(interval(0.0, 4.0).unwrap(), rotations).unwrap();
//! ```
//!
//! For more information on [spline curves] and [easing curves], see their respective modules.
//!
//! And, of course, you are also free to define curve types yourself, implementing the trait directly.
//! For custom sample-interpolated curves, the [`cores`] submodule provides machinery to avoid having to
//! reimplement interpolation logic yourself. In many other cases, implementing the trait directly is
//! often quite straightforward:
//! ```rust
//! # use bevy_math::prelude::*;
//! struct ExponentialCurve {
//! exponent: f32,
//! }
//!
//! impl Curve<f32> for ExponentialCurve {
//! fn domain(&self) -> Interval {
//! Interval::EVERYWHERE
//! }
//!
//! fn sample_unchecked(&self, t: f32) -> f32 {
//! f32::exp(self.exponent * t)
//! }
//!
//! // All other trait methods can be inferred from these.
//! }
//! ```
//!
//! ## Transforming curves
//!
//! The API provides a few key ways of transforming one curve into another. These are often useful when
//! you would like to make use of an interface that requires a curve that bears some logical relationship
//! to one that you already have access to, but with different requirements or expectations. For example,
//! the output type of the curves may differ, or the domain may be expected to be different. The `map`
//! and `reparametrize` methods can help address this.
//!
//! As a simple example of the kind of thing that arises in practice, let's imagine that we have a
//! `Curve<Vec2>` that we want to use to describe the motion of some object over time, but the interface
//! for animation expects a `Curve<Vec3>`, since the object will move in three dimensions:
//! ```rust
//! # use bevy_math::{vec2, prelude::*};
//! # use std::f32::consts::TAU;
//! // Our original curve, which may look something like this:
//! let ellipse_curve = FunctionCurve::new(
//! interval(0.0, TAU).unwrap(),
//! |t| vec2(t.cos(), t.sin() * 2.0)
//! );
//!
//! // Use `map` to situate this in 3D as a Curve<Vec3>; in this case, it will be in the xy-plane:
//! let ellipse_motion_curve = ellipse_curve.map(|pos| pos.extend(0.0));
//! ```
//!
//! We might imagine further still that the interface expects the curve to have domain `[0, 1]`. The
//! `reparametrize` methods can address this:
//! ```rust
//! # use bevy_math::{vec2, prelude::*};
//! # use std::f32::consts::TAU;
//! # let ellipse_curve = FunctionCurve::new(interval(0.0, TAU).unwrap(), |t| vec2(t.cos(), t.sin() * 2.0));
//! # let ellipse_motion_curve = ellipse_curve.map(|pos| pos.extend(0.0));
//! // Change the domain to `[0, 1]` instead of `[0, TAU]`:
//! let final_curve = ellipse_motion_curve.reparametrize_linear(Interval::UNIT).unwrap();
//! ```
//!
//! Of course, there are many other ways of using these methods. In general, `map` is used for transforming
//! the output and using it to drive something else, while `reparametrize` preserves the curve's shape but
//! changes the speed and direction in which it is traversed. For instance:
//! ```rust
//! # use bevy_math::{vec2, prelude::*};
//! // A line segment curve connecting two points in the plane:
//! let start = vec2(-1.0, 1.0);
//! let end = vec2(1.0, 1.0);
//! let segment = FunctionCurve::new(Interval::UNIT, |t| start.lerp(end, t));
//!
//! // Let's make a curve that goes back and forth along this line segment forever.
//! //
//! // Start by stretching the line segment in parameter space so that it travels along its length
//! // from `-1` to `1` instead of `0` to `1`:
//! let stretched_segment = segment.reparametrize_linear(interval(-1.0, 1.0).unwrap()).unwrap();
//!
//! // Now, the *output* of `f32::sin` in `[-1, 1]` corresponds to the *input* interval of
//! // `stretched_segment`; the sinusoid output is mapped to the input parameter and controls how
//! // far along the segment we are:
//! let back_and_forth_curve = stretched_segment.reparametrize(Interval::EVERYWHERE, f32::sin);
//! ```
//!
//! ## Combining curves
//!
//! Curves become more expressive when used together. For example, maybe you want to combine two
//! curves end-to-end:
//! ```rust
//! # use bevy_math::{vec2, prelude::*};
//! # use std::f32::consts::PI;
//! // A line segment connecting `(-1, 0)` to `(0, 0)`:
//! let line_curve = FunctionCurve::new(
//! Interval::UNIT,
//! |t| vec2(-1.0, 0.0).lerp(vec2(0.0, 0.0), t)
//! );
//!
//! // A half-circle curve starting at `(0, 0)`:
//! let half_circle_curve = FunctionCurve::new(
//! interval(0.0, PI).unwrap(),
//! |t| vec2(t.cos() * -1.0 + 1.0, t.sin())
//! );
//!
//! // A curve that traverses `line_curve` and then `half_circle_curve` over the interval
//! // from `0` to `PI + 1`:
//! let combined_curve = line_curve.chain(half_circle_curve).unwrap();
//! ```
//!
//! Or, instead, maybe you want to combine two curves the *other* way, producing a single curve
//! that combines their output in a tuple:
//! ```rust
//! # use bevy_math::{vec2, prelude::*};
//! // Some entity's position in 2D:
//! let position_curve = FunctionCurve::new(Interval::UNIT, |t| vec2(t.cos(), t.sin()));
//!
//! // The same entity's orientation, described as a rotation. (In this case it will be spinning.)
//! let orientation_curve = FunctionCurve::new(Interval::UNIT, |t| Rot2::radians(5.0 * t));
//!
//! // Both in one curve with `(Vec2, Rot2)` output:
//! let position_and_orientation = position_curve.zip(orientation_curve).unwrap();
//! ```
//!
//! See the documentation on [`chain`] and [`zip`] for more details on how these methods work.
//!
//! ## <a name="Resampling-and-rasterization"></a>Resampling and rasterization
//!
//! Sometimes, for reasons of portability, performance, or otherwise, it can be useful to ensure that
//! curves of various provenance all actually share the same concrete type. This is the purpose of the
//! [`resample`] family of functions: they allow a curve to be replaced by an approximate version of
//! itself defined by interpolation over samples from the original curve.
//!
//! In effect, this allows very different curves to be rasterized and treated uniformly. For example:
//! ```rust
//! # use bevy_math::{vec2, prelude::*};
//! // A curve that is not easily transported because it relies on evaluating a function:
//! let interesting_curve = FunctionCurve::new(Interval::UNIT, |t| vec2(t * 3.0, t.exp()));
//!
//! // A rasterized form of the preceding curve which is just a `SampleAutoCurve`. Inside, this
//! // just stores an `Interval` along with a buffer of sample data, so it's easy to serialize
//! // and deserialize:
//! let resampled_curve = interesting_curve.resample_auto(100).unwrap();
//!
//! // The rasterized form can be seamlessly used as a curve itself:
//! let some_value = resampled_curve.sample(0.5).unwrap();
//! ```
//!
//! ## <a name="Ownership-and-borrowing"></a>Ownership and borrowing
//!
//! It can be easy to get tripped up by how curves specifically interact with Rust's ownership semantics.
//! First of all, it's worth noting that the API never uses `&mut self` — every method either takes
//! ownership of the original curve or uses a shared reference.
//!
//! Because of the methods that take ownership, it is useful to be aware of the following:
//! - If `curve` is a curve, then `&curve` is also a curve with the same output. For convenience,
//! `&curve` can be written as `curve.by_ref()` for use in method chaining.
//! - However, `&curve` cannot outlive `curve`. In general, it is not `'static`.
//!
//! In other words, `&curve` can be used to perform temporary operations without consuming `curve` (for
//! example, to effectively pass `curve` into an API which expects an `impl Curve<T>`), but it *cannot*
//! be used in situations where persistence is necessary (e.g. when the curve itself must be stored
//! for later use).
//!
//! Here is a demonstration:
//! ```rust
//! # use bevy_math::prelude::*;
//! # let some_magic_constructor = || EasingCurve::new(0.0, 1.0, EaseFunction::ElasticInOut).graph();
//! //`my_curve` is obtained somehow. It is a `Curve<(f32, f32)>`.
//! let my_curve = some_magic_constructor();
//!
//! // Now, we want to sample a mapped version of `my_curve`.
//!
//! // let samples: Vec<f32> = my_curve.map(|(x, y)| y).samples(50).unwrap().collect();
//! // ^ This would work, but it would also invalidate `my_curve`, since `map` takes ownership.
//!
//! // Instead, we pass a borrowed version of `my_curve` to `map`. It lives long enough that we
//! // can extract samples:
//! let samples: Vec<f32> = my_curve.by_ref().map(|(x, y)| y).samples(50).unwrap().collect();
//!
//! // This way, we retain the ability to use `my_curve` later:
//! let new_curve = my_curve.map(|(x,y)| x + y);
//! ```
//!
//! [domain]: Curve::domain
//! [sampled]: Curve::sample
//! [changing parametrizations]: CurveExt::reparametrize
//! [mapping output]: CurveExt::map
//! [rasterization]: CurveResampleExt::resample
//! [functions]: FunctionCurve
//! [sample interpolation]: SampleCurve
//! [splines]: crate::cubic_splines
//! [easings]: easing
//! [spline curves]: crate::cubic_splines
//! [easing curves]: easing
//! [`chain`]: CurveExt::chain
//! [`zip`]: CurveExt::zip
//! [`resample`]: CurveResampleExt::resample
//!
//! [^footnote]: In fact, universal as well, in some sense: if `curve` is any curve, then `FunctionCurve::new
//! (curve.domain(), |t| curve.sample_unchecked(t))` is an equivalent function curve.
pub mod adaptors;
pub mod cores;
pub mod derivatives;
pub mod easing;
pub mod interval;
pub mod iterable;
#[cfg(feature = "alloc")]
pub mod sample_curves;
// bevy_math::curve re-exports all commonly-needed curve-related items.
pub use adaptors::*;
pub use easing::*;
pub use interval::{interval, Interval};
#[cfg(feature = "alloc")]
pub use {
cores::{EvenCore, UnevenCore},
sample_curves::*,
};
use crate::VectorSpace;
use core::{marker::PhantomData, ops::Deref};
use interval::InvalidIntervalError;
use thiserror::Error;
#[cfg(feature = "alloc")]
use {crate::StableInterpolate, itertools::Itertools};
/// A trait for a type that can represent values of type `T` parametrized over a fixed interval.
///
/// Typical examples of this are actual geometric curves where `T: VectorSpace`, but other kinds
/// of output data can be represented as well. See the [module-level documentation] for details.
///
/// [module-level documentation]: self
pub trait Curve<T> {
/// The interval over which this curve is parametrized.
///
/// This is the range of values of `t` where we can sample the curve and receive valid output.
fn domain(&self) -> Interval;
/// Sample a point on this curve at the parameter value `t`, extracting the associated value.
/// This is the unchecked version of sampling, which should only be used if the sample time `t`
/// is already known to lie within the curve's domain.
///
/// Values sampled from outside of a curve's domain are generally considered invalid; data which
/// is nonsensical or otherwise useless may be returned in such a circumstance, and extrapolation
/// beyond a curve's domain should not be relied upon.
fn sample_unchecked(&self, t: f32) -> T;
/// Sample a point on this curve at the parameter value `t`, returning `None` if the point is
/// outside of the curve's domain.
fn sample(&self, t: f32) -> Option<T> {
match self.domain().contains(t) {
true => Some(self.sample_unchecked(t)),
false => None,
}
}
/// Sample a point on this curve at the parameter value `t`, clamping `t` to lie inside the
/// domain of the curve.
fn sample_clamped(&self, t: f32) -> T {
let t = self.domain().clamp(t);
self.sample_unchecked(t)
}
}
impl<T, C, D> Curve<T> for D
where
C: Curve<T> + ?Sized,
D: Deref<Target = C>,
{
fn domain(&self) -> Interval {
<C as Curve<T>>::domain(self)
}
fn sample_unchecked(&self, t: f32) -> T {
<C as Curve<T>>::sample_unchecked(self, t)
}
}
/// Extension trait implemented by [curves], allowing access to a number of adaptors and
/// convenience methods.
///
/// This trait is automatically implemented for all curves that are `Sized`. In particular,
/// it is implemented for types like `Box<dyn Curve<T>>`. `CurveExt` is not dyn-compatible
/// itself.
///
/// For more information, see the [module-level documentation].
///
/// [curves]: Curve
/// [module-level documentation]: self
pub trait CurveExt<T>: Curve<T> + Sized {
/// Sample a collection of `n >= 0` points on this curve at the parameter values `t_n`,
/// returning `None` if the point is outside of the curve's domain.
///
/// The samples are returned in the same order as the parameter values `t_n` were provided and
/// will include all results. This leaves the responsibility for things like filtering and
/// sorting to the user for maximum flexibility.
fn sample_iter(&self, iter: impl IntoIterator<Item = f32>) -> impl Iterator<Item = Option<T>> {
iter.into_iter().map(|t| self.sample(t))
}
/// Sample a collection of `n >= 0` points on this curve at the parameter values `t_n`,
/// extracting the associated values. This is the unchecked version of sampling, which should
/// only be used if the sample times `t_n` are already known to lie within the curve's domain.
///
/// Values sampled from outside of a curve's domain are generally considered invalid; data
/// which is nonsensical or otherwise useless may be returned in such a circumstance, and
/// extrapolation beyond a curve's domain should not be relied upon.
///
/// The samples are returned in the same order as the parameter values `t_n` were provided and
/// will include all results. This leaves the responsibility for things like filtering and
/// sorting to the user for maximum flexibility.
fn sample_iter_unchecked(
&self,
iter: impl IntoIterator<Item = f32>,
) -> impl Iterator<Item = T> {
iter.into_iter().map(|t| self.sample_unchecked(t))
}
/// Sample a collection of `n >= 0` points on this curve at the parameter values `t_n`,
/// clamping `t_n` to lie inside the domain of the curve.
///
/// The samples are returned in the same order as the parameter values `t_n` were provided and
/// will include all results. This leaves the responsibility for things like filtering and
/// sorting to the user for maximum flexibility.
fn sample_iter_clamped(&self, iter: impl IntoIterator<Item = f32>) -> impl Iterator<Item = T> {
iter.into_iter().map(|t| self.sample_clamped(t))
}
/// Create a new curve by mapping the values of this curve via a function `f`; i.e., if the
/// sample at time `t` for this curve is `x`, the value at time `t` on the new curve will be
/// `f(x)`.
#[must_use]
fn map<S, F>(self, f: F) -> MapCurve<T, S, Self, F>
where
F: Fn(T) -> S,
{
MapCurve {
preimage: self,
f,
_phantom: PhantomData,
}
}
/// Create a new [`Curve`] whose parameter space is related to the parameter space of this curve
/// by `f`. For each time `t`, the sample from the new curve at time `t` is the sample from
/// this curve at time `f(t)`. The given `domain` will be the domain of the new curve. The
/// function `f` is expected to take `domain` into `self.domain()`.
///
/// Note that this is the opposite of what one might expect intuitively; for example, if this
/// curve has a parameter domain of `[0, 1]`, then stretching the parameter domain to
/// `[0, 2]` would be performed as follows, dividing by what might be perceived as the scaling
/// factor rather than multiplying:
/// ```
/// # use bevy_math::curve::*;
/// let my_curve = ConstantCurve::new(Interval::UNIT, 1.0);
/// let scaled_curve = my_curve.reparametrize(interval(0.0, 2.0).unwrap(), |t| t / 2.0);
/// ```
/// This kind of linear remapping is provided by the convenience method
/// [`CurveExt::reparametrize_linear`], which requires only the desired domain for the new curve.
///
/// # Examples
/// ```
/// // Reverse a curve:
/// # use bevy_math::curve::*;
/// # use bevy_math::vec2;
/// let my_curve = ConstantCurve::new(Interval::UNIT, 1.0);
/// let domain = my_curve.domain();
/// let reversed_curve = my_curve.reparametrize(domain, |t| domain.end() - (t - domain.start()));
///
/// // Take a segment of a curve:
/// # let my_curve = ConstantCurve::new(Interval::UNIT, 1.0);
/// let curve_segment = my_curve.reparametrize(interval(0.0, 0.5).unwrap(), |t| 0.5 + t);
/// ```
#[must_use]
fn reparametrize<F>(self, domain: Interval, f: F) -> ReparamCurve<T, Self, F>
where
F: Fn(f32) -> f32,
{
ReparamCurve {
domain,
base: self,
f,
_phantom: PhantomData,
}
}
/// Linearly reparametrize this [`Curve`], producing a new curve whose domain is the given
/// `domain` instead of the current one. This operation is only valid for curves with bounded
/// domains.
///
/// # Errors
///
/// If either this curve's domain or the given `domain` is unbounded, an error is returned.
fn reparametrize_linear(
self,
domain: Interval,
) -> Result<LinearReparamCurve<T, Self>, LinearReparamError> {
if !self.domain().is_bounded() {
return Err(LinearReparamError::SourceCurveUnbounded);
}
if !domain.is_bounded() {
return Err(LinearReparamError::TargetIntervalUnbounded);
}
Ok(LinearReparamCurve {
base: self,
new_domain: domain,
_phantom: PhantomData,
})
}
/// Reparametrize this [`Curve`] by sampling from another curve.
///
/// The resulting curve samples at time `t` by first sampling `other` at time `t`, which produces
/// another sample time `s` which is then used to sample this curve. The domain of the resulting
/// curve is the domain of `other`.
#[must_use]
fn reparametrize_by_curve<C>(self, other: C) -> CurveReparamCurve<T, Self, C>
where
C: Curve<f32>,
{
CurveReparamCurve {
base: self,
reparam_curve: other,
_phantom: PhantomData,
}
}
/// Create a new [`Curve`] which is the graph of this one; that is, its output echoes the sample
/// time as part of a tuple.
///
/// For example, if this curve outputs `x` at time `t`, then the produced curve will produce
/// `(t, x)` at time `t`. In particular, if this curve is a `Curve<T>`, the output of this method
/// is a `Curve<(f32, T)>`.
#[must_use]
fn graph(self) -> GraphCurve<T, Self> {
GraphCurve {
base: self,
_phantom: PhantomData,
}
}
/// Create a new [`Curve`] by zipping this curve together with another.
///
/// The sample at time `t` in the new curve is `(x, y)`, where `x` is the sample of `self` at
/// time `t` and `y` is the sample of `other` at time `t`. The domain of the new curve is the
/// intersection of the domains of its constituents.
///
/// # Errors
///
/// If the domain intersection would be empty, an error is returned instead.
fn zip<S, C>(self, other: C) -> Result<ZipCurve<T, S, Self, C>, InvalidIntervalError>
where
C: Curve<S> + Sized,
{
let domain = self.domain().intersect(other.domain())?;
Ok(ZipCurve {
domain,
first: self,
second: other,
_phantom: PhantomData,
})
}
/// Create a new [`Curve`] by composing this curve end-to-start with another, producing another curve
/// with outputs of the same type. The domain of the other curve is translated so that its start
/// coincides with where this curve ends.
///
/// # Errors
///
/// A [`ChainError`] is returned if this curve's domain doesn't have a finite end or if
/// `other`'s domain doesn't have a finite start.
fn chain<C>(self, other: C) -> Result<ChainCurve<T, Self, C>, ChainError>
where
C: Curve<T>,
{
if !self.domain().has_finite_end() {
return Err(ChainError::FirstEndInfinite);
}
if !other.domain().has_finite_start() {
return Err(ChainError::SecondStartInfinite);
}
Ok(ChainCurve {
first: self,
second: other,
_phantom: PhantomData,
})
}
/// Create a new [`Curve`] inverting this curve on the x-axis, producing another curve with
/// outputs of the same type, effectively playing backwards starting at `self.domain().end()`
/// and transitioning over to `self.domain().start()`. The domain of the new curve is still the
/// same.
///
/// # Errors
///
/// A [`ReverseError`] is returned if this curve's domain isn't bounded.
fn reverse(self) -> Result<ReverseCurve<T, Self>, ReverseError> {
self.domain()
.is_bounded()
.then(|| ReverseCurve {
curve: self,
_phantom: PhantomData,
})
.ok_or(ReverseError::SourceDomainEndInfinite)
}
/// Create a new [`Curve`] repeating this curve `N` times, producing another curve with outputs
/// of the same type. The domain of the new curve will be bigger by a factor of `n + 1`.
///
/// # Notes
///
/// - this doesn't guarantee a smooth transition from one occurrence of the curve to its next
/// iteration. The curve will make a jump if `self.domain().start() != self.domain().end()`!
/// - for `count == 0` the output of this adaptor is basically identical to the previous curve
/// - the value at the transitioning points (`domain.end() * n` for `n >= 1`) in the results is the
/// value at `domain.end()` in the original curve
///
/// # Errors
///
/// A [`RepeatError`] is returned if this curve's domain isn't bounded.
fn repeat(self, count: usize) -> Result<RepeatCurve<T, Self>, RepeatError> {
self.domain()
.is_bounded()
.then(|| {
// This unwrap always succeeds because `curve` has a valid Interval as its domain and the
// length of `curve` cannot be NAN. It's still fine if it's infinity.
let domain = Interval::new(
self.domain().start(),
self.domain().end() + self.domain().length() * count as f32,
)
.unwrap();
RepeatCurve {
domain,
curve: self,
_phantom: PhantomData,
}
})
.ok_or(RepeatError::SourceDomainUnbounded)
}
/// Create a new [`Curve`] repeating this curve forever, producing another curve with
/// outputs of the same type. The domain of the new curve will be unbounded.
///
/// # Notes
///
/// - this doesn't guarantee a smooth transition from one occurrence of the curve to its next
/// iteration. The curve will make a jump if `self.domain().start() != self.domain().end()`!
/// - the value at the transitioning points (`domain.end() * n` for `n >= 1`) in the results is the
/// value at `domain.end()` in the original curve
///
/// # Errors
///
/// A [`RepeatError`] is returned if this curve's domain isn't bounded.
fn forever(self) -> Result<ForeverCurve<T, Self>, RepeatError> {
self.domain()
.is_bounded()
.then(|| ForeverCurve {
curve: self,
_phantom: PhantomData,
})
.ok_or(RepeatError::SourceDomainUnbounded)
}
/// Create a new [`Curve`] chaining the original curve with its inverse, producing
/// another curve with outputs of the same type. The domain of the new curve will be twice as
/// long. The transition point is guaranteed to not make any jumps.
///
/// # Errors
///
/// A [`PingPongError`] is returned if this curve's domain isn't right-finite.
fn ping_pong(self) -> Result<PingPongCurve<T, Self>, PingPongError> {
self.domain()
.has_finite_end()
.then(|| PingPongCurve {
curve: self,
_phantom: PhantomData,
})
.ok_or(PingPongError::SourceDomainEndInfinite)
}
/// Create a new [`Curve`] by composing this curve end-to-start with another, producing another
/// curve with outputs of the same type. The domain of the other curve is translated so that
/// its start coincides with where this curve ends.
///
///
/// Additionally the transition of the samples is guaranteed to make no sudden jumps. This is
/// useful if you really just know about the shapes of your curves and don't want to deal with
/// stitching them together properly when it would just introduce useless complexity. It is
/// realized by translating the other curve so that its start sample point coincides with the
/// current curves' end sample point.
///
/// # Errors
///
/// A [`ChainError`] is returned if this curve's domain doesn't have a finite end or if
/// `other`'s domain doesn't have a finite start.
fn chain_continue<C>(self, other: C) -> Result<ContinuationCurve<T, Self, C>, ChainError>
where
T: VectorSpace,
C: Curve<T>,
{
if !self.domain().has_finite_end() {
return Err(ChainError::FirstEndInfinite);
}
if !other.domain().has_finite_start() {
return Err(ChainError::SecondStartInfinite);
}
let offset = self.sample_unchecked(self.domain().end())
- other.sample_unchecked(self.domain().start());
Ok(ContinuationCurve {
first: self,
second: other,
offset,
_phantom: PhantomData,
})
}
/// Extract an iterator over evenly-spaced samples from this curve.
///
/// # Errors
///
/// If `samples` is less than 2 or if this curve has unbounded domain, a [`ResamplingError`]
/// is returned.
fn samples(&self, samples: usize) -> Result<impl Iterator<Item = T>, ResamplingError> {
if samples < 2 {
return Err(ResamplingError::NotEnoughSamples(samples));
}
if !self.domain().is_bounded() {
return Err(ResamplingError::UnboundedDomain);
}
// Unwrap on `spaced_points` always succeeds because its error conditions are handled
// above.
Ok(self
.domain()
.spaced_points(samples)
.unwrap()
.map(|t| self.sample_unchecked(t)))
}
/// Borrow this curve rather than taking ownership of it. This is essentially an alias for a
/// prefix `&`; the point is that intermediate operations can be performed while retaining
/// access to the original curve.
///
/// # Example
/// ```
/// # use bevy_math::curve::*;
/// let my_curve = FunctionCurve::new(Interval::UNIT, |t| t * t + 1.0);
///
/// // Borrow `my_curve` long enough to resample a mapped version. Note that `map` takes
/// // ownership of its input.
/// let samples = my_curve.by_ref().map(|x| x * 2.0).resample_auto(100).unwrap();
///
/// // Do something else with `my_curve` since we retained ownership:
/// let new_curve = my_curve.reparametrize_linear(interval(-1.0, 1.0).unwrap()).unwrap();
/// ```
fn by_ref(&self) -> &Self {
self
}
/// Flip this curve so that its tuple output is arranged the other way.
#[must_use]
fn flip<U, V>(self) -> impl Curve<(V, U)>
where
Self: CurveExt<(U, V)>,
{
self.map(|(u, v)| (v, u))
}
}
impl<C, T> CurveExt<T> for C where C: Curve<T> {}
/// Extension trait implemented by [curves], allowing access to generic resampling methods as
/// well as those based on [stable interpolation].
///
/// This trait is automatically implemented for all curves.
///
/// For more information, see the [module-level documentation].
///
/// [curves]: Curve
/// [stable interpolation]: crate::StableInterpolate
/// [module-level documentation]: self
#[cfg(feature = "alloc")]
pub trait CurveResampleExt<T>: Curve<T> {
/// Resample this [`Curve`] to produce a new one that is defined by interpolation over equally
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/curve/cores.rs | crates/bevy_math/src/curve/cores.rs | //! Core data structures to be used internally in Curve implementations, encapsulating storage
//! and access patterns for reuse.
//!
//! The `Core` types here expose their fields publicly so that it is easier to manipulate and
//! extend them, but in doing so, you must maintain the invariants of those fields yourself. The
//! provided methods all maintain the invariants, so this is only a concern if you manually mutate
//! the fields.
use crate::ops;
use super::interval::Interval;
use core::fmt::Debug;
use thiserror::Error;
#[cfg(feature = "alloc")]
use {alloc::vec::Vec, itertools::Itertools};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
/// This type expresses the relationship of a value to a fixed collection of values. It is a kind
/// of summary used intermediately by sampling operations.
#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
pub enum InterpolationDatum<T> {
/// This value lies exactly on a value in the family.
Exact(T),
/// This value is off the left tail of the family; the inner value is the family's leftmost.
LeftTail(T),
/// This value is off the right tail of the family; the inner value is the family's rightmost.
RightTail(T),
/// This value lies on the interior, in between two points, with a third parameter expressing
/// the interpolation factor between the two.
Between(T, T, f32),
}
impl<T> InterpolationDatum<T> {
/// Map all values using a given function `f`, leaving the interpolation parameters in any
/// [`Between`] variants unchanged.
///
/// [`Between`]: `InterpolationDatum::Between`
#[must_use]
pub fn map<S>(self, f: impl Fn(T) -> S) -> InterpolationDatum<S> {
match self {
InterpolationDatum::Exact(v) => InterpolationDatum::Exact(f(v)),
InterpolationDatum::LeftTail(v) => InterpolationDatum::LeftTail(f(v)),
InterpolationDatum::RightTail(v) => InterpolationDatum::RightTail(f(v)),
InterpolationDatum::Between(u, v, s) => InterpolationDatum::Between(f(u), f(v), s),
}
}
}
/// The data core of a curve derived from evenly-spaced samples. The intention is to use this
/// in addition to explicit or inferred interpolation information in user-space in order to
/// implement curves using [`domain`] and [`sample_with`].
///
/// The internals are made transparent to give curve authors freedom, but [the provided constructor]
/// enforces the required invariants, and the methods maintain those invariants.
///
/// [the provided constructor]: EvenCore::new
/// [`domain`]: EvenCore::domain
/// [`sample_with`]: EvenCore::sample_with
///
/// # Example
/// ```rust
/// # use bevy_math::curve::*;
/// # use bevy_math::curve::cores::*;
/// // Let's make a curve that interpolates evenly spaced samples using either linear interpolation
/// // or step "interpolation" — i.e. just using the most recent sample as the source of truth.
/// enum InterpolationMode {
/// Linear,
/// Step,
/// }
///
/// // Linear interpolation mode is driven by a trait.
/// trait LinearInterpolate {
/// fn lerp(&self, other: &Self, t: f32) -> Self;
/// }
///
/// // Step interpolation just uses an explicit function.
/// fn step<T: Clone>(first: &T, second: &T, t: f32) -> T {
/// if t >= 1.0 {
/// second.clone()
/// } else {
/// first.clone()
/// }
/// }
///
/// // Omitted: Implementing `LinearInterpolate` on relevant types; e.g. `f32`, `Vec3`, and so on.
///
/// // The curve itself uses `EvenCore` to hold the evenly-spaced samples, and the `sample_with`
/// // function will do all the work of interpolating once given a function to do it with.
/// struct MyCurve<T> {
/// core: EvenCore<T>,
/// interpolation_mode: InterpolationMode,
/// }
///
/// impl<T> Curve<T> for MyCurve<T>
/// where
/// T: LinearInterpolate + Clone,
/// {
/// fn domain(&self) -> Interval {
/// self.core.domain()
/// }
///
/// fn sample_unchecked(&self, t: f32) -> T {
/// // To sample this curve, check the interpolation mode and dispatch accordingly.
/// match self.interpolation_mode {
/// InterpolationMode::Linear => self.core.sample_with(t, <T as LinearInterpolate>::lerp),
/// InterpolationMode::Step => self.core.sample_with(t, step),
/// }
/// }
/// }
/// ```
#[cfg(feature = "alloc")]
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
pub struct EvenCore<T> {
/// The domain over which the samples are taken, which corresponds to the domain of the curve
/// formed by interpolating them.
///
/// # Invariants
/// This must always be a bounded interval; i.e. its endpoints must be finite.
pub domain: Interval,
/// The samples that are interpolated to extract values.
///
/// # Invariants
/// This must always have a length of at least 2.
pub samples: Vec<T>,
}
/// An error indicating that an [`EvenCore`] could not be constructed.
#[derive(Debug, Error)]
#[error("Could not construct an EvenCore")]
pub enum EvenCoreError {
/// Not enough samples were provided.
#[error("Need at least two samples to create an EvenCore, but {samples} were provided")]
NotEnoughSamples {
/// The number of samples that were provided.
samples: usize,
},
/// Unbounded domains are not compatible with `EvenCore`.
#[error("Cannot create an EvenCore over an unbounded domain")]
UnboundedDomain,
}
#[cfg(feature = "alloc")]
impl<T> EvenCore<T> {
/// Create a new [`EvenCore`] from the specified `domain` and `samples`. The samples are
/// regarded to be evenly spaced within the given domain interval, so that the outermost
/// samples form the boundary of that interval. An error is returned if there are not at
/// least 2 samples or if the given domain is unbounded.
#[inline]
pub fn new(
domain: Interval,
samples: impl IntoIterator<Item = T>,
) -> Result<Self, EvenCoreError> {
let samples: Vec<T> = samples.into_iter().collect();
if samples.len() < 2 {
return Err(EvenCoreError::NotEnoughSamples {
samples: samples.len(),
});
}
if !domain.is_bounded() {
return Err(EvenCoreError::UnboundedDomain);
}
Ok(EvenCore { domain, samples })
}
/// The domain of the curve derived from this core.
#[inline]
pub const fn domain(&self) -> Interval {
self.domain
}
/// Obtain a value from the held samples using the given `interpolation` to interpolate
/// between adjacent samples.
///
/// The interpolation takes two values by reference together with a scalar parameter and
/// produces an owned value. The expectation is that `interpolation(&x, &y, 0.0)` and
/// `interpolation(&x, &y, 1.0)` are equivalent to `x` and `y` respectively.
#[inline]
pub fn sample_with<I>(&self, t: f32, interpolation: I) -> T
where
T: Clone,
I: Fn(&T, &T, f32) -> T,
{
match even_interp(self.domain, self.samples.len(), t) {
InterpolationDatum::Exact(idx)
| InterpolationDatum::LeftTail(idx)
| InterpolationDatum::RightTail(idx) => self.samples[idx].clone(),
InterpolationDatum::Between(lower_idx, upper_idx, s) => {
interpolation(&self.samples[lower_idx], &self.samples[upper_idx], s)
}
}
}
/// Given a time `t`, obtain a [`InterpolationDatum`] which governs how interpolation might recover
/// a sample at time `t`. For example, when a [`Between`] value is returned, its contents can
/// be used to interpolate between the two contained values with the given parameter. The other
/// variants give additional context about where the value is relative to the family of samples.
///
/// [`Between`]: `InterpolationDatum::Between`
pub fn sample_interp(&self, t: f32) -> InterpolationDatum<&T> {
even_interp(self.domain, self.samples.len(), t).map(|idx| &self.samples[idx])
}
/// Like [`sample_interp`], but the returned values include the sample times. This can be
/// useful when sample interpolation is not scale-invariant.
///
/// [`sample_interp`]: EvenCore::sample_interp
pub fn sample_interp_timed(&self, t: f32) -> InterpolationDatum<(f32, &T)> {
let segment_len = self.domain.length() / (self.samples.len() - 1) as f32;
even_interp(self.domain, self.samples.len(), t).map(|idx| {
(
self.domain.start() + segment_len * idx as f32,
&self.samples[idx],
)
})
}
}
/// Given a domain and a number of samples taken over that interval, return an [`InterpolationDatum`]
/// that governs how samples are extracted relative to the stored data.
///
/// `domain` must be a bounded interval (i.e. `domain.is_bounded() == true`).
///
/// `samples` must be at least 2.
///
/// This function will never panic, but it may return invalid indices if its assumptions are violated.
pub fn even_interp(domain: Interval, samples: usize, t: f32) -> InterpolationDatum<usize> {
let subdivs = samples - 1;
let step = domain.length() / subdivs as f32;
let t_shifted = t - domain.start();
let steps_taken = t_shifted / step;
if steps_taken <= 0.0 {
// To the left side of all the samples.
InterpolationDatum::LeftTail(0)
} else if steps_taken >= subdivs as f32 {
// To the right side of all the samples
InterpolationDatum::RightTail(samples - 1)
} else {
let lower_index = ops::floor(steps_taken) as usize;
// This upper index is always valid because `steps_taken` is a finite value
// strictly less than `samples - 1`, so its floor is at most `samples - 2`
let upper_index = lower_index + 1;
let s = ops::fract(steps_taken);
InterpolationDatum::Between(lower_index, upper_index, s)
}
}
/// The data core of a curve defined by unevenly-spaced samples or keyframes. The intention is to
/// use this in concert with implicitly or explicitly-defined interpolation in user-space in
/// order to implement the curve interface using [`domain`] and [`sample_with`].
///
/// The internals are made transparent to give curve authors freedom, but [the provided constructor]
/// enforces the required invariants, and the methods maintain those invariants.
///
/// # Example
/// ```rust
/// # use bevy_math::curve::*;
/// # use bevy_math::curve::cores::*;
/// // Let's make a curve formed by interpolating rotations.
/// // We'll support two common modes of interpolation:
/// // - Normalized linear: First do linear interpolation, then normalize to get a valid rotation.
/// // - Spherical linear: Interpolate through valid rotations with constant angular velocity.
/// enum InterpolationMode {
/// NormalizedLinear,
/// SphericalLinear,
/// }
///
/// // Our interpolation modes will be driven by traits.
/// trait NormalizedLinearInterpolate {
/// fn nlerp(&self, other: &Self, t: f32) -> Self;
/// }
///
/// trait SphericalLinearInterpolate {
/// fn slerp(&self, other: &Self, t: f32) -> Self;
/// }
///
/// // Omitted: These traits would be implemented for `Rot2`, `Quat`, and other rotation representations.
///
/// // The curve itself just needs to use the curve core for keyframes, `UnevenCore`, which handles
/// // everything except for the explicit interpolation used.
/// struct RotationCurve<T> {
/// core: UnevenCore<T>,
/// interpolation_mode: InterpolationMode,
/// }
///
/// impl<T> Curve<T> for RotationCurve<T>
/// where
/// T: NormalizedLinearInterpolate + SphericalLinearInterpolate + Clone,
/// {
/// fn domain(&self) -> Interval {
/// self.core.domain()
/// }
///
/// fn sample_unchecked(&self, t: f32) -> T {
/// // To sample the curve, we just look at the interpolation mode and
/// // dispatch accordingly.
/// match self.interpolation_mode {
/// InterpolationMode::NormalizedLinear =>
/// self.core.sample_with(t, <T as NormalizedLinearInterpolate>::nlerp),
/// InterpolationMode::SphericalLinear =>
/// self.core.sample_with(t, <T as SphericalLinearInterpolate>::slerp),
/// }
/// }
/// }
/// ```
///
/// [`domain`]: UnevenCore::domain
/// [`sample_with`]: UnevenCore::sample_with
/// [the provided constructor]: UnevenCore::new
#[cfg(feature = "alloc")]
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
pub struct UnevenCore<T> {
/// The times for the samples of this curve.
///
/// # Invariants
/// This must always have a length of at least 2, be sorted, and have no
/// duplicated or non-finite times.
pub times: Vec<f32>,
/// The samples corresponding to the times for this curve.
///
/// # Invariants
/// This must always have the same length as `times`.
pub samples: Vec<T>,
}
/// An error indicating that an [`UnevenCore`] could not be constructed.
#[derive(Debug, Error)]
#[error("Could not construct an UnevenCore")]
pub enum UnevenCoreError {
/// Not enough samples were provided.
#[error(
"Need at least two unique samples to create an UnevenCore, but {samples} were provided"
)]
NotEnoughSamples {
/// The number of samples that were provided.
samples: usize,
},
}
#[cfg(feature = "alloc")]
impl<T> UnevenCore<T> {
/// Create a new [`UnevenCore`]. The given samples are filtered to finite times and
/// sorted internally; if there are not at least 2 valid timed samples, an error will be
/// returned.
pub fn new(timed_samples: impl IntoIterator<Item = (f32, T)>) -> Result<Self, UnevenCoreError> {
// Filter out non-finite sample times first so they don't interfere with sorting/deduplication.
let mut timed_samples = timed_samples
.into_iter()
.filter(|(t, _)| t.is_finite())
.collect_vec();
timed_samples
// Using `total_cmp` is fine because no NANs remain and because deduplication uses
// `PartialEq` anyway (so -0.0 and 0.0 will be considered equal later regardless).
.sort_by(|(t0, _), (t1, _)| t0.total_cmp(t1));
timed_samples.dedup_by_key(|(t, _)| *t);
if timed_samples.len() < 2 {
return Err(UnevenCoreError::NotEnoughSamples {
samples: timed_samples.len(),
});
}
let (times, samples): (Vec<f32>, Vec<T>) = timed_samples.into_iter().unzip();
Ok(UnevenCore { times, samples })
}
/// The domain of the curve derived from this core.
///
/// # Panics
/// This method may panic if the type's invariants aren't satisfied.
#[inline]
pub fn domain(&self) -> Interval {
let start = self.times.first().unwrap();
let end = self.times.last().unwrap();
Interval::new(*start, *end).unwrap()
}
/// Obtain a value from the held samples using the given `interpolation` to interpolate
/// between adjacent samples.
///
/// The interpolation takes two values by reference together with a scalar parameter and
/// produces an owned value. The expectation is that `interpolation(&x, &y, 0.0)` and
/// `interpolation(&x, &y, 1.0)` are equivalent to `x` and `y` respectively.
#[inline]
pub fn sample_with<I>(&self, t: f32, interpolation: I) -> T
where
T: Clone,
I: Fn(&T, &T, f32) -> T,
{
match uneven_interp(&self.times, t) {
InterpolationDatum::Exact(idx)
| InterpolationDatum::LeftTail(idx)
| InterpolationDatum::RightTail(idx) => self.samples[idx].clone(),
InterpolationDatum::Between(lower_idx, upper_idx, s) => {
interpolation(&self.samples[lower_idx], &self.samples[upper_idx], s)
}
}
}
/// Given a time `t`, obtain a [`InterpolationDatum`] which governs how interpolation might recover
/// a sample at time `t`. For example, when a [`Between`] value is returned, its contents can
/// be used to interpolate between the two contained values with the given parameter. The other
/// variants give additional context about where the value is relative to the family of samples.
///
/// [`Between`]: `InterpolationDatum::Between`
pub fn sample_interp(&self, t: f32) -> InterpolationDatum<&T> {
uneven_interp(&self.times, t).map(|idx| &self.samples[idx])
}
/// Like [`sample_interp`], but the returned values include the sample times. This can be
/// useful when sample interpolation is not scale-invariant.
///
/// [`sample_interp`]: UnevenCore::sample_interp
pub fn sample_interp_timed(&self, t: f32) -> InterpolationDatum<(f32, &T)> {
uneven_interp(&self.times, t).map(|idx| (self.times[idx], &self.samples[idx]))
}
/// This core, but with the sample times moved by the map `f`.
/// In principle, when `f` is monotone, this is equivalent to [`CurveExt::reparametrize`],
/// but the function inputs to each are inverses of one another.
///
/// The samples are re-sorted by time after mapping and deduplicated by output time, so
/// the function `f` should generally be injective over the set of sample times, otherwise
/// data will be deleted.
///
/// [`CurveExt::reparametrize`]: crate::curve::CurveExt::reparametrize
#[must_use]
pub fn map_sample_times(mut self, f: impl Fn(f32) -> f32) -> UnevenCore<T> {
let mut timed_samples = self
.times
.into_iter()
.map(f)
.zip(self.samples)
.collect_vec();
timed_samples.sort_by(|(t1, _), (t2, _)| t1.total_cmp(t2));
timed_samples.dedup_by_key(|(t, _)| *t);
(self.times, self.samples) = timed_samples.into_iter().unzip();
self
}
}
/// The data core of a curve using uneven samples (i.e. keyframes), where each sample time
/// yields some fixed number of values — the [sampling width]. This may serve as storage for
/// curves that yield vectors or iterators, and in some cases, it may be useful for cache locality
/// if the sample type can effectively be encoded as a fixed-length slice of values.
///
/// [sampling width]: ChunkedUnevenCore::width
#[cfg(feature = "alloc")]
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
pub struct ChunkedUnevenCore<T> {
/// The times, one for each sample.
///
/// # Invariants
/// This must always have a length of at least 2, be sorted, and have no duplicated or
/// non-finite times.
pub times: Vec<f32>,
/// The values that are used in sampling. Each width-worth of these correspond to a single sample.
///
/// # Invariants
/// The length of this vector must always be some fixed integer multiple of that of `times`.
pub values: Vec<T>,
}
/// An error that indicates that a [`ChunkedUnevenCore`] could not be formed.
#[derive(Debug, Error)]
#[error("Could not create a ChunkedUnevenCore")]
pub enum ChunkedUnevenCoreError {
/// The width of a `ChunkedUnevenCore` cannot be zero.
#[error("Chunk width must be at least 1")]
ZeroWidth,
/// At least two sample times are necessary to interpolate in `ChunkedUnevenCore`.
#[error(
"Need at least two unique samples to create a ChunkedUnevenCore, but {samples} were provided"
)]
NotEnoughSamples {
/// The number of samples that were provided.
samples: usize,
},
/// The length of the value buffer is supposed to be the `width` times the number of samples.
#[error("Expected {expected} total values based on width, but {actual} were provided")]
MismatchedLengths {
/// The expected length of the value buffer.
expected: usize,
/// The actual length of the value buffer.
actual: usize,
},
/// Tried to infer the width, but the ratio of lengths wasn't an integer, so no such length exists.
#[error("The length of the list of values ({values_len}) was not divisible by that of the list of times ({times_len})")]
NonDivisibleLengths {
/// The length of the value buffer.
values_len: usize,
/// The length of the time buffer.
times_len: usize,
},
}
#[cfg(feature = "alloc")]
impl<T> ChunkedUnevenCore<T> {
/// Create a new [`ChunkedUnevenCore`]. The given `times` are sorted, filtered to finite times,
/// and deduplicated. See the [type-level documentation] for more information about this type.
///
/// Produces an error in any of the following circumstances:
/// - `width` is zero.
/// - `times` has less than `2` unique valid entries.
/// - `values` has the incorrect length relative to `times`.
///
/// [type-level documentation]: ChunkedUnevenCore
pub fn new(
times: impl IntoIterator<Item = f32>,
values: impl IntoIterator<Item = T>,
width: usize,
) -> Result<Self, ChunkedUnevenCoreError> {
let times = times.into_iter().collect_vec();
let values = values.into_iter().collect_vec();
if width == 0 {
return Err(ChunkedUnevenCoreError::ZeroWidth);
}
let times = filter_sort_dedup_times(times);
if times.len() < 2 {
return Err(ChunkedUnevenCoreError::NotEnoughSamples {
samples: times.len(),
});
}
if values.len() != times.len() * width {
return Err(ChunkedUnevenCoreError::MismatchedLengths {
expected: times.len() * width,
actual: values.len(),
});
}
Ok(Self { times, values })
}
/// Create a new [`ChunkedUnevenCore`], inferring the width from the sizes of the inputs.
/// The given `times` are sorted, filtered to finite times, and deduplicated. See the
/// [type-level documentation] for more information about this type. Prefer using [`new`]
/// if possible, since that constructor has richer error checking.
///
/// Produces an error in any of the following circumstances:
/// - `values` has length zero.
/// - `times` has less than `2` unique valid entries.
/// - The length of `values` is not divisible by that of `times` (once sorted, filtered,
/// and deduplicated).
///
/// The [width] is implicitly taken to be the length of `values` divided by that of `times`
/// (once sorted, filtered, and deduplicated).
///
/// [type-level documentation]: ChunkedUnevenCore
/// [`new`]: ChunkedUnevenCore::new
/// [width]: ChunkedUnevenCore::width
pub fn new_width_inferred(
times: impl IntoIterator<Item = f32>,
values: impl IntoIterator<Item = T>,
) -> Result<Self, ChunkedUnevenCoreError> {
let times = times.into_iter().collect_vec();
let values = values.into_iter().collect_vec();
let times = filter_sort_dedup_times(times);
if times.len() < 2 {
return Err(ChunkedUnevenCoreError::NotEnoughSamples {
samples: times.len(),
});
}
if values.len() % times.len() != 0 {
return Err(ChunkedUnevenCoreError::NonDivisibleLengths {
values_len: values.len(),
times_len: times.len(),
});
}
if values.is_empty() {
return Err(ChunkedUnevenCoreError::ZeroWidth);
}
Ok(Self { times, values })
}
/// The domain of the curve derived from this core.
///
/// # Panics
/// This may panic if this type's invariants aren't met.
#[inline]
pub fn domain(&self) -> Interval {
let start = self.times.first().unwrap();
let end = self.times.last().unwrap();
Interval::new(*start, *end).unwrap()
}
/// The sample width: the number of values that are contained in each sample.
#[inline]
pub fn width(&self) -> usize {
self.values.len() / self.times.len()
}
/// Given a time `t`, obtain a [`InterpolationDatum`] which governs how interpolation might recover
/// a sample at time `t`. For example, when a [`Between`] value is returned, its contents can
/// be used to interpolate between the two contained values with the given parameter. The other
/// variants give additional context about where the value is relative to the family of samples.
///
/// [`Between`]: `InterpolationDatum::Between`
#[inline]
pub fn sample_interp(&self, t: f32) -> InterpolationDatum<&[T]> {
uneven_interp(&self.times, t).map(|idx| self.time_index_to_slice(idx))
}
/// Like [`sample_interp`], but the returned values include the sample times. This can be
/// useful when sample interpolation is not scale-invariant.
///
/// [`sample_interp`]: ChunkedUnevenCore::sample_interp
pub fn sample_interp_timed(&self, t: f32) -> InterpolationDatum<(f32, &[T])> {
uneven_interp(&self.times, t).map(|idx| (self.times[idx], self.time_index_to_slice(idx)))
}
/// Given an index in [times], returns the slice of [values] that correspond to the sample at
/// that time.
///
/// [times]: ChunkedUnevenCore::times
/// [values]: ChunkedUnevenCore::values
#[inline]
fn time_index_to_slice(&self, idx: usize) -> &[T] {
let width = self.width();
let lower_idx = width * idx;
let upper_idx = lower_idx + width;
&self.values[lower_idx..upper_idx]
}
}
/// Sort the given times, deduplicate them, and filter them to only finite times.
#[cfg(feature = "alloc")]
fn filter_sort_dedup_times(times: impl IntoIterator<Item = f32>) -> Vec<f32> {
// Filter before sorting/deduplication so that NAN doesn't interfere with them.
let mut times = times.into_iter().filter(|t| t.is_finite()).collect_vec();
times.sort_by(f32::total_cmp);
times.dedup();
times
}
/// Given a list of `times` and a target value, get the interpolation relationship for the
/// target value in terms of the indices of the starting list. In a sense, this encapsulates the
/// heart of uneven/keyframe sampling.
///
/// `times` is assumed to be sorted, deduplicated, and consisting only of finite values. It is also
/// assumed to contain at least two values.
///
/// # Panics
/// This function will panic if `times` contains NAN.
pub fn uneven_interp(times: &[f32], t: f32) -> InterpolationDatum<usize> {
match times.binary_search_by(|pt| pt.partial_cmp(&t).unwrap()) {
Ok(index) => InterpolationDatum::Exact(index),
Err(index) => {
if index == 0 {
// This is before the first keyframe.
InterpolationDatum::LeftTail(0)
} else if index >= times.len() {
// This is after the last keyframe.
InterpolationDatum::RightTail(times.len() - 1)
} else {
// This is actually in the middle somewhere.
let t_lower = times[index - 1];
let t_upper = times[index];
let s = (t - t_lower) / (t_upper - t_lower);
InterpolationDatum::Between(index - 1, index, s)
}
}
}
}
#[cfg(all(test, feature = "alloc"))]
mod tests {
use super::{ChunkedUnevenCore, EvenCore, UnevenCore};
use crate::curve::{cores::InterpolationDatum, interval};
use alloc::vec;
use approx::{assert_abs_diff_eq, AbsDiffEq};
fn approx_between<T>(datum: InterpolationDatum<T>, start: T, end: T, p: f32) -> bool
where
T: PartialEq,
{
if let InterpolationDatum::Between(m_start, m_end, m_p) = datum {
m_start == start && m_end == end && m_p.abs_diff_eq(&p, 1e-6)
} else {
false
}
}
fn is_left_tail<T>(datum: InterpolationDatum<T>) -> bool {
matches!(datum, InterpolationDatum::LeftTail(_))
}
fn is_right_tail<T>(datum: InterpolationDatum<T>) -> bool {
matches!(datum, InterpolationDatum::RightTail(_))
}
fn is_exact<T>(datum: InterpolationDatum<T>, target: T) -> bool
where
T: PartialEq,
{
if let InterpolationDatum::Exact(v) = datum {
v == target
} else {
false
}
}
#[test]
fn even_sample_interp() {
let even_core = EvenCore::<f32>::new(
interval(0.0, 1.0).unwrap(),
// 11 entries -> 10 segments
vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0],
)
.expect("Failed to construct test core");
let datum = even_core.sample_interp(-1.0);
assert!(is_left_tail(datum));
let datum = even_core.sample_interp(0.0);
assert!(is_left_tail(datum));
let datum = even_core.sample_interp(1.0);
assert!(is_right_tail(datum));
let datum = even_core.sample_interp(2.0);
assert!(is_right_tail(datum));
let datum = even_core.sample_interp(0.05);
let InterpolationDatum::Between(0.0, 1.0, p) = datum else {
panic!("Sample did not lie in the correct subinterval")
};
assert_abs_diff_eq!(p, 0.5);
let datum = even_core.sample_interp(0.05);
assert!(approx_between(datum, &0.0, &1.0, 0.5));
let datum = even_core.sample_interp(0.33);
assert!(approx_between(datum, &3.0, &4.0, 0.3));
let datum = even_core.sample_interp(0.78);
assert!(approx_between(datum, &7.0, &8.0, 0.8));
let datum = even_core.sample_interp(0.5);
assert!(approx_between(datum, &4.0, &5.0, 1.0) || approx_between(datum, &5.0, &6.0, 0.0));
let datum = even_core.sample_interp(0.7);
assert!(approx_between(datum, &6.0, &7.0, 1.0) || approx_between(datum, &7.0, &8.0, 0.0));
}
#[test]
fn uneven_sample_interp() {
let uneven_core = UnevenCore::<f32>::new(vec![
(0.0, 0.0),
(1.0, 3.0),
(2.0, 9.0),
(4.0, 10.0),
(8.0, -5.0),
])
.expect("Failed to construct test core");
let datum = uneven_core.sample_interp(-1.0);
assert!(is_left_tail(datum));
let datum = uneven_core.sample_interp(0.0);
assert!(is_exact(datum, &0.0));
let datum = uneven_core.sample_interp(8.0);
assert!(is_exact(datum, &(-5.0)));
let datum = uneven_core.sample_interp(9.0);
assert!(is_right_tail(datum));
let datum = uneven_core.sample_interp(0.5);
assert!(approx_between(datum, &0.0, &3.0, 0.5));
let datum = uneven_core.sample_interp(2.5);
assert!(approx_between(datum, &9.0, &10.0, 0.25));
let datum = uneven_core.sample_interp(7.0);
assert!(approx_between(datum, &10.0, &(-5.0), 0.75));
let datum = uneven_core.sample_interp(2.0);
assert!(is_exact(datum, &9.0));
let datum = uneven_core.sample_interp(4.0);
assert!(is_exact(datum, &10.0));
}
#[test]
fn chunked_uneven_sample_interp() {
let core =
ChunkedUnevenCore::new(vec![0.0, 2.0, 8.0], vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0], 2)
.expect("Failed to construct test core");
let datum = core.sample_interp(-1.0);
assert!(is_left_tail(datum));
let datum = core.sample_interp(0.0);
assert!(is_exact(datum, &[0.0, 1.0]));
let datum = core.sample_interp(8.0);
assert!(is_exact(datum, &[4.0, 5.0]));
let datum = core.sample_interp(10.0);
assert!(is_right_tail(datum));
let datum = core.sample_interp(1.0);
assert!(approx_between(datum, &[0.0, 1.0], &[2.0, 3.0], 0.5));
let datum = core.sample_interp(3.0);
assert!(approx_between(datum, &[2.0, 3.0], &[4.0, 5.0], 1.0 / 6.0));
let datum = core.sample_interp(2.0);
assert!(is_exact(datum, &[2.0, 3.0]));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/curve/sample_curves.rs | crates/bevy_math/src/curve/sample_curves.rs | //! Sample-interpolated curves constructed using the [`Curve`] API.
use super::cores::{EvenCore, EvenCoreError, UnevenCore, UnevenCoreError};
use super::{Curve, Interval};
use crate::StableInterpolate;
#[cfg(feature = "bevy_reflect")]
use alloc::format;
use core::any::type_name;
use core::fmt::{self, Debug};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{utility::GenericTypePathCell, Reflect, TypePath};
#[cfg(feature = "bevy_reflect")]
mod paths {
pub(super) const THIS_MODULE: &str = "bevy_math::curve::sample_curves";
pub(super) const THIS_CRATE: &str = "bevy_math";
}
/// A curve that is defined by explicit neighbor interpolation over a set of evenly-spaced samples.
#[derive(Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(where T: TypePath),
reflect(from_reflect = false, type_path = false),
)]
pub struct SampleCurve<T, I> {
pub(crate) core: EvenCore<T>,
#[cfg_attr(feature = "bevy_reflect", reflect(ignore))]
pub(crate) interpolation: I,
}
impl<T, I> Debug for SampleCurve<T, I>
where
EvenCore<T>: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SampleCurve")
.field("core", &self.core)
.field("interpolation", &type_name::<I>())
.finish()
}
}
/// Note: This is not a fully stable implementation of `TypePath` due to usage of `type_name`
/// for function members.
#[cfg(feature = "bevy_reflect")]
impl<T, I> TypePath for SampleCurve<T, I>
where
T: TypePath,
I: 'static,
{
fn type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| {
format!(
"{}::SampleCurve<{},{}>",
paths::THIS_MODULE,
T::type_path(),
type_name::<I>()
)
})
}
fn short_type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| {
format!("SampleCurve<{},{}>", T::type_path(), type_name::<I>())
})
}
fn type_ident() -> Option<&'static str> {
Some("SampleCurve")
}
fn crate_name() -> Option<&'static str> {
Some(paths::THIS_CRATE)
}
fn module_path() -> Option<&'static str> {
Some(paths::THIS_MODULE)
}
}
impl<T, I> Curve<T> for SampleCurve<T, I>
where
T: Clone,
I: Fn(&T, &T, f32) -> T,
{
#[inline]
fn domain(&self) -> Interval {
self.core.domain()
}
#[inline]
fn sample_clamped(&self, t: f32) -> T {
// `EvenCore::sample_with` is implicitly clamped.
self.core.sample_with(t, &self.interpolation)
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
self.sample_clamped(t)
}
}
impl<T, I> SampleCurve<T, I> {
/// Create a new [`SampleCurve`] using the specified `interpolation` to interpolate between
/// the given `samples`. An error is returned if there are not at least 2 samples or if the
/// given `domain` is unbounded.
///
/// The interpolation takes two values by reference together with a scalar parameter and
/// produces an owned value. The expectation is that `interpolation(&x, &y, 0.0)` and
/// `interpolation(&x, &y, 1.0)` are equivalent to `x` and `y` respectively.
pub fn new(
domain: Interval,
samples: impl IntoIterator<Item = T>,
interpolation: I,
) -> Result<Self, EvenCoreError>
where
I: Fn(&T, &T, f32) -> T,
{
Ok(Self {
core: EvenCore::new(domain, samples)?,
interpolation,
})
}
}
/// A curve that is defined by neighbor interpolation over a set of evenly-spaced samples,
/// interpolated automatically using [a particularly well-behaved interpolation].
///
/// [a particularly well-behaved interpolation]: StableInterpolate
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
pub struct SampleAutoCurve<T> {
pub(crate) core: EvenCore<T>,
}
impl<T> Curve<T> for SampleAutoCurve<T>
where
T: StableInterpolate,
{
#[inline]
fn domain(&self) -> Interval {
self.core.domain()
}
#[inline]
fn sample_clamped(&self, t: f32) -> T {
// `EvenCore::sample_with` is implicitly clamped.
self.core
.sample_with(t, <T as StableInterpolate>::interpolate_stable)
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
self.sample_clamped(t)
}
}
impl<T> SampleAutoCurve<T> {
/// Create a new [`SampleCurve`] using type-inferred interpolation to interpolate between
/// the given `samples`. An error is returned if there are not at least 2 samples or if the
/// given `domain` is unbounded.
pub fn new(
domain: Interval,
samples: impl IntoIterator<Item = T>,
) -> Result<Self, EvenCoreError> {
Ok(Self {
core: EvenCore::new(domain, samples)?,
})
}
}
/// A curve that is defined by interpolation over unevenly spaced samples with explicit
/// interpolation.
#[derive(Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(where T: TypePath),
reflect(from_reflect = false, type_path = false),
)]
pub struct UnevenSampleCurve<T, I> {
pub(crate) core: UnevenCore<T>,
#[cfg_attr(feature = "bevy_reflect", reflect(ignore))]
pub(crate) interpolation: I,
}
impl<T, I> Debug for UnevenSampleCurve<T, I>
where
UnevenCore<T>: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SampleCurve")
.field("core", &self.core)
.field("interpolation", &type_name::<I>())
.finish()
}
}
/// Note: This is not a fully stable implementation of `TypePath` due to usage of `type_name`
/// for function members.
#[cfg(feature = "bevy_reflect")]
impl<T, I> TypePath for UnevenSampleCurve<T, I>
where
T: TypePath,
I: 'static,
{
fn type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| {
format!(
"{}::UnevenSampleCurve<{},{}>",
paths::THIS_MODULE,
T::type_path(),
type_name::<I>()
)
})
}
fn short_type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| {
format!("UnevenSampleCurve<{},{}>", T::type_path(), type_name::<I>())
})
}
fn type_ident() -> Option<&'static str> {
Some("UnevenSampleCurve")
}
fn crate_name() -> Option<&'static str> {
Some(paths::THIS_CRATE)
}
fn module_path() -> Option<&'static str> {
Some(paths::THIS_MODULE)
}
}
impl<T, I> Curve<T> for UnevenSampleCurve<T, I>
where
T: Clone,
I: Fn(&T, &T, f32) -> T,
{
#[inline]
fn domain(&self) -> Interval {
self.core.domain()
}
#[inline]
fn sample_clamped(&self, t: f32) -> T {
// `UnevenCore::sample_with` is implicitly clamped.
self.core.sample_with(t, &self.interpolation)
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
self.sample_clamped(t)
}
}
impl<T, I> UnevenSampleCurve<T, I> {
/// Create a new [`UnevenSampleCurve`] using the provided `interpolation` to interpolate
/// between adjacent `timed_samples`. The given samples are filtered to finite times and
/// sorted internally; if there are not at least 2 valid timed samples, an error will be
/// returned.
///
/// The interpolation takes two values by reference together with a scalar parameter and
/// produces an owned value. The expectation is that `interpolation(&x, &y, 0.0)` and
/// `interpolation(&x, &y, 1.0)` are equivalent to `x` and `y` respectively.
pub fn new(
timed_samples: impl IntoIterator<Item = (f32, T)>,
interpolation: I,
) -> Result<Self, UnevenCoreError>
where
I: Fn(&T, &T, f32) -> T,
{
Ok(Self {
core: UnevenCore::new(timed_samples)?,
interpolation,
})
}
/// This [`UnevenSampleAutoCurve`], but with the sample times moved by the map `f`.
/// In principle, when `f` is monotone, this is equivalent to [`CurveExt::reparametrize`],
/// but the function inputs to each are inverses of one another.
///
/// The samples are re-sorted by time after mapping and deduplicated by output time, so
/// the function `f` should generally be injective over the sample times of the curve.
///
/// [`CurveExt::reparametrize`]: super::CurveExt::reparametrize
pub fn map_sample_times(self, f: impl Fn(f32) -> f32) -> UnevenSampleCurve<T, I> {
Self {
core: self.core.map_sample_times(f),
interpolation: self.interpolation,
}
}
}
/// A curve that is defined by interpolation over unevenly spaced samples,
/// interpolated automatically using [a particularly well-behaved interpolation].
///
/// [a particularly well-behaved interpolation]: StableInterpolate
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
pub struct UnevenSampleAutoCurve<T> {
pub(crate) core: UnevenCore<T>,
}
impl<T> Curve<T> for UnevenSampleAutoCurve<T>
where
T: StableInterpolate,
{
#[inline]
fn domain(&self) -> Interval {
self.core.domain()
}
#[inline]
fn sample_clamped(&self, t: f32) -> T {
// `UnevenCore::sample_with` is implicitly clamped.
self.core
.sample_with(t, <T as StableInterpolate>::interpolate_stable)
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
self.sample_clamped(t)
}
}
impl<T> UnevenSampleAutoCurve<T> {
/// Create a new [`UnevenSampleAutoCurve`] from a given set of timed samples.
///
/// The samples are filtered to finite times and sorted internally; if there are not
/// at least 2 valid timed samples, an error will be returned.
pub fn new(timed_samples: impl IntoIterator<Item = (f32, T)>) -> Result<Self, UnevenCoreError> {
Ok(Self {
core: UnevenCore::new(timed_samples)?,
})
}
/// This [`UnevenSampleAutoCurve`], but with the sample times moved by the map `f`.
/// In principle, when `f` is monotone, this is equivalent to [`CurveExt::reparametrize`],
/// but the function inputs to each are inverses of one another.
///
/// The samples are re-sorted by time after mapping and deduplicated by output time, so
/// the function `f` should generally be injective over the sample times of the curve.
///
/// [`CurveExt::reparametrize`]: super::CurveExt::reparametrize
pub fn map_sample_times(self, f: impl Fn(f32) -> f32) -> UnevenSampleAutoCurve<T> {
Self {
core: self.core.map_sample_times(f),
}
}
}
#[cfg(test)]
#[cfg(feature = "bevy_reflect")]
mod tests {
//! These tests should guarantee (by even compiling) that `SampleCurve` and `UnevenSampleCurve`
//! can be `Reflect` under reasonable circumstances where their interpolation is defined by:
//! - function items
//! - 'static closures
//! - function pointers
use super::{SampleCurve, UnevenSampleCurve};
use crate::{curve::Interval, VectorSpace};
use alloc::boxed::Box;
use bevy_reflect::Reflect;
#[test]
fn reflect_sample_curve() {
fn foo(x: &f32, y: &f32, t: f32) -> f32 {
x.lerp(*y, t)
}
let bar = |x: &f32, y: &f32, t: f32| x.lerp(*y, t);
let baz: fn(&f32, &f32, f32) -> f32 = bar;
let samples = [0.0, 1.0, 2.0];
let _: Box<dyn Reflect> = Box::new(SampleCurve::new(Interval::UNIT, samples, foo).unwrap());
let _: Box<dyn Reflect> = Box::new(SampleCurve::new(Interval::UNIT, samples, bar).unwrap());
let _: Box<dyn Reflect> = Box::new(SampleCurve::new(Interval::UNIT, samples, baz).unwrap());
}
#[test]
fn reflect_uneven_sample_curve() {
fn foo(x: &f32, y: &f32, t: f32) -> f32 {
x.lerp(*y, t)
}
let bar = |x: &f32, y: &f32, t: f32| x.lerp(*y, t);
let baz: fn(&f32, &f32, f32) -> f32 = bar;
let keyframes = [(0.0, 1.0), (1.0, 0.0), (2.0, -1.0)];
let _: Box<dyn Reflect> = Box::new(UnevenSampleCurve::new(keyframes, foo).unwrap());
let _: Box<dyn Reflect> = Box::new(UnevenSampleCurve::new(keyframes, bar).unwrap());
let _: Box<dyn Reflect> = Box::new(UnevenSampleCurve::new(keyframes, baz).unwrap());
}
#[test]
fn test_infer_interp_arguments() {
// it should be possible to infer the x and y arguments of the interpolation function
// from the input samples. If that becomes impossible, this will fail to compile.
SampleCurve::new(Interval::UNIT, [0.0, 1.0], |x, y, t| x.lerp(*y, t)).ok();
UnevenSampleCurve::new([(0.1, 1.0), (1.0, 3.0)], |x, y, t| x.lerp(*y, t)).ok();
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/curve/interval.rs | crates/bevy_math/src/curve/interval.rs | //! The [`Interval`] type for nonempty intervals used by the [`Curve`](super::Curve) trait.
use core::{
cmp::{max_by, min_by},
ops::RangeInclusive,
};
use itertools::Either;
use thiserror::Error;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
#[cfg(all(feature = "serialize", feature = "bevy_reflect"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
/// A nonempty closed interval, possibly unbounded in either direction.
///
/// In other words, the interval may stretch all the way to positive or negative infinity, but it
/// will always have some nonempty interior.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Interval {
start: f32,
end: f32,
}
/// An error that indicates that an operation would have returned an invalid [`Interval`].
#[derive(Debug, Error)]
#[error("The resulting interval would be invalid (empty or with a NaN endpoint)")]
pub struct InvalidIntervalError;
/// An error indicating that spaced points could not be extracted from an unbounded interval.
#[derive(Debug, Error)]
#[error("Cannot extract spaced points from an unbounded interval")]
pub struct SpacedPointsError;
/// An error indicating that a linear map between intervals could not be constructed because of
/// unboundedness.
#[derive(Debug, Error)]
#[error("Could not construct linear function to map between intervals")]
pub(super) enum LinearMapError {
/// The source interval being mapped out of was unbounded.
#[error("The source interval is unbounded")]
SourceUnbounded,
/// The target interval being mapped into was unbounded.
#[error("The target interval is unbounded")]
TargetUnbounded,
}
impl Interval {
/// Create a new [`Interval`] with the specified `start` and `end`. The interval can be unbounded
/// but cannot be empty (so `start` must be less than `end`) and neither endpoint can be NaN; invalid
/// parameters will result in an error.
#[inline]
pub const fn new(start: f32, end: f32) -> Result<Self, InvalidIntervalError> {
if start >= end || start.is_nan() || end.is_nan() {
Err(InvalidIntervalError)
} else {
Ok(Self { start, end })
}
}
/// An interval of length 1.0, starting at 0.0 and ending at 1.0.
pub const UNIT: Self = Self {
start: 0.0,
end: 1.0,
};
/// An interval which stretches across the entire real line from negative infinity to infinity.
pub const EVERYWHERE: Self = Self {
start: f32::NEG_INFINITY,
end: f32::INFINITY,
};
/// Get the start of this interval.
#[inline]
pub const fn start(self) -> f32 {
self.start
}
/// Get the end of this interval.
#[inline]
pub const fn end(self) -> f32 {
self.end
}
/// Create an [`Interval`] by intersecting this interval with another. Returns an error if the
/// intersection would be empty (hence an invalid interval).
pub fn intersect(self, other: Interval) -> Result<Interval, InvalidIntervalError> {
let lower = max_by(self.start, other.start, f32::total_cmp);
let upper = min_by(self.end, other.end, f32::total_cmp);
Self::new(lower, upper)
}
/// Get the length of this interval. Note that the result may be infinite (`f32::INFINITY`).
#[inline]
pub const fn length(self) -> f32 {
self.end - self.start
}
/// Returns `true` if this interval is bounded — that is, if both its start and end are finite.
///
/// Equivalently, an interval is bounded if its length is finite.
#[inline]
pub const fn is_bounded(self) -> bool {
self.length().is_finite()
}
/// Returns `true` if this interval has a finite start.
#[inline]
pub const fn has_finite_start(self) -> bool {
self.start.is_finite()
}
/// Returns `true` if this interval has a finite end.
#[inline]
pub const fn has_finite_end(self) -> bool {
self.end.is_finite()
}
/// Returns `true` if `item` is contained in this interval.
#[inline]
pub fn contains(self, item: f32) -> bool {
(self.start..=self.end).contains(&item)
}
/// Returns `true` if the other interval is contained in this interval.
///
/// This is non-strict: each interval will contain itself.
#[inline]
pub const fn contains_interval(self, other: Self) -> bool {
self.start <= other.start && self.end >= other.end
}
/// Clamp the given `value` to lie within this interval.
#[inline]
pub const fn clamp(self, value: f32) -> f32 {
value.clamp(self.start, self.end)
}
/// Get an iterator over equally-spaced points from this interval in increasing order.
/// If `points` is 1, the start of this interval is returned. If `points` is 0, an empty
/// iterator is returned. An error is returned if the interval is unbounded.
#[inline]
pub fn spaced_points(
self,
points: usize,
) -> Result<impl Iterator<Item = f32>, SpacedPointsError> {
if !self.is_bounded() {
return Err(SpacedPointsError);
}
if points < 2 {
// If `points` is 1, this is `Some(self.start)` as an iterator, and if `points` is 0,
// then this is `None` as an iterator. This is written this way to avoid having to
// introduce a ternary disjunction of iterators.
let iter = (points == 1).then_some(self.start).into_iter();
return Ok(Either::Left(iter));
}
let step = self.length() / (points - 1) as f32;
let iter = (0..points).map(move |x| self.start + x as f32 * step);
Ok(Either::Right(iter))
}
/// Get the linear function which maps this interval onto the `other` one. Returns an error if either
/// interval is unbounded.
#[inline]
pub(super) fn linear_map_to(self, other: Self) -> Result<impl Fn(f32) -> f32, LinearMapError> {
if !self.is_bounded() {
return Err(LinearMapError::SourceUnbounded);
}
if !other.is_bounded() {
return Err(LinearMapError::TargetUnbounded);
}
let scale = other.length() / self.length();
Ok(move |x| (x - self.start) * scale + other.start)
}
}
impl TryFrom<RangeInclusive<f32>> for Interval {
type Error = InvalidIntervalError;
fn try_from(range: RangeInclusive<f32>) -> Result<Self, Self::Error> {
Interval::new(*range.start(), *range.end())
}
}
/// Create an [`Interval`] with a given `start` and `end`. Alias of [`Interval::new`].
#[inline]
pub const fn interval(start: f32, end: f32) -> Result<Interval, InvalidIntervalError> {
Interval::new(start, end)
}
#[cfg(test)]
mod tests {
use crate::ops;
use super::*;
use alloc::vec::Vec;
use approx::{assert_abs_diff_eq, AbsDiffEq};
#[test]
fn make_intervals() {
let ivl = Interval::new(2.0, -1.0);
assert!(ivl.is_err());
let ivl = Interval::new(-0.0, 0.0);
assert!(ivl.is_err());
let ivl = Interval::new(f32::NEG_INFINITY, 15.5);
assert!(ivl.is_ok());
let ivl = Interval::new(-2.0, f32::INFINITY);
assert!(ivl.is_ok());
let ivl = Interval::new(f32::NEG_INFINITY, f32::INFINITY);
assert!(ivl.is_ok());
let ivl = Interval::new(f32::INFINITY, f32::NEG_INFINITY);
assert!(ivl.is_err());
let ivl = Interval::new(-1.0, f32::NAN);
assert!(ivl.is_err());
let ivl = Interval::new(f32::NAN, -42.0);
assert!(ivl.is_err());
let ivl = Interval::new(f32::NAN, f32::NAN);
assert!(ivl.is_err());
let ivl = Interval::new(0.0, 1.0);
assert!(ivl.is_ok());
}
#[test]
fn lengths() {
let ivl = interval(-5.0, 10.0).unwrap();
assert!(ops::abs(ivl.length() - 15.0) <= f32::EPSILON);
let ivl = interval(5.0, 100.0).unwrap();
assert!(ops::abs(ivl.length() - 95.0) <= f32::EPSILON);
let ivl = interval(0.0, f32::INFINITY).unwrap();
assert_eq!(ivl.length(), f32::INFINITY);
let ivl = interval(f32::NEG_INFINITY, 0.0).unwrap();
assert_eq!(ivl.length(), f32::INFINITY);
let ivl = Interval::EVERYWHERE;
assert_eq!(ivl.length(), f32::INFINITY);
}
#[test]
fn intersections() {
let ivl1 = interval(-1.0, 1.0).unwrap();
let ivl2 = interval(0.0, 2.0).unwrap();
let ivl3 = interval(-3.0, 0.0).unwrap();
let ivl4 = interval(0.0, f32::INFINITY).unwrap();
let ivl5 = interval(f32::NEG_INFINITY, 0.0).unwrap();
let ivl6 = Interval::EVERYWHERE;
assert!(ivl1.intersect(ivl2).is_ok_and(|ivl| ivl == Interval::UNIT));
assert!(ivl1
.intersect(ivl3)
.is_ok_and(|ivl| ivl == interval(-1.0, 0.0).unwrap()));
assert!(ivl2.intersect(ivl3).is_err());
assert!(ivl1.intersect(ivl4).is_ok_and(|ivl| ivl == Interval::UNIT));
assert!(ivl1
.intersect(ivl5)
.is_ok_and(|ivl| ivl == interval(-1.0, 0.0).unwrap()));
assert!(ivl4.intersect(ivl5).is_err());
assert_eq!(ivl1.intersect(ivl6).unwrap(), ivl1);
assert_eq!(ivl4.intersect(ivl6).unwrap(), ivl4);
assert_eq!(ivl5.intersect(ivl6).unwrap(), ivl5);
}
#[test]
fn containment() {
let ivl = Interval::UNIT;
assert!(ivl.contains(0.0));
assert!(ivl.contains(1.0));
assert!(ivl.contains(0.5));
assert!(!ivl.contains(-0.1));
assert!(!ivl.contains(1.1));
assert!(!ivl.contains(f32::NAN));
let ivl = interval(3.0, f32::INFINITY).unwrap();
assert!(ivl.contains(3.0));
assert!(ivl.contains(2.0e5));
assert!(ivl.contains(3.5e6));
assert!(!ivl.contains(2.5));
assert!(!ivl.contains(-1e5));
assert!(!ivl.contains(f32::NAN));
}
#[test]
fn interval_containment() {
let ivl = Interval::UNIT;
assert!(ivl.contains_interval(interval(-0.0, 0.5).unwrap()));
assert!(ivl.contains_interval(interval(0.5, 1.0).unwrap()));
assert!(ivl.contains_interval(interval(0.25, 0.75).unwrap()));
assert!(!ivl.contains_interval(interval(-0.25, 0.5).unwrap()));
assert!(!ivl.contains_interval(interval(0.5, 1.25).unwrap()));
assert!(!ivl.contains_interval(interval(0.25, f32::INFINITY).unwrap()));
assert!(!ivl.contains_interval(interval(f32::NEG_INFINITY, 0.75).unwrap()));
let big_ivl = interval(0.0, f32::INFINITY).unwrap();
assert!(big_ivl.contains_interval(interval(0.0, 5.0).unwrap()));
assert!(big_ivl.contains_interval(interval(0.0, f32::INFINITY).unwrap()));
assert!(big_ivl.contains_interval(interval(1.0, 5.0).unwrap()));
assert!(!big_ivl.contains_interval(interval(-1.0, f32::INFINITY).unwrap()));
assert!(!big_ivl.contains_interval(interval(-2.0, 5.0).unwrap()));
}
#[test]
fn boundedness() {
assert!(!Interval::EVERYWHERE.is_bounded());
assert!(interval(0.0, 3.5e5).unwrap().is_bounded());
assert!(!interval(-2.0, f32::INFINITY).unwrap().is_bounded());
assert!(!interval(f32::NEG_INFINITY, 5.0).unwrap().is_bounded());
}
#[test]
fn linear_maps() {
let ivl1 = interval(-3.0, 5.0).unwrap();
let ivl2 = Interval::UNIT;
let map = ivl1.linear_map_to(ivl2);
assert!(map.is_ok_and(|f| f(-3.0).abs_diff_eq(&0.0, f32::EPSILON)
&& f(5.0).abs_diff_eq(&1.0, f32::EPSILON)
&& f(1.0).abs_diff_eq(&0.5, f32::EPSILON)));
let ivl1 = Interval::UNIT;
let ivl2 = Interval::EVERYWHERE;
assert!(ivl1.linear_map_to(ivl2).is_err());
let ivl1 = interval(f32::NEG_INFINITY, -4.0).unwrap();
let ivl2 = Interval::UNIT;
assert!(ivl1.linear_map_to(ivl2).is_err());
}
#[test]
fn spaced_points() {
let ivl = interval(0.0, 50.0).unwrap();
let points_iter: Vec<f32> = ivl.spaced_points(1).unwrap().collect();
assert_abs_diff_eq!(points_iter[0], 0.0);
assert_eq!(points_iter.len(), 1);
let points_iter: Vec<f32> = ivl.spaced_points(2).unwrap().collect();
assert_abs_diff_eq!(points_iter[0], 0.0);
assert_abs_diff_eq!(points_iter[1], 50.0);
let points_iter = ivl.spaced_points(21).unwrap();
let step = ivl.length() / 20.0;
for (index, point) in points_iter.enumerate() {
let expected = ivl.start() + step * index as f32;
assert_abs_diff_eq!(point, expected);
}
let ivl = interval(-21.0, 79.0).unwrap();
let points_iter = ivl.spaced_points(10000).unwrap();
let step = ivl.length() / 9999.0;
for (index, point) in points_iter.enumerate() {
let expected = ivl.start() + step * index as f32;
assert_abs_diff_eq!(point, expected);
}
let ivl = interval(-1.0, f32::INFINITY).unwrap();
let points_iter = ivl.spaced_points(25);
assert!(points_iter.is_err());
let ivl = interval(f32::NEG_INFINITY, -25.0).unwrap();
let points_iter = ivl.spaced_points(9);
assert!(points_iter.is_err());
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/curve/adaptors.rs | crates/bevy_math/src/curve/adaptors.rs | //! Adaptors used by the Curve API for transforming and combining curves together.
use super::interval::*;
use super::Curve;
use crate::ops;
use crate::VectorSpace;
use core::any::type_name;
use core::fmt::{self, Debug};
use core::marker::PhantomData;
#[cfg(feature = "bevy_reflect")]
use {
alloc::format,
bevy_reflect::{utility::GenericTypePathCell, FromReflect, Reflect, TypePath},
};
#[cfg(feature = "bevy_reflect")]
mod paths {
pub(super) const THIS_MODULE: &str = "bevy_math::curve::adaptors";
pub(super) const THIS_CRATE: &str = "bevy_math";
}
#[expect(unused, reason = "imported just for doc links")]
use super::CurveExt;
// NOTE ON REFLECTION:
//
// Function members of structs pose an obstacle for reflection, because they don't implement
// reflection traits themselves. Some of these are more problematic than others; for example,
// `FromReflect` is basically hopeless for function members regardless, so function-containing
// adaptors will just never be `FromReflect` (at least until function item types implement
// Default, if that ever happens). Similarly, they do not implement `TypePath`, and as a result,
// those adaptors also need custom `TypePath` adaptors which use `type_name` instead.
//
// The sum total weirdness of the `Reflect` implementations amounts to this; those adaptors:
// - are currently never `FromReflect`;
// - have custom `TypePath` implementations which are not fully stable;
// - have custom `Debug` implementations which display the function only by type name.
/// A curve with a constant value over its domain.
///
/// This is a curve that holds an inner value and always produces a clone of that value when sampled.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
pub struct ConstantCurve<T> {
pub(crate) domain: Interval,
pub(crate) value: T,
}
impl<T> ConstantCurve<T>
where
T: Clone,
{
/// Create a constant curve, which has the given `domain` and always produces the given `value`
/// when sampled.
pub fn new(domain: Interval, value: T) -> Self {
Self { domain, value }
}
}
impl<T> Curve<T> for ConstantCurve<T>
where
T: Clone,
{
#[inline]
fn domain(&self) -> Interval {
self.domain
}
#[inline]
fn sample_unchecked(&self, _t: f32) -> T {
self.value.clone()
}
}
/// A curve defined by a function together with a fixed domain.
///
/// This is a curve that holds an inner function `f` which takes numbers (`f32`) as input and produces
/// output of type `T`. The value of this curve when sampled at time `t` is just `f(t)`.
#[derive(Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(where T: TypePath),
reflect(from_reflect = false, type_path = false),
)]
pub struct FunctionCurve<T, F> {
pub(crate) domain: Interval,
#[cfg_attr(feature = "bevy_reflect", reflect(ignore))]
pub(crate) f: F,
#[cfg_attr(feature = "serialize", serde(skip))]
#[cfg_attr(feature = "bevy_reflect", reflect(ignore, clone))]
pub(crate) _phantom: PhantomData<fn() -> T>,
}
impl<T, F> Debug for FunctionCurve<T, F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FunctionCurve")
.field("domain", &self.domain)
.field("f", &type_name::<F>())
.finish()
}
}
/// Note: This is not a fully stable implementation of `TypePath` due to usage of `type_name`
/// for function members.
#[cfg(feature = "bevy_reflect")]
impl<T, F> TypePath for FunctionCurve<T, F>
where
T: TypePath,
F: 'static,
{
fn type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| {
format!(
"{}::FunctionCurve<{},{}>",
paths::THIS_MODULE,
T::type_path(),
type_name::<F>()
)
})
}
fn short_type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| {
format!(
"FunctionCurve<{},{}>",
T::short_type_path(),
type_name::<F>()
)
})
}
fn type_ident() -> Option<&'static str> {
Some("FunctionCurve")
}
fn crate_name() -> Option<&'static str> {
Some(paths::THIS_CRATE)
}
fn module_path() -> Option<&'static str> {
Some(paths::THIS_MODULE)
}
}
impl<T, F> FunctionCurve<T, F>
where
F: Fn(f32) -> T,
{
/// Create a new curve with the given `domain` from the given `function`. When sampled, the
/// `function` is evaluated at the sample time to compute the output.
pub fn new(domain: Interval, function: F) -> Self {
FunctionCurve {
domain,
f: function,
_phantom: PhantomData,
}
}
}
impl<T, F> Curve<T> for FunctionCurve<T, F>
where
F: Fn(f32) -> T,
{
#[inline]
fn domain(&self) -> Interval {
self.domain
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
(self.f)(t)
}
}
/// A curve whose samples are defined by mapping samples from another curve through a
/// given function. Curves of this type are produced by [`CurveExt::map`].
#[derive(Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(where S: TypePath, T: TypePath, C: TypePath),
reflect(from_reflect = false, type_path = false),
)]
pub struct MapCurve<S, T, C, F> {
pub(crate) preimage: C,
#[cfg_attr(feature = "bevy_reflect", reflect(ignore))]
pub(crate) f: F,
#[cfg_attr(feature = "serialize", serde(skip))]
#[cfg_attr(feature = "bevy_reflect", reflect(ignore, clone))]
pub(crate) _phantom: PhantomData<(fn() -> S, fn(S) -> T)>,
}
impl<S, T, C, F> Debug for MapCurve<S, T, C, F>
where
C: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MapCurve")
.field("preimage", &self.preimage)
.field("f", &type_name::<F>())
.finish()
}
}
/// Note: This is not a fully stable implementation of `TypePath` due to usage of `type_name`
/// for function members.
#[cfg(feature = "bevy_reflect")]
impl<S, T, C, F> TypePath for MapCurve<S, T, C, F>
where
S: TypePath,
T: TypePath,
C: TypePath,
F: 'static,
{
fn type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| {
format!(
"{}::MapCurve<{},{},{},{}>",
paths::THIS_MODULE,
S::type_path(),
T::type_path(),
C::type_path(),
type_name::<F>()
)
})
}
fn short_type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| {
format!(
"MapCurve<{},{},{},{}>",
S::type_path(),
T::type_path(),
C::type_path(),
type_name::<F>()
)
})
}
fn type_ident() -> Option<&'static str> {
Some("MapCurve")
}
fn crate_name() -> Option<&'static str> {
Some(paths::THIS_CRATE)
}
fn module_path() -> Option<&'static str> {
Some(paths::THIS_MODULE)
}
}
impl<S, T, C, F> Curve<T> for MapCurve<S, T, C, F>
where
C: Curve<S>,
F: Fn(S) -> T,
{
#[inline]
fn domain(&self) -> Interval {
self.preimage.domain()
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
(self.f)(self.preimage.sample_unchecked(t))
}
}
/// A curve whose sample space is mapped onto that of some base curve's before sampling.
/// Curves of this type are produced by [`CurveExt::reparametrize`].
#[derive(Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(where T: TypePath, C: TypePath),
reflect(from_reflect = false, type_path = false),
)]
pub struct ReparamCurve<T, C, F> {
pub(crate) domain: Interval,
pub(crate) base: C,
#[cfg_attr(feature = "bevy_reflect", reflect(ignore))]
pub(crate) f: F,
#[cfg_attr(feature = "serialize", serde(skip))]
#[cfg_attr(feature = "bevy_reflect", reflect(ignore, clone))]
pub(crate) _phantom: PhantomData<fn() -> T>,
}
impl<T, C, F> Debug for ReparamCurve<T, C, F>
where
C: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ReparamCurve")
.field("domain", &self.domain)
.field("base", &self.base)
.field("f", &type_name::<F>())
.finish()
}
}
/// Note: This is not a fully stable implementation of `TypePath` due to usage of `type_name`
/// for function members.
#[cfg(feature = "bevy_reflect")]
impl<T, C, F> TypePath for ReparamCurve<T, C, F>
where
T: TypePath,
C: TypePath,
F: 'static,
{
fn type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| {
format!(
"{}::ReparamCurve<{},{},{}>",
paths::THIS_MODULE,
T::type_path(),
C::type_path(),
type_name::<F>()
)
})
}
fn short_type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| {
format!(
"ReparamCurve<{},{},{}>",
T::type_path(),
C::type_path(),
type_name::<F>()
)
})
}
fn type_ident() -> Option<&'static str> {
Some("ReparamCurve")
}
fn crate_name() -> Option<&'static str> {
Some(paths::THIS_CRATE)
}
fn module_path() -> Option<&'static str> {
Some(paths::THIS_MODULE)
}
}
impl<T, C, F> Curve<T> for ReparamCurve<T, C, F>
where
C: Curve<T>,
F: Fn(f32) -> f32,
{
#[inline]
fn domain(&self) -> Interval {
self.domain
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
self.base.sample_unchecked((self.f)(t))
}
}
/// A curve that has had its domain changed by a linear reparameterization (stretching and scaling).
/// Curves of this type are produced by [`CurveExt::reparametrize_linear`].
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect, FromReflect),
reflect(from_reflect = false)
)]
pub struct LinearReparamCurve<T, C> {
/// Invariants: The domain of this curve must always be bounded.
pub(crate) base: C,
/// Invariants: This interval must always be bounded.
pub(crate) new_domain: Interval,
#[cfg_attr(feature = "serialize", serde(skip))]
#[cfg_attr(feature = "bevy_reflect", reflect(ignore, clone))]
pub(crate) _phantom: PhantomData<fn() -> T>,
}
impl<T, C> Curve<T> for LinearReparamCurve<T, C>
where
C: Curve<T>,
{
#[inline]
fn domain(&self) -> Interval {
self.new_domain
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
// The invariants imply this unwrap always succeeds.
let f = self.new_domain.linear_map_to(self.base.domain()).unwrap();
self.base.sample_unchecked(f(t))
}
}
/// A curve that has been reparametrized by another curve, using that curve to transform the
/// sample times before sampling. Curves of this type are produced by [`CurveExt::reparametrize_by_curve`].
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect, FromReflect),
reflect(from_reflect = false)
)]
pub struct CurveReparamCurve<T, C, D> {
pub(crate) base: C,
pub(crate) reparam_curve: D,
#[cfg_attr(feature = "serialize", serde(skip))]
#[cfg_attr(feature = "bevy_reflect", reflect(ignore, clone))]
pub(crate) _phantom: PhantomData<fn() -> T>,
}
impl<T, C, D> Curve<T> for CurveReparamCurve<T, C, D>
where
C: Curve<T>,
D: Curve<f32>,
{
#[inline]
fn domain(&self) -> Interval {
self.reparam_curve.domain()
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
let sample_time = self.reparam_curve.sample_unchecked(t);
self.base.sample_unchecked(sample_time)
}
}
/// A curve that is the graph of another curve over its parameter space. Curves of this type are
/// produced by [`CurveExt::graph`].
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect, FromReflect),
reflect(from_reflect = false)
)]
pub struct GraphCurve<T, C> {
pub(crate) base: C,
#[cfg_attr(feature = "serialize", serde(skip))]
#[cfg_attr(feature = "bevy_reflect", reflect(ignore, clone))]
pub(crate) _phantom: PhantomData<fn() -> T>,
}
impl<T, C> Curve<(f32, T)> for GraphCurve<T, C>
where
C: Curve<T>,
{
#[inline]
fn domain(&self) -> Interval {
self.base.domain()
}
#[inline]
fn sample_unchecked(&self, t: f32) -> (f32, T) {
(t, self.base.sample_unchecked(t))
}
}
/// A curve that combines the output data from two constituent curves into a tuple output. Curves
/// of this type are produced by [`CurveExt::zip`].
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect, FromReflect),
reflect(from_reflect = false)
)]
pub struct ZipCurve<S, T, C, D> {
pub(crate) domain: Interval,
pub(crate) first: C,
pub(crate) second: D,
#[cfg_attr(feature = "serialize", serde(skip))]
#[cfg_attr(feature = "bevy_reflect", reflect(ignore, clone))]
pub(crate) _phantom: PhantomData<fn() -> (S, T)>,
}
impl<S, T, C, D> Curve<(S, T)> for ZipCurve<S, T, C, D>
where
C: Curve<S>,
D: Curve<T>,
{
#[inline]
fn domain(&self) -> Interval {
self.domain
}
#[inline]
fn sample_unchecked(&self, t: f32) -> (S, T) {
(
self.first.sample_unchecked(t),
self.second.sample_unchecked(t),
)
}
}
/// The curve that results from chaining one curve with another. The second curve is
/// effectively reparametrized so that its start is at the end of the first.
///
/// For this to be well-formed, the first curve's domain must be right-finite and the second's
/// must be left-finite.
///
/// Curves of this type are produced by [`CurveExt::chain`].
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect, FromReflect),
reflect(from_reflect = false)
)]
pub struct ChainCurve<T, C, D> {
pub(crate) first: C,
pub(crate) second: D,
#[cfg_attr(feature = "serialize", serde(skip))]
#[cfg_attr(feature = "bevy_reflect", reflect(ignore, clone))]
pub(crate) _phantom: PhantomData<fn() -> T>,
}
impl<T, C, D> Curve<T> for ChainCurve<T, C, D>
where
C: Curve<T>,
D: Curve<T>,
{
#[inline]
fn domain(&self) -> Interval {
// This unwrap always succeeds because `first` has a valid Interval as its domain and the
// length of `second` cannot be NAN. It's still fine if it's infinity.
Interval::new(
self.first.domain().start(),
self.first.domain().end() + self.second.domain().length(),
)
.unwrap()
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
if t > self.first.domain().end() {
self.second.sample_unchecked(
// `t - first.domain.end` computes the offset into the domain of the second.
t - self.first.domain().end() + self.second.domain().start(),
)
} else {
self.first.sample_unchecked(t)
}
}
}
/// The curve that results from reversing another.
///
/// Curves of this type are produced by [`CurveExt::reverse`].
///
/// # Domain
///
/// The original curve's domain must be bounded to get a valid [`ReverseCurve`].
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect, FromReflect),
reflect(from_reflect = false)
)]
pub struct ReverseCurve<T, C> {
pub(crate) curve: C,
#[cfg_attr(feature = "serialize", serde(skip))]
#[cfg_attr(feature = "bevy_reflect", reflect(ignore, clone))]
pub(crate) _phantom: PhantomData<fn() -> T>,
}
impl<T, C> Curve<T> for ReverseCurve<T, C>
where
C: Curve<T>,
{
#[inline]
fn domain(&self) -> Interval {
self.curve.domain()
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
self.curve
.sample_unchecked(self.domain().end() - (t - self.domain().start()))
}
}
/// The curve that results from repeating a curve `N` times.
///
/// # Notes
///
/// - the value at the transitioning points (`domain.end() * n` for `n >= 1`) in the results is the
/// value at `domain.end()` in the original curve
///
/// Curves of this type are produced by [`CurveExt::repeat`].
///
/// # Domain
///
/// The original curve's domain must be bounded to get a valid [`RepeatCurve`].
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect, FromReflect),
reflect(from_reflect = false)
)]
pub struct RepeatCurve<T, C> {
pub(crate) domain: Interval,
pub(crate) curve: C,
#[cfg_attr(feature = "serialize", serde(skip))]
#[cfg_attr(feature = "bevy_reflect", reflect(ignore, clone))]
pub(crate) _phantom: PhantomData<fn() -> T>,
}
impl<T, C> Curve<T> for RepeatCurve<T, C>
where
C: Curve<T>,
{
#[inline]
fn domain(&self) -> Interval {
self.domain
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
let t = self.base_curve_sample_time(t);
self.curve.sample_unchecked(t)
}
}
impl<T, C> RepeatCurve<T, C>
where
C: Curve<T>,
{
#[inline]
pub(crate) fn base_curve_sample_time(&self, t: f32) -> f32 {
// the domain is bounded by construction
let d = self.curve.domain();
let cyclic_t = ops::rem_euclid(t - d.start(), d.length());
if t != d.start() && cyclic_t == 0.0 {
d.end()
} else {
d.start() + cyclic_t
}
}
}
/// The curve that results from repeating a curve forever.
///
/// # Notes
///
/// - the value at the transitioning points (`domain.end() * n` for `n >= 1`) in the results is the
/// value at `domain.end()` in the original curve
///
/// Curves of this type are produced by [`CurveExt::forever`].
///
/// # Domain
///
/// The original curve's domain must be bounded to get a valid [`ForeverCurve`].
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect, FromReflect),
reflect(from_reflect = false)
)]
pub struct ForeverCurve<T, C> {
pub(crate) curve: C,
#[cfg_attr(feature = "serialize", serde(skip))]
#[cfg_attr(feature = "bevy_reflect", reflect(ignore, clone))]
pub(crate) _phantom: PhantomData<fn() -> T>,
}
impl<T, C> Curve<T> for ForeverCurve<T, C>
where
C: Curve<T>,
{
#[inline]
fn domain(&self) -> Interval {
Interval::EVERYWHERE
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
let t = self.base_curve_sample_time(t);
self.curve.sample_unchecked(t)
}
}
impl<T, C> ForeverCurve<T, C>
where
C: Curve<T>,
{
#[inline]
pub(crate) fn base_curve_sample_time(&self, t: f32) -> f32 {
// the domain is bounded by construction
let d = self.curve.domain();
let cyclic_t = ops::rem_euclid(t - d.start(), d.length());
if t != d.start() && cyclic_t == 0.0 {
d.end()
} else {
d.start() + cyclic_t
}
}
}
/// The curve that results from chaining a curve with its reversed version. The transition point
/// is guaranteed to make no jump.
///
/// Curves of this type are produced by [`CurveExt::ping_pong`].
///
/// # Domain
///
/// The original curve's domain must be right-finite to get a valid [`PingPongCurve`].
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect, FromReflect),
reflect(from_reflect = false)
)]
pub struct PingPongCurve<T, C> {
pub(crate) curve: C,
#[cfg_attr(feature = "serialize", serde(skip))]
#[cfg_attr(feature = "bevy_reflect", reflect(ignore, clone))]
pub(crate) _phantom: PhantomData<fn() -> T>,
}
impl<T, C> Curve<T> for PingPongCurve<T, C>
where
C: Curve<T>,
{
#[inline]
fn domain(&self) -> Interval {
// This unwrap always succeeds because `curve` has a valid Interval as its domain and the
// length of `curve` cannot be NAN. It's still fine if it's infinity.
Interval::new(
self.curve.domain().start(),
self.curve.domain().end() + self.curve.domain().length(),
)
.unwrap()
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
// the domain is bounded by construction
let final_t = if t > self.curve.domain().end() {
self.curve.domain().end() * 2.0 - t
} else {
t
};
self.curve.sample_unchecked(final_t)
}
}
/// The curve that results from chaining two curves.
///
/// Additionally the transition of the samples is guaranteed to not make sudden jumps. This is
/// useful if you really just know about the shapes of your curves and don't want to deal with
/// stitching them together properly when it would just introduce useless complexity. It is
/// realized by translating the second curve so that its start sample point coincides with the
/// first curves' end sample point.
///
/// Curves of this type are produced by [`CurveExt::chain_continue`].
///
/// # Domain
///
/// The first curve's domain must be right-finite and the second's must be left-finite to get a
/// valid [`ContinuationCurve`].
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect, FromReflect),
reflect(from_reflect = false)
)]
pub struct ContinuationCurve<T, C, D> {
pub(crate) first: C,
pub(crate) second: D,
// cache the offset in the curve directly to prevent triple sampling for every sample we make
pub(crate) offset: T,
#[cfg_attr(feature = "serialize", serde(skip))]
#[cfg_attr(feature = "bevy_reflect", reflect(ignore, clone))]
pub(crate) _phantom: PhantomData<fn() -> T>,
}
impl<T, C, D> Curve<T> for ContinuationCurve<T, C, D>
where
T: VectorSpace,
C: Curve<T>,
D: Curve<T>,
{
#[inline]
fn domain(&self) -> Interval {
// This unwrap always succeeds because `curve` has a valid Interval as its domain and the
// length of `curve` cannot be NAN. It's still fine if it's infinity.
Interval::new(
self.first.domain().start(),
self.first.domain().end() + self.second.domain().length(),
)
.unwrap()
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
if t > self.first.domain().end() {
self.second.sample_unchecked(
// `t - first.domain.end` computes the offset into the domain of the second.
t - self.first.domain().end() + self.second.domain().start(),
) + self.offset
} else {
self.first.sample_unchecked(t)
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/curve/derivatives/adaptor_impls.rs | crates/bevy_math/src/curve/derivatives/adaptor_impls.rs | //! Implementations of derivatives on curve adaptors. These allow
//! compositionality for derivatives.
use super::{SampleDerivative, SampleTwoDerivatives};
use crate::common_traits::{HasTangent, Sum, VectorSpace, WithDerivative, WithTwoDerivatives};
use crate::curve::{
adaptors::{
ChainCurve, ConstantCurve, ContinuationCurve, CurveReparamCurve, ForeverCurve, GraphCurve,
LinearReparamCurve, PingPongCurve, RepeatCurve, ReverseCurve, ZipCurve,
},
Curve,
};
// -- ConstantCurve
impl<T> SampleDerivative<T> for ConstantCurve<T>
where
T: HasTangent + Clone,
{
fn sample_with_derivative_unchecked(&self, _t: f32) -> WithDerivative<T> {
WithDerivative {
value: self.value.clone(),
derivative: VectorSpace::ZERO,
}
}
}
impl<T> SampleTwoDerivatives<T> for ConstantCurve<T>
where
T: HasTangent + Clone,
{
fn sample_with_two_derivatives_unchecked(&self, _t: f32) -> WithTwoDerivatives<T> {
WithTwoDerivatives {
value: self.value.clone(),
derivative: VectorSpace::ZERO,
second_derivative: VectorSpace::ZERO,
}
}
}
// -- ChainCurve
impl<T, C, D> SampleDerivative<T> for ChainCurve<T, C, D>
where
T: HasTangent,
C: SampleDerivative<T>,
D: SampleDerivative<T>,
{
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<T> {
if t > self.first.domain().end() {
self.second.sample_with_derivative_unchecked(
// `t - first.domain.end` computes the offset into the domain of the second.
t - self.first.domain().end() + self.second.domain().start(),
)
} else {
self.first.sample_with_derivative_unchecked(t)
}
}
}
impl<T, C, D> SampleTwoDerivatives<T> for ChainCurve<T, C, D>
where
T: HasTangent,
C: SampleTwoDerivatives<T>,
D: SampleTwoDerivatives<T>,
{
fn sample_with_two_derivatives_unchecked(&self, t: f32) -> WithTwoDerivatives<T> {
if t > self.first.domain().end() {
self.second.sample_with_two_derivatives_unchecked(
// `t - first.domain.end` computes the offset into the domain of the second.
t - self.first.domain().end() + self.second.domain().start(),
)
} else {
self.first.sample_with_two_derivatives_unchecked(t)
}
}
}
// -- ContinuationCurve
impl<T, C, D> SampleDerivative<T> for ContinuationCurve<T, C, D>
where
T: VectorSpace,
C: SampleDerivative<T>,
D: SampleDerivative<T>,
{
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<T> {
if t > self.first.domain().end() {
let mut output = self.second.sample_with_derivative_unchecked(
// `t - first.domain.end` computes the offset into the domain of the second.
t - self.first.domain().end() + self.second.domain().start(),
);
output.value = output.value + self.offset;
output
} else {
self.first.sample_with_derivative_unchecked(t)
}
}
}
impl<T, C, D> SampleTwoDerivatives<T> for ContinuationCurve<T, C, D>
where
T: VectorSpace,
C: SampleTwoDerivatives<T>,
D: SampleTwoDerivatives<T>,
{
fn sample_with_two_derivatives_unchecked(&self, t: f32) -> WithTwoDerivatives<T> {
if t > self.first.domain().end() {
let mut output = self.second.sample_with_two_derivatives_unchecked(
// `t - first.domain.end` computes the offset into the domain of the second.
t - self.first.domain().end() + self.second.domain().start(),
);
output.value = output.value + self.offset;
output
} else {
self.first.sample_with_two_derivatives_unchecked(t)
}
}
}
// -- RepeatCurve
impl<T, C> SampleDerivative<T> for RepeatCurve<T, C>
where
T: HasTangent,
C: SampleDerivative<T>,
{
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<T> {
let t = self.base_curve_sample_time(t);
self.curve.sample_with_derivative_unchecked(t)
}
}
impl<T, C> SampleTwoDerivatives<T> for RepeatCurve<T, C>
where
T: HasTangent,
C: SampleTwoDerivatives<T>,
{
fn sample_with_two_derivatives_unchecked(&self, t: f32) -> WithTwoDerivatives<T> {
let t = self.base_curve_sample_time(t);
self.curve.sample_with_two_derivatives_unchecked(t)
}
}
// -- ForeverCurve
impl<T, C> SampleDerivative<T> for ForeverCurve<T, C>
where
T: HasTangent,
C: SampleDerivative<T>,
{
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<T> {
let t = self.base_curve_sample_time(t);
self.curve.sample_with_derivative_unchecked(t)
}
}
impl<T, C> SampleTwoDerivatives<T> for ForeverCurve<T, C>
where
T: HasTangent,
C: SampleTwoDerivatives<T>,
{
fn sample_with_two_derivatives_unchecked(&self, t: f32) -> WithTwoDerivatives<T> {
let t = self.base_curve_sample_time(t);
self.curve.sample_with_two_derivatives_unchecked(t)
}
}
// -- PingPongCurve
impl<T, C> SampleDerivative<T> for PingPongCurve<T, C>
where
T: HasTangent,
C: SampleDerivative<T>,
{
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<T> {
if t > self.curve.domain().end() {
let t = self.curve.domain().end() * 2.0 - t;
// The derivative of the preceding expression is -1, so the chain
// rule implies the derivative should be negated.
let mut output = self.curve.sample_with_derivative_unchecked(t);
output.derivative = -output.derivative;
output
} else {
self.curve.sample_with_derivative_unchecked(t)
}
}
}
impl<T, C> SampleTwoDerivatives<T> for PingPongCurve<T, C>
where
T: HasTangent,
C: SampleTwoDerivatives<T>,
{
fn sample_with_two_derivatives_unchecked(&self, t: f32) -> WithTwoDerivatives<T> {
if t > self.curve.domain().end() {
let t = self.curve.domain().end() * 2.0 - t;
// See the implementation on `ReverseCurve` for an explanation of
// why this is correct.
let mut output = self.curve.sample_with_two_derivatives_unchecked(t);
output.derivative = -output.derivative;
output
} else {
self.curve.sample_with_two_derivatives_unchecked(t)
}
}
}
// -- ZipCurve
impl<U, V, S, T, C, D> SampleDerivative<(S, T)> for ZipCurve<S, T, C, D>
where
U: VectorSpace<Scalar = f32>,
V: VectorSpace<Scalar = f32>,
S: HasTangent<Tangent = U>,
T: HasTangent<Tangent = V>,
C: SampleDerivative<S>,
D: SampleDerivative<T>,
{
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<(S, T)> {
let first_output = self.first.sample_with_derivative_unchecked(t);
let second_output = self.second.sample_with_derivative_unchecked(t);
WithDerivative {
value: (first_output.value, second_output.value),
derivative: Sum(first_output.derivative, second_output.derivative),
}
}
}
impl<U, V, S, T, C, D> SampleTwoDerivatives<(S, T)> for ZipCurve<S, T, C, D>
where
U: VectorSpace<Scalar = f32>,
V: VectorSpace<Scalar = f32>,
S: HasTangent<Tangent = U>,
T: HasTangent<Tangent = V>,
C: SampleTwoDerivatives<S>,
D: SampleTwoDerivatives<T>,
{
fn sample_with_two_derivatives_unchecked(&self, t: f32) -> WithTwoDerivatives<(S, T)> {
let first_output = self.first.sample_with_two_derivatives_unchecked(t);
let second_output = self.second.sample_with_two_derivatives_unchecked(t);
WithTwoDerivatives {
value: (first_output.value, second_output.value),
derivative: Sum(first_output.derivative, second_output.derivative),
second_derivative: Sum(
first_output.second_derivative,
second_output.second_derivative,
),
}
}
}
// -- GraphCurve
impl<V, T, C> SampleDerivative<(f32, T)> for GraphCurve<T, C>
where
V: VectorSpace<Scalar = f32>,
T: HasTangent<Tangent = V>,
C: SampleDerivative<T>,
{
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<(f32, T)> {
let output = self.base.sample_with_derivative_unchecked(t);
WithDerivative {
value: (t, output.value),
derivative: Sum(1.0, output.derivative),
}
}
}
impl<V, T, C> SampleTwoDerivatives<(f32, T)> for GraphCurve<T, C>
where
V: VectorSpace<Scalar = f32>,
T: HasTangent<Tangent = V>,
C: SampleTwoDerivatives<T>,
{
fn sample_with_two_derivatives_unchecked(&self, t: f32) -> WithTwoDerivatives<(f32, T)> {
let output = self.base.sample_with_two_derivatives_unchecked(t);
WithTwoDerivatives {
value: (t, output.value),
derivative: Sum(1.0, output.derivative),
second_derivative: Sum(0.0, output.second_derivative),
}
}
}
// -- ReverseCurve
impl<T, C> SampleDerivative<T> for ReverseCurve<T, C>
where
T: HasTangent,
C: SampleDerivative<T>,
{
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<T> {
// This gets almost the correct value, but we haven't accounted for the
// reversal of orientation yet.
let mut output = self
.curve
.sample_with_derivative_unchecked(self.domain().end() - (t - self.domain().start()));
output.derivative = -output.derivative;
output
}
}
impl<T, C> SampleTwoDerivatives<T> for ReverseCurve<T, C>
where
T: HasTangent,
C: SampleTwoDerivatives<T>,
{
fn sample_with_two_derivatives_unchecked(&self, t: f32) -> WithTwoDerivatives<T> {
// This gets almost the correct value, but we haven't accounted for the
// reversal of orientation yet.
let mut output = self.curve.sample_with_two_derivatives_unchecked(
self.domain().end() - (t - self.domain().start()),
);
output.derivative = -output.derivative;
// (Note that the reparametrization that reverses the curve satisfies
// g'(t)^2 = 1 and g''(t) = 0, so the second derivative is already
// correct.)
output
}
}
// -- CurveReparamCurve
impl<V, T, C, D> SampleDerivative<T> for CurveReparamCurve<T, C, D>
where
V: VectorSpace<Scalar = f32>,
T: HasTangent<Tangent = V>,
C: SampleDerivative<T>,
D: SampleDerivative<f32>,
{
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<T> {
// This curve is r(t) = f(g(t)), where f(t) is `self.base` and g(t)
// is `self.reparam_curve`.
// Start by computing g(t) and g'(t).
let reparam_output = self.reparam_curve.sample_with_derivative_unchecked(t);
// Compute:
// - value: f(g(t))
// - derivative: f'(g(t))
let mut output = self
.base
.sample_with_derivative_unchecked(reparam_output.value);
// Do the multiplication part of the chain rule.
output.derivative = output.derivative * reparam_output.derivative;
// value: f(g(t)), derivative: f'(g(t)) g'(t)
output
}
}
impl<V, T, C, D> SampleTwoDerivatives<T> for CurveReparamCurve<T, C, D>
where
V: VectorSpace<Scalar = f32>,
T: HasTangent<Tangent = V>,
C: SampleTwoDerivatives<T>,
D: SampleTwoDerivatives<f32>,
{
fn sample_with_two_derivatives_unchecked(&self, t: f32) -> WithTwoDerivatives<T> {
// This curve is r(t) = f(g(t)), where f(t) is `self.base` and g(t)
// is `self.reparam_curve`.
// Start by computing g(t), g'(t), g''(t).
let reparam_output = self.reparam_curve.sample_with_two_derivatives_unchecked(t);
// Compute:
// - value: f(g(t))
// - derivative: f'(g(t))
// - second derivative: f''(g(t))
let mut output = self
.base
.sample_with_two_derivatives_unchecked(reparam_output.value);
// Set the second derivative according to the chain and product rules
// r''(t) = f''(g(t)) g'(t)^2 + f'(g(t)) g''(t)
output.second_derivative = (output.second_derivative
* (reparam_output.derivative * reparam_output.derivative))
+ (output.derivative * reparam_output.second_derivative);
// Set the first derivative according to the chain rule
// r'(t) = f'(g(t)) g'(t)
output.derivative = output.derivative * reparam_output.derivative;
output
}
}
// -- LinearReparamCurve
impl<V, T, C> SampleDerivative<T> for LinearReparamCurve<T, C>
where
V: VectorSpace<Scalar = f32>,
T: HasTangent<Tangent = V>,
C: SampleDerivative<T>,
{
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<T> {
// This curve is r(t) = f(g(t)), where f(t) is `self.base` and g(t) is
// the linear map bijecting `self.new_domain` onto `self.base.domain()`.
// The invariants imply this unwrap always succeeds.
let g = self.new_domain.linear_map_to(self.base.domain()).unwrap();
// Compute g'(t) from the domain lengths.
let g_derivative = self.base.domain().length() / self.new_domain.length();
// Compute:
// - value: f(g(t))
// - derivative: f'(g(t))
let mut output = self.base.sample_with_derivative_unchecked(g(t));
// Adjust the derivative according to the chain rule.
output.derivative = output.derivative * g_derivative;
output
}
}
impl<V, T, C> SampleTwoDerivatives<T> for LinearReparamCurve<T, C>
where
V: VectorSpace<Scalar = f32>,
T: HasTangent<Tangent = V>,
C: SampleTwoDerivatives<T>,
{
fn sample_with_two_derivatives_unchecked(&self, t: f32) -> WithTwoDerivatives<T> {
// This curve is r(t) = f(g(t)), where f(t) is `self.base` and g(t) is
// the linear map bijecting `self.new_domain` onto `self.base.domain()`.
// The invariants imply this unwrap always succeeds.
let g = self.new_domain.linear_map_to(self.base.domain()).unwrap();
// Compute g'(t) from the domain lengths.
let g_derivative = self.base.domain().length() / self.new_domain.length();
// Compute:
// - value: f(g(t))
// - derivative: f'(g(t))
// - second derivative: f''(g(t))
let mut output = self.base.sample_with_two_derivatives_unchecked(g(t));
// Set the second derivative according to the chain and product rules
// r''(t) = f''(g(t)) g'(t)^2 (g''(t) = 0)
output.second_derivative = output.second_derivative * (g_derivative * g_derivative);
// Set the first derivative according to the chain rule
// r'(t) = f'(g(t)) g'(t)
output.derivative = output.derivative * g_derivative;
output
}
}
#[cfg(test)]
mod tests {
use approx::assert_abs_diff_eq;
use super::*;
use crate::cubic_splines::{CubicBezier, CubicCardinalSpline, CubicCurve, CubicGenerator};
use crate::curve::{Curve, CurveExt, Interval};
use crate::{vec2, Vec2, Vec3};
fn test_curve() -> CubicCurve<Vec2> {
let control_pts = [[
vec2(0.0, 0.0),
vec2(1.0, 0.0),
vec2(0.0, 1.0),
vec2(1.0, 1.0),
]];
CubicBezier::new(control_pts).to_curve().unwrap()
}
fn other_test_curve() -> CubicCurve<Vec2> {
let control_pts = [
vec2(1.0, 1.0),
vec2(2.0, 1.0),
vec2(2.0, 0.0),
vec2(1.0, 0.0),
];
CubicCardinalSpline::new(0.5, control_pts)
.to_curve()
.unwrap()
}
fn reparam_curve() -> CubicCurve<f32> {
let control_pts = [[0.0, 0.25, 0.75, 1.0]];
CubicBezier::new(control_pts).to_curve().unwrap()
}
#[test]
fn constant_curve() {
let curve = ConstantCurve::new(Interval::UNIT, Vec3::new(0.2, 1.5, -2.6));
let jet = curve.sample_with_derivative(0.5).unwrap();
assert_abs_diff_eq!(jet.derivative, Vec3::ZERO);
}
#[test]
fn chain_curve() {
let curve1 = test_curve();
let curve2 = other_test_curve();
let curve = curve1.by_ref().chain(&curve2).unwrap();
let jet = curve.sample_with_derivative(0.65).unwrap();
let true_jet = curve1.sample_with_derivative(0.65).unwrap();
assert_abs_diff_eq!(jet.value, true_jet.value);
assert_abs_diff_eq!(jet.derivative, true_jet.derivative);
let jet = curve.sample_with_derivative(1.1).unwrap();
let true_jet = curve2.sample_with_derivative(0.1).unwrap();
assert_abs_diff_eq!(jet.value, true_jet.value);
assert_abs_diff_eq!(jet.derivative, true_jet.derivative);
}
#[test]
fn continuation_curve() {
let curve1 = test_curve();
let curve2 = other_test_curve();
let curve = curve1.by_ref().chain_continue(&curve2).unwrap();
let jet = curve.sample_with_derivative(0.99).unwrap();
let true_jet = curve1.sample_with_derivative(0.99).unwrap();
assert_abs_diff_eq!(jet.value, true_jet.value);
assert_abs_diff_eq!(jet.derivative, true_jet.derivative);
let jet = curve.sample_with_derivative(1.3).unwrap();
let true_jet = curve2.sample_with_derivative(0.3).unwrap();
assert_abs_diff_eq!(jet.value, true_jet.value);
assert_abs_diff_eq!(jet.derivative, true_jet.derivative);
}
#[test]
fn repeat_curve() {
let curve1 = test_curve();
let curve = curve1.by_ref().repeat(3).unwrap();
let jet = curve.sample_with_derivative(0.73).unwrap();
let true_jet = curve1.sample_with_derivative(0.73).unwrap();
assert_abs_diff_eq!(jet.value, true_jet.value);
assert_abs_diff_eq!(jet.derivative, true_jet.derivative);
let jet = curve.sample_with_derivative(3.5).unwrap();
let true_jet = curve1.sample_with_derivative(0.5).unwrap();
assert_abs_diff_eq!(jet.value, true_jet.value);
assert_abs_diff_eq!(jet.derivative, true_jet.derivative);
}
#[test]
fn forever_curve() {
let curve1 = test_curve();
let curve = curve1.by_ref().forever().unwrap();
let jet = curve.sample_with_derivative(0.12).unwrap();
let true_jet = curve1.sample_with_derivative(0.12).unwrap();
assert_abs_diff_eq!(jet.value, true_jet.value);
assert_abs_diff_eq!(jet.derivative, true_jet.derivative);
let jet = curve.sample_with_derivative(500.5).unwrap();
let true_jet = curve1.sample_with_derivative(0.5).unwrap();
assert_abs_diff_eq!(jet.value, true_jet.value);
assert_abs_diff_eq!(jet.derivative, true_jet.derivative);
}
#[test]
fn ping_pong_curve() {
let curve1 = test_curve();
let curve = curve1.by_ref().ping_pong().unwrap();
let jet = curve.sample_with_derivative(0.99).unwrap();
let comparison_jet = curve1.sample_with_derivative(0.99).unwrap();
assert_abs_diff_eq!(jet.value, comparison_jet.value);
assert_abs_diff_eq!(jet.derivative, comparison_jet.derivative);
let jet = curve.sample_with_derivative(1.3).unwrap();
let comparison_jet = curve1.sample_with_derivative(0.7).unwrap();
assert_abs_diff_eq!(jet.value, comparison_jet.value);
assert_abs_diff_eq!(jet.derivative, -comparison_jet.derivative, epsilon = 1.0e-5);
}
#[test]
fn zip_curve() {
let curve1 = test_curve();
let curve2 = other_test_curve();
let curve = curve1.by_ref().zip(&curve2).unwrap();
let jet = curve.sample_with_derivative(0.7).unwrap();
let comparison_jet1 = curve1.sample_with_derivative(0.7).unwrap();
let comparison_jet2 = curve2.sample_with_derivative(0.7).unwrap();
assert_abs_diff_eq!(jet.value.0, comparison_jet1.value);
assert_abs_diff_eq!(jet.value.1, comparison_jet2.value);
let Sum(derivative1, derivative2) = jet.derivative;
assert_abs_diff_eq!(derivative1, comparison_jet1.derivative);
assert_abs_diff_eq!(derivative2, comparison_jet2.derivative);
}
#[test]
fn graph_curve() {
let curve1 = test_curve();
let curve = curve1.by_ref().graph();
let jet = curve.sample_with_derivative(0.25).unwrap();
let comparison_jet = curve1.sample_with_derivative(0.25).unwrap();
assert_abs_diff_eq!(jet.value.0, 0.25);
assert_abs_diff_eq!(jet.value.1, comparison_jet.value);
let Sum(one, derivative) = jet.derivative;
assert_abs_diff_eq!(one, 1.0);
assert_abs_diff_eq!(derivative, comparison_jet.derivative);
}
#[test]
fn reverse_curve() {
let curve1 = test_curve();
let curve = curve1.by_ref().reverse().unwrap();
let jet = curve.sample_with_derivative(0.23).unwrap();
let comparison_jet = curve1.sample_with_derivative(0.77).unwrap();
assert_abs_diff_eq!(jet.value, comparison_jet.value);
assert_abs_diff_eq!(jet.derivative, -comparison_jet.derivative);
}
#[test]
fn curve_reparam_curve() {
let reparam_curve = reparam_curve();
let reparam_jet = reparam_curve.sample_with_derivative(0.6).unwrap();
let curve1 = test_curve();
let curve = curve1.by_ref().reparametrize_by_curve(&reparam_curve);
let jet = curve.sample_with_derivative(0.6).unwrap();
let base_jet = curve1
.sample_with_derivative(reparam_curve.sample(0.6).unwrap())
.unwrap();
assert_abs_diff_eq!(jet.value, base_jet.value);
assert_abs_diff_eq!(jet.derivative, base_jet.derivative * reparam_jet.derivative);
}
#[test]
fn linear_reparam_curve() {
let curve1 = test_curve();
let curve = curve1
.by_ref()
.reparametrize_linear(Interval::new(0.0, 0.5).unwrap())
.unwrap();
let jet = curve.sample_with_derivative(0.23).unwrap();
let comparison_jet = curve1.sample_with_derivative(0.46).unwrap();
assert_abs_diff_eq!(jet.value, comparison_jet.value);
assert_abs_diff_eq!(jet.derivative, comparison_jet.derivative * 2.0);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/curve/derivatives/mod.rs | crates/bevy_math/src/curve/derivatives/mod.rs | //! This module holds traits related to extracting derivatives from curves. In
//! applications, the derivatives of interest are chiefly the first and second;
//! in this module, these are provided by the traits [`CurveWithDerivative`]
//! and [`CurveWithTwoDerivatives`].
//!
//! These take ownership of the curve they are used on by default, so that
//! the resulting output may be used in more durable contexts. For example,
//! `CurveWithDerivative<T>` is not dyn-compatible, but `Curve<WithDerivative<T>>`
//! is, so if such a curve needs to be stored in a dynamic context, calling
//! [`with_derivative`] and then placing the result in a
//! `Box<Curve<WithDerivative<T>>>` is sensible.
//!
//! On the other hand, in more transient contexts, consuming a value merely to
//! sample derivatives is inconvenient, and in these cases, it is recommended
//! to use [`by_ref`] when possible to create a referential curve first, retaining
//! liveness of the original.
//!
//! This module also holds the [`SampleDerivative`] and [`SampleTwoDerivatives`]
//! traits, which can be used to easily implement `CurveWithDerivative` and its
//! counterpart.
//!
//! [`with_derivative`]: CurveWithDerivative::with_derivative
//! [`by_ref`]: crate::curve::CurveExt::by_ref
pub mod adaptor_impls;
use crate::{
common_traits::{HasTangent, WithDerivative, WithTwoDerivatives},
curve::{Curve, Interval},
};
use core::ops::Deref;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{FromReflect, Reflect};
/// Trait for curves that have a well-defined notion of derivative, allowing for
/// derivatives to be extracted along with values.
///
/// This is implemented by implementing [`SampleDerivative`].
pub trait CurveWithDerivative<T>: SampleDerivative<T> + Sized
where
T: HasTangent,
{
/// This curve, but with its first derivative included in sampling.
///
/// Notably, the output type is a `Curve<WithDerivative<T>>`.
fn with_derivative(self) -> SampleDerivativeWrapper<Self>;
}
/// Trait for curves that have a well-defined notion of second derivative,
/// allowing for two derivatives to be extracted along with values.
///
/// This is implemented by implementing [`SampleTwoDerivatives`].
pub trait CurveWithTwoDerivatives<T>: SampleTwoDerivatives<T> + Sized
where
T: HasTangent,
{
/// This curve, but with its first two derivatives included in sampling.
///
/// Notably, the output type is a `Curve<WithTwoDerivatives<T>>`.
fn with_two_derivatives(self) -> SampleTwoDerivativesWrapper<Self>;
}
/// A trait for curves that can sample derivatives in addition to values.
///
/// Types that implement this trait automatically implement [`CurveWithDerivative`];
/// the curve produced by [`with_derivative`] uses the sampling defined in the trait
/// implementation.
///
/// [`with_derivative`]: CurveWithDerivative::with_derivative
pub trait SampleDerivative<T>: Curve<T>
where
T: HasTangent,
{
/// Sample this curve at the parameter value `t`, extracting the associated value
/// in addition to its derivative. This is the unchecked version of sampling, which
/// should only be used if the sample time `t` is already known to lie within the
/// curve's domain.
///
/// See [`Curve::sample_unchecked`] for more information.
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<T>;
/// Sample this curve's value and derivative at the parameter value `t`, returning
/// `None` if the point is outside of the curve's domain.
fn sample_with_derivative(&self, t: f32) -> Option<WithDerivative<T>> {
match self.domain().contains(t) {
true => Some(self.sample_with_derivative_unchecked(t)),
false => None,
}
}
/// Sample this curve's value and derivative at the parameter value `t`, clamping `t`
/// to lie inside the domain of the curve.
fn sample_with_derivative_clamped(&self, t: f32) -> WithDerivative<T> {
let t = self.domain().clamp(t);
self.sample_with_derivative_unchecked(t)
}
}
impl<T, C, D> SampleDerivative<T> for D
where
T: HasTangent,
C: SampleDerivative<T> + ?Sized,
D: Deref<Target = C>,
{
fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<T> {
<C as SampleDerivative<T>>::sample_with_derivative_unchecked(self, t)
}
}
/// A trait for curves that can sample two derivatives in addition to values.
///
/// Types that implement this trait automatically implement [`CurveWithTwoDerivatives`];
/// the curve produced by [`with_two_derivatives`] uses the sampling defined in the trait
/// implementation.
///
/// [`with_two_derivatives`]: CurveWithTwoDerivatives::with_two_derivatives
pub trait SampleTwoDerivatives<T>: Curve<T>
where
T: HasTangent,
{
/// Sample this curve at the parameter value `t`, extracting the associated value
/// in addition to two derivatives. This is the unchecked version of sampling, which
/// should only be used if the sample time `t` is already known to lie within the
/// curve's domain.
///
/// See [`Curve::sample_unchecked`] for more information.
fn sample_with_two_derivatives_unchecked(&self, t: f32) -> WithTwoDerivatives<T>;
/// Sample this curve's value and two derivatives at the parameter value `t`, returning
/// `None` if the point is outside of the curve's domain.
fn sample_with_two_derivatives(&self, t: f32) -> Option<WithTwoDerivatives<T>> {
match self.domain().contains(t) {
true => Some(self.sample_with_two_derivatives_unchecked(t)),
false => None,
}
}
/// Sample this curve's value and two derivatives at the parameter value `t`, clamping `t`
/// to lie inside the domain of the curve.
fn sample_with_two_derivatives_clamped(&self, t: f32) -> WithTwoDerivatives<T> {
let t = self.domain().clamp(t);
self.sample_with_two_derivatives_unchecked(t)
}
}
/// A wrapper that uses a [`SampleDerivative<T>`] curve to produce a `Curve<WithDerivative<T>>`.
#[derive(Copy, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect, FromReflect),
reflect(from_reflect = false)
)]
pub struct SampleDerivativeWrapper<C>(C);
impl<T, C> Curve<WithDerivative<T>> for SampleDerivativeWrapper<C>
where
T: HasTangent,
C: SampleDerivative<T>,
{
fn domain(&self) -> Interval {
self.0.domain()
}
fn sample_unchecked(&self, t: f32) -> WithDerivative<T> {
self.0.sample_with_derivative_unchecked(t)
}
fn sample(&self, t: f32) -> Option<WithDerivative<T>> {
self.0.sample_with_derivative(t)
}
fn sample_clamped(&self, t: f32) -> WithDerivative<T> {
self.0.sample_with_derivative_clamped(t)
}
}
/// A wrapper that uses a [`SampleTwoDerivatives<T>`] curve to produce a
/// `Curve<WithTwoDerivatives<T>>`.
#[derive(Copy, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect, FromReflect),
reflect(from_reflect = false)
)]
pub struct SampleTwoDerivativesWrapper<C>(C);
impl<T, C> Curve<WithTwoDerivatives<T>> for SampleTwoDerivativesWrapper<C>
where
T: HasTangent,
C: SampleTwoDerivatives<T>,
{
fn domain(&self) -> Interval {
self.0.domain()
}
fn sample_unchecked(&self, t: f32) -> WithTwoDerivatives<T> {
self.0.sample_with_two_derivatives_unchecked(t)
}
fn sample(&self, t: f32) -> Option<WithTwoDerivatives<T>> {
self.0.sample_with_two_derivatives(t)
}
fn sample_clamped(&self, t: f32) -> WithTwoDerivatives<T> {
self.0.sample_with_two_derivatives_clamped(t)
}
}
impl<T, C> CurveWithDerivative<T> for C
where
T: HasTangent,
C: SampleDerivative<T>,
{
fn with_derivative(self) -> SampleDerivativeWrapper<Self> {
SampleDerivativeWrapper(self)
}
}
impl<T, C> CurveWithTwoDerivatives<T> for C
where
T: HasTangent,
C: SampleTwoDerivatives<T> + CurveWithDerivative<T>,
{
fn with_two_derivatives(self) -> SampleTwoDerivativesWrapper<Self> {
SampleTwoDerivativesWrapper(self)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/bounding/raycast2d.rs | crates/bevy_math/src/bounding/raycast2d.rs | use super::{Aabb2d, BoundingCircle, IntersectsVolume};
use crate::{
ops::{self, FloatPow},
Dir2, Ray2d, Vec2,
};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
/// A raycast intersection test for 2D bounding volumes
#[derive(Clone, Debug)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
pub struct RayCast2d {
/// The ray for the test
pub ray: Ray2d,
/// The maximum distance for the ray
pub max: f32,
/// The multiplicative inverse direction of the ray
direction_recip: Vec2,
}
impl RayCast2d {
/// Construct a [`RayCast2d`] from an origin, [`Dir2`], and max distance.
pub fn new(origin: Vec2, direction: Dir2, max: f32) -> Self {
Self::from_ray(Ray2d { origin, direction }, max)
}
/// Construct a [`RayCast2d`] from a [`Ray2d`] and max distance.
pub fn from_ray(ray: Ray2d, max: f32) -> Self {
Self {
ray,
direction_recip: ray.direction.recip(),
max,
}
}
/// Get the cached multiplicative inverse of the direction of the ray.
pub fn direction_recip(&self) -> Vec2 {
self.direction_recip
}
/// Get the distance of an intersection with an [`Aabb2d`], if any.
pub fn aabb_intersection_at(&self, aabb: &Aabb2d) -> Option<f32> {
let (min_x, max_x) = if self.ray.direction.x.is_sign_positive() {
(aabb.min.x, aabb.max.x)
} else {
(aabb.max.x, aabb.min.x)
};
let (min_y, max_y) = if self.ray.direction.y.is_sign_positive() {
(aabb.min.y, aabb.max.y)
} else {
(aabb.max.y, aabb.min.y)
};
// Calculate the minimum/maximum time for each axis based on how much the direction goes that
// way. These values can get arbitrarily large, or even become NaN, which is handled by the
// min/max operations below
let tmin_x = (min_x - self.ray.origin.x) * self.direction_recip.x;
let tmin_y = (min_y - self.ray.origin.y) * self.direction_recip.y;
let tmax_x = (max_x - self.ray.origin.x) * self.direction_recip.x;
let tmax_y = (max_y - self.ray.origin.y) * self.direction_recip.y;
// An axis that is not relevant to the ray direction will be NaN. When one of the arguments
// to min/max is NaN, the other argument is used.
// An axis for which the direction is the wrong way will return an arbitrarily large
// negative value.
let tmin = tmin_x.max(tmin_y).max(0.);
let tmax = tmax_y.min(tmax_x).min(self.max);
if tmin <= tmax {
Some(tmin)
} else {
None
}
}
/// Get the distance of an intersection with a [`BoundingCircle`], if any.
pub fn circle_intersection_at(&self, circle: &BoundingCircle) -> Option<f32> {
let offset = self.ray.origin - circle.center;
let projected = offset.dot(*self.ray.direction);
let cross = offset.perp_dot(*self.ray.direction);
let distance_squared = circle.radius().squared() - cross.squared();
if distance_squared < 0.
|| ops::copysign(projected.squared(), -projected) < -distance_squared
{
None
} else {
let toi = -projected - ops::sqrt(distance_squared);
if toi > self.max {
None
} else {
Some(toi.max(0.))
}
}
}
}
impl IntersectsVolume<Aabb2d> for RayCast2d {
fn intersects(&self, volume: &Aabb2d) -> bool {
self.aabb_intersection_at(volume).is_some()
}
}
impl IntersectsVolume<BoundingCircle> for RayCast2d {
fn intersects(&self, volume: &BoundingCircle) -> bool {
self.circle_intersection_at(volume).is_some()
}
}
/// An intersection test that casts an [`Aabb2d`] along a ray.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
pub struct AabbCast2d {
/// The ray along which to cast the bounding volume
pub ray: RayCast2d,
/// The aabb that is being cast
pub aabb: Aabb2d,
}
impl AabbCast2d {
/// Construct an [`AabbCast2d`] from an [`Aabb2d`], origin, [`Dir2`], and max distance.
pub fn new(aabb: Aabb2d, origin: Vec2, direction: Dir2, max: f32) -> Self {
Self::from_ray(aabb, Ray2d { origin, direction }, max)
}
/// Construct an [`AabbCast2d`] from an [`Aabb2d`], [`Ray2d`], and max distance.
pub fn from_ray(aabb: Aabb2d, ray: Ray2d, max: f32) -> Self {
Self {
ray: RayCast2d::from_ray(ray, max),
aabb,
}
}
/// Get the distance at which the [`Aabb2d`]s collide, if at all.
pub fn aabb_collision_at(&self, mut aabb: Aabb2d) -> Option<f32> {
aabb.min -= self.aabb.max;
aabb.max -= self.aabb.min;
self.ray.aabb_intersection_at(&aabb)
}
}
impl IntersectsVolume<Aabb2d> for AabbCast2d {
fn intersects(&self, volume: &Aabb2d) -> bool {
self.aabb_collision_at(*volume).is_some()
}
}
/// An intersection test that casts a [`BoundingCircle`] along a ray.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
pub struct BoundingCircleCast {
/// The ray along which to cast the bounding volume
pub ray: RayCast2d,
/// The circle that is being cast
pub circle: BoundingCircle,
}
impl BoundingCircleCast {
/// Construct a [`BoundingCircleCast`] from a [`BoundingCircle`], origin, [`Dir2`], and max distance.
pub fn new(circle: BoundingCircle, origin: Vec2, direction: Dir2, max: f32) -> Self {
Self::from_ray(circle, Ray2d { origin, direction }, max)
}
/// Construct a [`BoundingCircleCast`] from a [`BoundingCircle`], [`Ray2d`], and max distance.
pub fn from_ray(circle: BoundingCircle, ray: Ray2d, max: f32) -> Self {
Self {
ray: RayCast2d::from_ray(ray, max),
circle,
}
}
/// Get the distance at which the [`BoundingCircle`]s collide, if at all.
pub fn circle_collision_at(&self, mut circle: BoundingCircle) -> Option<f32> {
circle.center -= self.circle.center;
circle.circle.radius += self.circle.radius();
self.ray.circle_intersection_at(&circle)
}
}
impl IntersectsVolume<BoundingCircle> for BoundingCircleCast {
fn intersects(&self, volume: &BoundingCircle) -> bool {
self.circle_collision_at(*volume).is_some()
}
}
#[cfg(test)]
mod tests {
use super::*;
const EPSILON: f32 = 0.001;
#[test]
fn test_ray_intersection_circle_hits() {
for (test, volume, expected_distance) in &[
(
// Hit the center of a centered bounding circle
RayCast2d::new(Vec2::Y * -5., Dir2::Y, 90.),
BoundingCircle::new(Vec2::ZERO, 1.),
4.,
),
(
// Hit the center of a centered bounding circle, but from the other side
RayCast2d::new(Vec2::Y * 5., -Dir2::Y, 90.),
BoundingCircle::new(Vec2::ZERO, 1.),
4.,
),
(
// Hit the center of an offset circle
RayCast2d::new(Vec2::ZERO, Dir2::Y, 90.),
BoundingCircle::new(Vec2::Y * 3., 2.),
1.,
),
(
// Just barely hit the circle before the max distance
RayCast2d::new(Vec2::X, Dir2::Y, 1.),
BoundingCircle::new(Vec2::ONE, 0.01),
0.99,
),
(
// Hit a circle off-center
RayCast2d::new(Vec2::X, Dir2::Y, 90.),
BoundingCircle::new(Vec2::Y * 5., 2.),
3.268,
),
(
// Barely hit a circle on the side
RayCast2d::new(Vec2::X * 0.99999, Dir2::Y, 90.),
BoundingCircle::new(Vec2::Y * 5., 1.),
4.996,
),
] {
assert!(
test.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
let actual_distance = test.circle_intersection_at(volume).unwrap();
assert!(
ops::abs(actual_distance - expected_distance) < EPSILON,
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}\n Actual distance: {actual_distance}",
);
let inverted_ray = RayCast2d::new(test.ray.origin, -test.ray.direction, test.max);
assert!(
!inverted_ray.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
}
}
#[test]
fn test_ray_intersection_circle_misses() {
for (test, volume) in &[
(
// The ray doesn't go in the right direction
RayCast2d::new(Vec2::ZERO, Dir2::X, 90.),
BoundingCircle::new(Vec2::Y * 2., 1.),
),
(
// Ray's alignment isn't enough to hit the circle
RayCast2d::new(Vec2::ZERO, Dir2::from_xy(1., 1.).unwrap(), 90.),
BoundingCircle::new(Vec2::Y * 2., 1.),
),
(
// The ray's maximum distance isn't high enough
RayCast2d::new(Vec2::ZERO, Dir2::Y, 0.5),
BoundingCircle::new(Vec2::Y * 2., 1.),
),
] {
assert!(
!test.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}",
);
}
}
#[test]
fn test_ray_intersection_circle_inside() {
let volume = BoundingCircle::new(Vec2::splat(0.5), 1.);
for origin in &[Vec2::X, Vec2::Y, Vec2::ONE, Vec2::ZERO] {
for direction in &[Dir2::X, Dir2::Y, -Dir2::X, -Dir2::Y] {
for max in &[0., 1., 900.] {
let test = RayCast2d::new(*origin, *direction, *max);
assert!(
test.intersects(&volume),
"Case:\n origin: {origin:?}\n Direction: {direction:?}\n Max: {max}",
);
let actual_distance = test.circle_intersection_at(&volume);
assert_eq!(
actual_distance,
Some(0.),
"Case:\n origin: {origin:?}\n Direction: {direction:?}\n Max: {max}",
);
}
}
}
}
#[test]
fn test_ray_intersection_aabb_hits() {
for (test, volume, expected_distance) in &[
(
// Hit the center of a centered aabb
RayCast2d::new(Vec2::Y * -5., Dir2::Y, 90.),
Aabb2d::new(Vec2::ZERO, Vec2::ONE),
4.,
),
(
// Hit the center of a centered aabb, but from the other side
RayCast2d::new(Vec2::Y * 5., -Dir2::Y, 90.),
Aabb2d::new(Vec2::ZERO, Vec2::ONE),
4.,
),
(
// Hit the center of an offset aabb
RayCast2d::new(Vec2::ZERO, Dir2::Y, 90.),
Aabb2d::new(Vec2::Y * 3., Vec2::splat(2.)),
1.,
),
(
// Just barely hit the aabb before the max distance
RayCast2d::new(Vec2::X, Dir2::Y, 1.),
Aabb2d::new(Vec2::ONE, Vec2::splat(0.01)),
0.99,
),
(
// Hit an aabb off-center
RayCast2d::new(Vec2::X, Dir2::Y, 90.),
Aabb2d::new(Vec2::Y * 5., Vec2::splat(2.)),
3.,
),
(
// Barely hit an aabb on corner
RayCast2d::new(Vec2::X * -0.001, Dir2::from_xy(1., 1.).unwrap(), 90.),
Aabb2d::new(Vec2::Y * 2., Vec2::ONE),
1.414,
),
] {
assert!(
test.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
let actual_distance = test.aabb_intersection_at(volume).unwrap();
assert!(
ops::abs(actual_distance - expected_distance) < EPSILON,
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}\n Actual distance: {actual_distance}",
);
let inverted_ray = RayCast2d::new(test.ray.origin, -test.ray.direction, test.max);
assert!(
!inverted_ray.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
}
}
#[test]
fn test_ray_intersection_aabb_misses() {
for (test, volume) in &[
(
// The ray doesn't go in the right direction
RayCast2d::new(Vec2::ZERO, Dir2::X, 90.),
Aabb2d::new(Vec2::Y * 2., Vec2::ONE),
),
(
// Ray's alignment isn't enough to hit the aabb
RayCast2d::new(Vec2::ZERO, Dir2::from_xy(1., 0.99).unwrap(), 90.),
Aabb2d::new(Vec2::Y * 2., Vec2::ONE),
),
(
// The ray's maximum distance isn't high enough
RayCast2d::new(Vec2::ZERO, Dir2::Y, 0.5),
Aabb2d::new(Vec2::Y * 2., Vec2::ONE),
),
] {
assert!(
!test.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}",
);
}
}
#[test]
fn test_ray_intersection_aabb_inside() {
let volume = Aabb2d::new(Vec2::splat(0.5), Vec2::ONE);
for origin in &[Vec2::X, Vec2::Y, Vec2::ONE, Vec2::ZERO] {
for direction in &[Dir2::X, Dir2::Y, -Dir2::X, -Dir2::Y] {
for max in &[0., 1., 900.] {
let test = RayCast2d::new(*origin, *direction, *max);
assert!(
test.intersects(&volume),
"Case:\n origin: {origin:?}\n Direction: {direction:?}\n Max: {max}",
);
let actual_distance = test.aabb_intersection_at(&volume);
assert_eq!(
actual_distance,
Some(0.),
"Case:\n origin: {origin:?}\n Direction: {direction:?}\n Max: {max}",
);
}
}
}
}
#[test]
fn test_aabb_cast_hits() {
for (test, volume, expected_distance) in &[
(
// Hit the center of the aabb, that a ray would've also hit
AabbCast2d::new(Aabb2d::new(Vec2::ZERO, Vec2::ONE), Vec2::ZERO, Dir2::Y, 90.),
Aabb2d::new(Vec2::Y * 5., Vec2::ONE),
3.,
),
(
// Hit the center of the aabb, but from the other side
AabbCast2d::new(
Aabb2d::new(Vec2::ZERO, Vec2::ONE),
Vec2::Y * 10.,
-Dir2::Y,
90.,
),
Aabb2d::new(Vec2::Y * 5., Vec2::ONE),
3.,
),
(
// Hit the edge of the aabb, that a ray would've missed
AabbCast2d::new(
Aabb2d::new(Vec2::ZERO, Vec2::ONE),
Vec2::X * 1.5,
Dir2::Y,
90.,
),
Aabb2d::new(Vec2::Y * 5., Vec2::ONE),
3.,
),
(
// Hit the edge of the aabb, by casting an off-center AABB
AabbCast2d::new(
Aabb2d::new(Vec2::X * -2., Vec2::ONE),
Vec2::X * 3.,
Dir2::Y,
90.,
),
Aabb2d::new(Vec2::Y * 5., Vec2::ONE),
3.,
),
] {
assert!(
test.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
let actual_distance = test.aabb_collision_at(*volume).unwrap();
assert!(
ops::abs(actual_distance - expected_distance) < EPSILON,
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}\n Actual distance: {actual_distance}",
);
let inverted_ray =
RayCast2d::new(test.ray.ray.origin, -test.ray.ray.direction, test.ray.max);
assert!(
!inverted_ray.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
}
}
#[test]
fn test_circle_cast_hits() {
for (test, volume, expected_distance) in &[
(
// Hit the center of the bounding circle, that a ray would've also hit
BoundingCircleCast::new(
BoundingCircle::new(Vec2::ZERO, 1.),
Vec2::ZERO,
Dir2::Y,
90.,
),
BoundingCircle::new(Vec2::Y * 5., 1.),
3.,
),
(
// Hit the center of the bounding circle, but from the other side
BoundingCircleCast::new(
BoundingCircle::new(Vec2::ZERO, 1.),
Vec2::Y * 10.,
-Dir2::Y,
90.,
),
BoundingCircle::new(Vec2::Y * 5., 1.),
3.,
),
(
// Hit the bounding circle off-center, that a ray would've missed
BoundingCircleCast::new(
BoundingCircle::new(Vec2::ZERO, 1.),
Vec2::X * 1.5,
Dir2::Y,
90.,
),
BoundingCircle::new(Vec2::Y * 5., 1.),
3.677,
),
(
// Hit the bounding circle off-center, by casting a circle that is off-center
BoundingCircleCast::new(
BoundingCircle::new(Vec2::X * -1.5, 1.),
Vec2::X * 3.,
Dir2::Y,
90.,
),
BoundingCircle::new(Vec2::Y * 5., 1.),
3.677,
),
] {
assert!(
test.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
let actual_distance = test.circle_collision_at(*volume).unwrap();
assert!(
ops::abs(actual_distance - expected_distance) < EPSILON,
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}\n Actual distance: {actual_distance}",
);
let inverted_ray =
RayCast2d::new(test.ray.ray.origin, -test.ray.ray.direction, test.ray.max);
assert!(
!inverted_ray.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/bounding/mod.rs | crates/bevy_math/src/bounding/mod.rs | //! This module contains traits and implements for working with bounding shapes
//!
//! There are four traits used:
//! - [`BoundingVolume`] is a generic abstraction for any bounding volume
//! - [`IntersectsVolume`] abstracts intersection tests against a [`BoundingVolume`]
//! - [`Bounded2d`]/[`Bounded3d`] are abstractions for shapes to generate [`BoundingVolume`]s
/// A trait that generalizes different bounding volumes.
/// Bounding volumes are simplified shapes that are used to get simpler ways to check for
/// overlapping elements or finding intersections.
///
/// This trait supports both 2D and 3D bounding shapes.
pub trait BoundingVolume: Sized {
/// The position type used for the volume. This should be `Vec2` for 2D and `Vec3` for 3D.
type Translation: Clone + Copy + PartialEq;
/// The rotation type used for the volume. This should be `Rot2` for 2D and `Quat` for 3D.
type Rotation: Clone + Copy + PartialEq;
/// The type used for the size of the bounding volume. Usually a half size. For example an
/// `f32` radius for a circle, or a `Vec3` with half sizes for x, y and z for a 3D axis-aligned
/// bounding box
type HalfSize;
/// Returns the center of the bounding volume.
fn center(&self) -> Self::Translation;
/// Returns the half size of the bounding volume.
fn half_size(&self) -> Self::HalfSize;
/// Computes the visible surface area of the bounding volume.
/// This method can be useful to make decisions about merging bounding volumes,
/// using a Surface Area Heuristic.
///
/// For 2D shapes this would simply be the area of the shape.
/// For 3D shapes this would usually be half the area of the shape.
fn visible_area(&self) -> f32;
/// Checks if this bounding volume contains another one.
fn contains(&self, other: &Self) -> bool;
/// Computes the smallest bounding volume that contains both `self` and `other`.
fn merge(&self, other: &Self) -> Self;
/// Increases the size of the bounding volume in each direction by the given amount.
fn grow(&self, amount: impl Into<Self::HalfSize>) -> Self;
/// Decreases the size of the bounding volume in each direction by the given amount.
fn shrink(&self, amount: impl Into<Self::HalfSize>) -> Self;
/// Scale the size of the bounding volume around its center by the given amount
fn scale_around_center(&self, scale: impl Into<Self::HalfSize>) -> Self;
/// Transforms the bounding volume by first rotating it around the origin and then applying a translation.
fn transformed_by(
mut self,
translation: impl Into<Self::Translation>,
rotation: impl Into<Self::Rotation>,
) -> Self {
self.transform_by(translation, rotation);
self
}
/// Transforms the bounding volume by first rotating it around the origin and then applying a translation.
fn transform_by(
&mut self,
translation: impl Into<Self::Translation>,
rotation: impl Into<Self::Rotation>,
) {
self.rotate_by(rotation);
self.translate_by(translation);
}
/// Translates the bounding volume by the given translation.
fn translated_by(mut self, translation: impl Into<Self::Translation>) -> Self {
self.translate_by(translation);
self
}
/// Translates the bounding volume by the given translation.
fn translate_by(&mut self, translation: impl Into<Self::Translation>);
/// Rotates the bounding volume around the origin by the given rotation.
///
/// The result is a combination of the original volume and the rotated volume,
/// so it is guaranteed to be either the same size or larger than the original.
fn rotated_by(mut self, rotation: impl Into<Self::Rotation>) -> Self {
self.rotate_by(rotation);
self
}
/// Rotates the bounding volume around the origin by the given rotation.
///
/// The result is a combination of the original volume and the rotated volume,
/// so it is guaranteed to be either the same size or larger than the original.
fn rotate_by(&mut self, rotation: impl Into<Self::Rotation>);
}
/// A trait that generalizes intersection tests against a volume.
/// Intersection tests can be used for a variety of tasks, for example:
/// - Raycasting
/// - Testing for overlap
/// - Checking if an object is within the view frustum of a camera
pub trait IntersectsVolume<Volume: BoundingVolume> {
/// Check if a volume intersects with this intersection test
fn intersects(&self, volume: &Volume) -> bool;
}
mod bounded2d;
pub use bounded2d::*;
mod bounded3d;
pub use bounded3d::*;
mod raycast2d;
pub use raycast2d::*;
mod raycast3d;
pub use raycast3d::*;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/bounding/raycast3d.rs | crates/bevy_math/src/bounding/raycast3d.rs | use super::{Aabb3d, BoundingSphere, IntersectsVolume};
use crate::{
ops::{self, FloatPow},
Dir3A, Ray3d, Vec3A,
};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
/// A raycast intersection test for 3D bounding volumes
#[derive(Clone, Debug)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
pub struct RayCast3d {
/// The origin of the ray.
pub origin: Vec3A,
/// The direction of the ray.
pub direction: Dir3A,
/// The maximum distance for the ray
pub max: f32,
/// The multiplicative inverse direction of the ray
direction_recip: Vec3A,
}
impl RayCast3d {
/// Construct a [`RayCast3d`] from an origin, [direction], and max distance.
///
/// [direction]: crate::direction::Dir3
pub fn new(origin: impl Into<Vec3A>, direction: impl Into<Dir3A>, max: f32) -> Self {
let direction = direction.into();
Self {
origin: origin.into(),
direction,
direction_recip: direction.recip(),
max,
}
}
/// Construct a [`RayCast3d`] from a [`Ray3d`] and max distance.
pub fn from_ray(ray: Ray3d, max: f32) -> Self {
Self::new(ray.origin, ray.direction, max)
}
/// Get the cached multiplicative inverse of the direction of the ray.
pub fn direction_recip(&self) -> Vec3A {
self.direction_recip
}
/// Get the distance of an intersection with an [`Aabb3d`], if any.
pub fn aabb_intersection_at(&self, aabb: &Aabb3d) -> Option<f32> {
let positive = self.direction.signum().cmpgt(Vec3A::ZERO);
let min = Vec3A::select(positive, aabb.min, aabb.max);
let max = Vec3A::select(positive, aabb.max, aabb.min);
// Calculate the minimum/maximum time for each axis based on how much the direction goes that
// way. These values can get arbitrarily large, or even become NaN, which is handled by the
// min/max operations below
let tmin = (min - self.origin) * self.direction_recip;
let tmax = (max - self.origin) * self.direction_recip;
// An axis that is not relevant to the ray direction will be NaN. When one of the arguments
// to min/max is NaN, the other argument is used.
// An axis for which the direction is the wrong way will return an arbitrarily large
// negative value.
let tmin = tmin.max_element().max(0.);
let tmax = tmax.min_element().min(self.max);
if tmin <= tmax {
Some(tmin)
} else {
None
}
}
/// Get the distance of an intersection with a [`BoundingSphere`], if any.
pub fn sphere_intersection_at(&self, sphere: &BoundingSphere) -> Option<f32> {
let offset = self.origin - sphere.center;
let projected = offset.dot(*self.direction);
let closest_point = offset - projected * *self.direction;
let distance_squared = sphere.radius().squared() - closest_point.length_squared();
if distance_squared < 0.
|| ops::copysign(projected.squared(), -projected) < -distance_squared
{
None
} else {
let toi = -projected - ops::sqrt(distance_squared);
if toi > self.max {
None
} else {
Some(toi.max(0.))
}
}
}
}
impl IntersectsVolume<Aabb3d> for RayCast3d {
fn intersects(&self, volume: &Aabb3d) -> bool {
self.aabb_intersection_at(volume).is_some()
}
}
impl IntersectsVolume<BoundingSphere> for RayCast3d {
fn intersects(&self, volume: &BoundingSphere) -> bool {
self.sphere_intersection_at(volume).is_some()
}
}
/// An intersection test that casts an [`Aabb3d`] along a ray.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
pub struct AabbCast3d {
/// The ray along which to cast the bounding volume
pub ray: RayCast3d,
/// The aabb that is being cast
pub aabb: Aabb3d,
}
impl AabbCast3d {
/// Construct an [`AabbCast3d`] from an [`Aabb3d`], origin, [direction], and max distance.
///
/// [direction]: crate::direction::Dir3
pub fn new(
aabb: Aabb3d,
origin: impl Into<Vec3A>,
direction: impl Into<Dir3A>,
max: f32,
) -> Self {
Self {
ray: RayCast3d::new(origin, direction, max),
aabb,
}
}
/// Construct an [`AabbCast3d`] from an [`Aabb3d`], [`Ray3d`], and max distance.
pub fn from_ray(aabb: Aabb3d, ray: Ray3d, max: f32) -> Self {
Self::new(aabb, ray.origin, ray.direction, max)
}
/// Get the distance at which the [`Aabb3d`]s collide, if at all.
pub fn aabb_collision_at(&self, mut aabb: Aabb3d) -> Option<f32> {
aabb.min -= self.aabb.max;
aabb.max -= self.aabb.min;
self.ray.aabb_intersection_at(&aabb)
}
}
impl IntersectsVolume<Aabb3d> for AabbCast3d {
fn intersects(&self, volume: &Aabb3d) -> bool {
self.aabb_collision_at(*volume).is_some()
}
}
/// An intersection test that casts a [`BoundingSphere`] along a ray.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
pub struct BoundingSphereCast {
/// The ray along which to cast the bounding volume
pub ray: RayCast3d,
/// The sphere that is being cast
pub sphere: BoundingSphere,
}
impl BoundingSphereCast {
/// Construct a [`BoundingSphereCast`] from a [`BoundingSphere`], origin, [direction], and max distance.
///
/// [direction]: crate::direction::Dir3
pub fn new(
sphere: BoundingSphere,
origin: impl Into<Vec3A>,
direction: impl Into<Dir3A>,
max: f32,
) -> Self {
Self {
ray: RayCast3d::new(origin, direction, max),
sphere,
}
}
/// Construct a [`BoundingSphereCast`] from a [`BoundingSphere`], [`Ray3d`], and max distance.
pub fn from_ray(sphere: BoundingSphere, ray: Ray3d, max: f32) -> Self {
Self::new(sphere, ray.origin, ray.direction, max)
}
/// Get the distance at which the [`BoundingSphere`]s collide, if at all.
pub fn sphere_collision_at(&self, mut sphere: BoundingSphere) -> Option<f32> {
sphere.center -= self.sphere.center;
sphere.sphere.radius += self.sphere.radius();
self.ray.sphere_intersection_at(&sphere)
}
}
impl IntersectsVolume<BoundingSphere> for BoundingSphereCast {
fn intersects(&self, volume: &BoundingSphere) -> bool {
self.sphere_collision_at(*volume).is_some()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Dir3, Vec3};
const EPSILON: f32 = 0.001;
#[test]
fn test_ray_intersection_sphere_hits() {
for (test, volume, expected_distance) in &[
(
// Hit the center of a centered bounding sphere
RayCast3d::new(Vec3::Y * -5., Dir3::Y, 90.),
BoundingSphere::new(Vec3::ZERO, 1.),
4.,
),
(
// Hit the center of a centered bounding sphere, but from the other side
RayCast3d::new(Vec3::Y * 5., -Dir3::Y, 90.),
BoundingSphere::new(Vec3::ZERO, 1.),
4.,
),
(
// Hit the center of an offset sphere
RayCast3d::new(Vec3::ZERO, Dir3::Y, 90.),
BoundingSphere::new(Vec3::Y * 3., 2.),
1.,
),
(
// Just barely hit the sphere before the max distance
RayCast3d::new(Vec3::X, Dir3::Y, 1.),
BoundingSphere::new(Vec3::new(1., 1., 0.), 0.01),
0.99,
),
(
// Hit a sphere off-center
RayCast3d::new(Vec3::X, Dir3::Y, 90.),
BoundingSphere::new(Vec3::Y * 5., 2.),
3.268,
),
(
// Barely hit a sphere on the side
RayCast3d::new(Vec3::X * 0.99999, Dir3::Y, 90.),
BoundingSphere::new(Vec3::Y * 5., 1.),
4.996,
),
] {
assert!(
test.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
let actual_distance = test.sphere_intersection_at(volume).unwrap();
assert!(
ops::abs(actual_distance - expected_distance) < EPSILON,
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}\n Actual distance: {actual_distance}",
);
let inverted_ray = RayCast3d::new(test.origin, -test.direction, test.max);
assert!(
!inverted_ray.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
}
}
#[test]
fn test_ray_intersection_sphere_misses() {
for (test, volume) in &[
(
// The ray doesn't go in the right direction
RayCast3d::new(Vec3::ZERO, Dir3::X, 90.),
BoundingSphere::new(Vec3::Y * 2., 1.),
),
(
// Ray's alignment isn't enough to hit the sphere
RayCast3d::new(Vec3::ZERO, Dir3::from_xyz(1., 1., 1.).unwrap(), 90.),
BoundingSphere::new(Vec3::Y * 2., 1.),
),
(
// The ray's maximum distance isn't high enough
RayCast3d::new(Vec3::ZERO, Dir3::Y, 0.5),
BoundingSphere::new(Vec3::Y * 2., 1.),
),
] {
assert!(
!test.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}",
);
}
}
#[test]
fn test_ray_intersection_sphere_inside() {
let volume = BoundingSphere::new(Vec3::splat(0.5), 1.);
for origin in &[Vec3::X, Vec3::Y, Vec3::ONE, Vec3::ZERO] {
for direction in &[Dir3::X, Dir3::Y, Dir3::Z, -Dir3::X, -Dir3::Y, -Dir3::Z] {
for max in &[0., 1., 900.] {
let test = RayCast3d::new(*origin, *direction, *max);
assert!(
test.intersects(&volume),
"Case:\n origin: {origin:?}\n Direction: {direction:?}\n Max: {max}",
);
let actual_distance = test.sphere_intersection_at(&volume);
assert_eq!(
actual_distance,
Some(0.),
"Case:\n origin: {origin:?}\n Direction: {direction:?}\n Max: {max}",
);
}
}
}
}
#[test]
fn test_ray_intersection_aabb_hits() {
for (test, volume, expected_distance) in &[
(
// Hit the center of a centered aabb
RayCast3d::new(Vec3::Y * -5., Dir3::Y, 90.),
Aabb3d::new(Vec3::ZERO, Vec3::ONE),
4.,
),
(
// Hit the center of a centered aabb, but from the other side
RayCast3d::new(Vec3::Y * 5., -Dir3::Y, 90.),
Aabb3d::new(Vec3::ZERO, Vec3::ONE),
4.,
),
(
// Hit the center of an offset aabb
RayCast3d::new(Vec3::ZERO, Dir3::Y, 90.),
Aabb3d::new(Vec3::Y * 3., Vec3::splat(2.)),
1.,
),
(
// Just barely hit the aabb before the max distance
RayCast3d::new(Vec3::X, Dir3::Y, 1.),
Aabb3d::new(Vec3::new(1., 1., 0.), Vec3::splat(0.01)),
0.99,
),
(
// Hit an aabb off-center
RayCast3d::new(Vec3::X, Dir3::Y, 90.),
Aabb3d::new(Vec3::Y * 5., Vec3::splat(2.)),
3.,
),
(
// Barely hit an aabb on corner
RayCast3d::new(Vec3::X * -0.001, Dir3::from_xyz(1., 1., 1.).unwrap(), 90.),
Aabb3d::new(Vec3::Y * 2., Vec3::ONE),
1.732,
),
] {
assert!(
test.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
let actual_distance = test.aabb_intersection_at(volume).unwrap();
assert!(
ops::abs(actual_distance - expected_distance) < EPSILON,
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}\n Actual distance: {actual_distance}",
);
let inverted_ray = RayCast3d::new(test.origin, -test.direction, test.max);
assert!(
!inverted_ray.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
}
}
#[test]
fn test_ray_intersection_aabb_misses() {
for (test, volume) in &[
(
// The ray doesn't go in the right direction
RayCast3d::new(Vec3::ZERO, Dir3::X, 90.),
Aabb3d::new(Vec3::Y * 2., Vec3::ONE),
),
(
// Ray's alignment isn't enough to hit the aabb
RayCast3d::new(Vec3::ZERO, Dir3::from_xyz(1., 0.99, 1.).unwrap(), 90.),
Aabb3d::new(Vec3::Y * 2., Vec3::ONE),
),
(
// The ray's maximum distance isn't high enough
RayCast3d::new(Vec3::ZERO, Dir3::Y, 0.5),
Aabb3d::new(Vec3::Y * 2., Vec3::ONE),
),
] {
assert!(
!test.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}",
);
}
}
#[test]
fn test_ray_intersection_aabb_inside() {
let volume = Aabb3d::new(Vec3::splat(0.5), Vec3::ONE);
for origin in &[Vec3::X, Vec3::Y, Vec3::ONE, Vec3::ZERO] {
for direction in &[Dir3::X, Dir3::Y, Dir3::Z, -Dir3::X, -Dir3::Y, -Dir3::Z] {
for max in &[0., 1., 900.] {
let test = RayCast3d::new(*origin, *direction, *max);
assert!(
test.intersects(&volume),
"Case:\n origin: {origin:?}\n Direction: {direction:?}\n Max: {max}",
);
let actual_distance = test.aabb_intersection_at(&volume);
assert_eq!(
actual_distance,
Some(0.),
"Case:\n origin: {origin:?}\n Direction: {direction:?}\n Max: {max}",
);
}
}
}
}
#[test]
fn test_aabb_cast_hits() {
for (test, volume, expected_distance) in &[
(
// Hit the center of the aabb, that a ray would've also hit
AabbCast3d::new(Aabb3d::new(Vec3::ZERO, Vec3::ONE), Vec3::ZERO, Dir3::Y, 90.),
Aabb3d::new(Vec3::Y * 5., Vec3::ONE),
3.,
),
(
// Hit the center of the aabb, but from the other side
AabbCast3d::new(
Aabb3d::new(Vec3::ZERO, Vec3::ONE),
Vec3::Y * 10.,
-Dir3::Y,
90.,
),
Aabb3d::new(Vec3::Y * 5., Vec3::ONE),
3.,
),
(
// Hit the edge of the aabb, that a ray would've missed
AabbCast3d::new(
Aabb3d::new(Vec3::ZERO, Vec3::ONE),
Vec3::X * 1.5,
Dir3::Y,
90.,
),
Aabb3d::new(Vec3::Y * 5., Vec3::ONE),
3.,
),
(
// Hit the edge of the aabb, by casting an off-center AABB
AabbCast3d::new(
Aabb3d::new(Vec3::X * -2., Vec3::ONE),
Vec3::X * 3.,
Dir3::Y,
90.,
),
Aabb3d::new(Vec3::Y * 5., Vec3::ONE),
3.,
),
] {
assert!(
test.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
let actual_distance = test.aabb_collision_at(*volume).unwrap();
assert!(
ops::abs(actual_distance - expected_distance) < EPSILON,
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}\n Actual distance: {actual_distance}",
);
let inverted_ray = RayCast3d::new(test.ray.origin, -test.ray.direction, test.ray.max);
assert!(
!inverted_ray.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
}
}
#[test]
fn test_sphere_cast_hits() {
for (test, volume, expected_distance) in &[
(
// Hit the center of the bounding sphere, that a ray would've also hit
BoundingSphereCast::new(
BoundingSphere::new(Vec3::ZERO, 1.),
Vec3::ZERO,
Dir3::Y,
90.,
),
BoundingSphere::new(Vec3::Y * 5., 1.),
3.,
),
(
// Hit the center of the bounding sphere, but from the other side
BoundingSphereCast::new(
BoundingSphere::new(Vec3::ZERO, 1.),
Vec3::Y * 10.,
-Dir3::Y,
90.,
),
BoundingSphere::new(Vec3::Y * 5., 1.),
3.,
),
(
// Hit the bounding sphere off-center, that a ray would've missed
BoundingSphereCast::new(
BoundingSphere::new(Vec3::ZERO, 1.),
Vec3::X * 1.5,
Dir3::Y,
90.,
),
BoundingSphere::new(Vec3::Y * 5., 1.),
3.677,
),
(
// Hit the bounding sphere off-center, by casting a sphere that is off-center
BoundingSphereCast::new(
BoundingSphere::new(Vec3::X * -1.5, 1.),
Vec3::X * 3.,
Dir3::Y,
90.,
),
BoundingSphere::new(Vec3::Y * 5., 1.),
3.677,
),
] {
assert!(
test.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
let actual_distance = test.sphere_collision_at(*volume).unwrap();
assert!(
ops::abs(actual_distance - expected_distance) < EPSILON,
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}\n Actual distance: {actual_distance}",
);
let inverted_ray = RayCast3d::new(test.ray.origin, -test.ray.direction, test.ray.max);
assert!(
!inverted_ray.intersects(volume),
"Case:\n Test: {test:?}\n Volume: {volume:?}\n Expected distance: {expected_distance:?}",
);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/bounding/bounded3d/extrusion.rs | crates/bevy_math/src/bounding/bounded3d/extrusion.rs | use core::f32::consts::FRAC_PI_2;
use glam::{Vec2, Vec3A, Vec3Swizzles};
use crate::{
bounding::{BoundingCircle, BoundingVolume},
ops,
primitives::{
Capsule2d, Cuboid, Cylinder, Ellipse, Extrusion, Line2d, Primitive2d, Rectangle,
RegularPolygon, Ring, Segment2d, Triangle2d,
},
Isometry2d, Isometry3d, Quat, Rot2,
};
#[cfg(feature = "alloc")]
use crate::primitives::{Polygon, Polyline2d};
use crate::{bounding::Bounded2d, primitives::Circle};
use super::{Aabb3d, Bounded3d, BoundingSphere};
impl BoundedExtrusion for Circle {
fn extrusion_aabb_3d(&self, half_depth: f32, isometry: impl Into<Isometry3d>) -> Aabb3d {
// Reference: http://iquilezles.org/articles/diskbbox/
let isometry = isometry.into();
let segment_dir = isometry.rotation * Vec3A::Z;
let top = (segment_dir * half_depth).abs();
let e = (Vec3A::ONE - segment_dir * segment_dir).max(Vec3A::ZERO);
let half_size = self.radius * Vec3A::new(ops::sqrt(e.x), ops::sqrt(e.y), ops::sqrt(e.z));
Aabb3d {
min: isometry.translation - half_size - top,
max: isometry.translation + half_size + top,
}
}
}
impl BoundedExtrusion for Ellipse {
fn extrusion_aabb_3d(&self, half_depth: f32, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
let Vec2 { x: a, y: b } = self.half_size;
let normal = isometry.rotation * Vec3A::Z;
let conjugate_rot = isometry.rotation.conjugate();
let [max_x, max_y, max_z] = Vec3A::AXES.map(|axis| {
let Some(axis) = (conjugate_rot * axis.reject_from(normal))
.xy()
.try_normalize()
else {
return Vec3A::ZERO;
};
if axis.element_product() == 0. {
return isometry.rotation * Vec3A::new(a * axis.y, b * axis.x, 0.);
}
let m = -axis.x / axis.y;
let signum = axis.signum();
let y = signum.y * b * b / ops::sqrt(b * b + m * m * a * a);
let x = signum.x * a * ops::sqrt(1. - y * y / b / b);
isometry.rotation * Vec3A::new(x, y, 0.)
});
let half_size = Vec3A::new(max_x.x, max_y.y, max_z.z).abs() + (normal * half_depth).abs();
Aabb3d::new(isometry.translation, half_size)
}
}
impl BoundedExtrusion for Line2d {
fn extrusion_aabb_3d(&self, half_depth: f32, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
let dir = isometry.rotation * Vec3A::from(self.direction.extend(0.));
let half_depth = (isometry.rotation * Vec3A::new(0., 0., half_depth)).abs();
let max = f32::MAX / 2.;
let half_size = Vec3A::new(
if dir.x == 0. { half_depth.x } else { max },
if dir.y == 0. { half_depth.y } else { max },
if dir.z == 0. { half_depth.z } else { max },
);
Aabb3d::new(isometry.translation, half_size)
}
}
impl BoundedExtrusion for Segment2d {
fn extrusion_aabb_3d(&self, half_depth: f32, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
let half_size = isometry.rotation * Vec3A::from(self.point1().extend(0.));
let depth = isometry.rotation * Vec3A::new(0., 0., half_depth);
Aabb3d::new(isometry.translation, half_size.abs() + depth.abs())
}
}
#[cfg(feature = "alloc")]
impl BoundedExtrusion for Polyline2d {
fn extrusion_aabb_3d(&self, half_depth: f32, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
let aabb = Aabb3d::from_point_cloud(isometry, self.vertices.iter().map(|v| v.extend(0.)));
let depth = isometry.rotation * Vec3A::new(0., 0., half_depth);
aabb.grow(depth.abs())
}
}
impl BoundedExtrusion for Triangle2d {
fn extrusion_aabb_3d(&self, half_depth: f32, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
let aabb = Aabb3d::from_point_cloud(isometry, self.vertices.iter().map(|v| v.extend(0.)));
let depth = isometry.rotation * Vec3A::new(0., 0., half_depth);
aabb.grow(depth.abs())
}
}
impl BoundedExtrusion for Rectangle {
fn extrusion_aabb_3d(&self, half_depth: f32, isometry: impl Into<Isometry3d>) -> Aabb3d {
Cuboid {
half_size: self.half_size.extend(half_depth),
}
.aabb_3d(isometry)
}
}
#[cfg(feature = "alloc")]
impl BoundedExtrusion for Polygon {
fn extrusion_aabb_3d(&self, half_depth: f32, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
let aabb = Aabb3d::from_point_cloud(isometry, self.vertices.iter().map(|v| v.extend(0.)));
let depth = isometry.rotation * Vec3A::new(0., 0., half_depth);
aabb.grow(depth.abs())
}
}
impl BoundedExtrusion for RegularPolygon {
fn extrusion_aabb_3d(&self, half_depth: f32, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
let aabb = Aabb3d::from_point_cloud(
isometry,
self.vertices(0.).into_iter().map(|v| v.extend(0.)),
);
let depth = isometry.rotation * Vec3A::new(0., 0., half_depth);
aabb.grow(depth.abs())
}
}
impl BoundedExtrusion for Capsule2d {
fn extrusion_aabb_3d(&self, half_depth: f32, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
let aabb = Cylinder {
half_height: half_depth,
radius: self.radius,
}
.aabb_3d(isometry.rotation * Quat::from_rotation_x(FRAC_PI_2));
let up = isometry.rotation * Vec3A::new(0., self.half_length, 0.);
let half_size = aabb.max + up.abs();
Aabb3d::new(isometry.translation, half_size)
}
}
impl<T: BoundedExtrusion> BoundedExtrusion for Ring<T> {
fn extrusion_aabb_3d(&self, half_depth: f32, isometry: impl Into<Isometry3d>) -> Aabb3d {
self.outer_shape.extrusion_aabb_3d(half_depth, isometry)
}
fn extrusion_bounding_sphere(
&self,
half_depth: f32,
isometry: impl Into<Isometry3d>,
) -> BoundingSphere {
self.outer_shape
.extrusion_bounding_sphere(half_depth, isometry)
}
}
impl<T: BoundedExtrusion> Bounded3d for Extrusion<T> {
fn aabb_3d(&self, isometry: impl Into<Isometry3d>) -> Aabb3d {
self.base_shape.extrusion_aabb_3d(self.half_depth, isometry)
}
fn bounding_sphere(&self, isometry: impl Into<Isometry3d>) -> BoundingSphere {
self.base_shape
.extrusion_bounding_sphere(self.half_depth, isometry)
}
}
/// A trait implemented on 2D shapes which determines the 3D bounding volumes of their extrusions.
///
/// Since default implementations can be inferred from 2D bounding volumes, this allows a `Bounded2d`
/// implementation on some shape `MyShape` to be extrapolated to a `Bounded3d` implementation on
/// `Extrusion<MyShape>` without supplying any additional data; e.g.:
/// `impl BoundedExtrusion for MyShape {}`
pub trait BoundedExtrusion: Primitive2d + Bounded2d {
/// Get an axis-aligned bounding box for an extrusion with this shape as a base and the given `half_depth`, transformed by the given `translation` and `rotation`.
fn extrusion_aabb_3d(&self, half_depth: f32, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
let cap_normal = isometry.rotation * Vec3A::Z;
let conjugate_rot = isometry.rotation.conjugate();
// The `(halfsize, offset)` for each axis
let axis_values = Vec3A::AXES.map(|ax| {
// This is the direction of the line of intersection of a plane with the `ax` normal and the plane containing the cap of the extrusion.
let intersect_line = ax.cross(cap_normal);
if intersect_line.length_squared() <= f32::EPSILON {
return (0., 0.);
};
// This is the normal vector of the intersection line rotated to be in the XY-plane
let line_normal = (conjugate_rot * intersect_line).yx();
let angle = line_normal.to_angle();
// Since the plane containing the caps of the extrusion is not guaranteed to be orthogonal to the `ax` plane, only a certain "scale" factor
// of the `Aabb2d` will actually go towards the dimensions of the `Aabb3d`
let scale = cap_normal.reject_from(ax).length();
// Calculate the `Aabb2d` of the base shape. The shape is rotated so that the line of intersection is parallel to the Y axis in the `Aabb2d` calculations.
// This guarantees that the X value of the `Aabb2d` is closest to the `ax` plane
let aabb2d = self.aabb_2d(Rot2::radians(angle));
(aabb2d.half_size().x * scale, aabb2d.center().x * scale)
});
let offset = Vec3A::from_array(axis_values.map(|(_, offset)| offset));
let cap_size = Vec3A::from_array(axis_values.map(|(max_val, _)| max_val)).abs();
let depth = isometry.rotation * Vec3A::new(0., 0., half_depth);
Aabb3d::new(isometry.translation - offset, cap_size + depth.abs())
}
/// Get a bounding sphere for an extrusion of the `base_shape` with the given `half_depth` with the given translation and rotation
fn extrusion_bounding_sphere(
&self,
half_depth: f32,
isometry: impl Into<Isometry3d>,
) -> BoundingSphere {
let isometry = isometry.into();
// We calculate the bounding circle of the base shape.
// Since each of the extrusions bases will have the same distance from its center,
// and they are just shifted along the Z-axis, the minimum bounding sphere will be the bounding sphere
// of the cylinder defined by the two bounding circles of the bases for any base shape
let BoundingCircle {
center,
circle: Circle { radius },
} = self.bounding_circle(Isometry2d::IDENTITY);
let radius = ops::hypot(radius, half_depth);
let center = isometry * Vec3A::from(center.extend(0.));
BoundingSphere::new(center, radius)
}
}
#[cfg(test)]
mod tests {
use core::f32::consts::FRAC_PI_4;
use glam::{EulerRot, Quat, Vec2, Vec3, Vec3A};
use crate::{
bounding::{Bounded3d, BoundingVolume},
ops,
primitives::{
Capsule2d, Circle, Ellipse, Extrusion, Line2d, Polygon, Polyline2d, Rectangle,
RegularPolygon, Segment2d, Triangle2d,
},
Dir2, Isometry3d,
};
#[test]
fn circle() {
let cylinder = Extrusion::new(Circle::new(0.5), 2.0);
let translation = Vec3::new(2.0, 1.0, 0.0);
let aabb = cylinder.aabb_3d(translation);
assert_eq!(aabb.center(), Vec3A::from(translation));
assert_eq!(aabb.half_size(), Vec3A::new(0.5, 0.5, 1.0));
let bounding_sphere = cylinder.bounding_sphere(translation);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(bounding_sphere.radius(), ops::hypot(1.0, 0.5));
}
#[test]
fn ellipse() {
let extrusion = Extrusion::new(Ellipse::new(2.0, 0.5), 4.0);
let translation = Vec3::new(3., 4., 5.);
let rotation = Quat::from_euler(EulerRot::ZYX, FRAC_PI_4, FRAC_PI_4, FRAC_PI_4);
let isometry = Isometry3d::new(translation, rotation);
let aabb = extrusion.aabb_3d(isometry);
assert_eq!(aabb.center(), Vec3A::from(translation));
assert_eq!(aabb.half_size(), Vec3A::new(2.709784, 1.3801551, 2.436141));
let bounding_sphere = extrusion.bounding_sphere(isometry);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(bounding_sphere.radius(), ops::sqrt(8f32));
}
#[test]
fn line() {
let extrusion = Extrusion::new(
Line2d {
direction: Dir2::new_unchecked(Vec2::Y),
},
4.,
);
let translation = Vec3::new(3., 4., 5.);
let rotation = Quat::from_rotation_y(FRAC_PI_4);
let isometry = Isometry3d::new(translation, rotation);
let aabb = extrusion.aabb_3d(isometry);
assert_eq!(aabb.min, Vec3A::new(1.5857864, f32::MIN / 2., 3.5857865));
assert_eq!(aabb.max, Vec3A::new(4.4142136, f32::MAX / 2., 6.414213));
let bounding_sphere = extrusion.bounding_sphere(isometry);
assert_eq!(bounding_sphere.center(), translation.into());
assert_eq!(bounding_sphere.radius(), f32::MAX / 2.);
}
#[test]
fn rectangle() {
let extrusion = Extrusion::new(Rectangle::new(2.0, 1.0), 4.0);
let translation = Vec3::new(3., 4., 5.);
let rotation = Quat::from_rotation_z(FRAC_PI_4);
let isometry = Isometry3d::new(translation, rotation);
let aabb = extrusion.aabb_3d(isometry);
assert_eq!(aabb.center(), translation.into());
assert_eq!(aabb.half_size(), Vec3A::new(1.0606602, 1.0606602, 2.));
let bounding_sphere = extrusion.bounding_sphere(isometry);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(bounding_sphere.radius(), 2.291288);
}
#[test]
fn segment() {
let extrusion = Extrusion::new(
Segment2d::new(Vec2::new(0.0, -1.5), Vec2::new(0.0, 1.5)),
4.0,
);
let translation = Vec3::new(3., 4., 5.);
let rotation = Quat::from_rotation_x(FRAC_PI_4);
let isometry = Isometry3d::new(translation, rotation);
let aabb = extrusion.aabb_3d(isometry);
assert_eq!(aabb.center(), translation.into());
assert_eq!(aabb.half_size(), Vec3A::new(0., 2.4748735, 2.4748735));
let bounding_sphere = extrusion.bounding_sphere(isometry);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(bounding_sphere.radius(), 2.5);
}
#[test]
fn polyline() {
let polyline = Polyline2d::new([
Vec2::ONE,
Vec2::new(-1.0, 1.0),
Vec2::NEG_ONE,
Vec2::new(1.0, -1.0),
]);
let extrusion = Extrusion::new(polyline, 3.0);
let translation = Vec3::new(3., 4., 5.);
let rotation = Quat::from_rotation_x(FRAC_PI_4);
let isometry = Isometry3d::new(translation, rotation);
let aabb = extrusion.aabb_3d(isometry);
assert_eq!(aabb.center(), translation.into());
assert_eq!(aabb.half_size(), Vec3A::new(1., 1.7677668, 1.7677668));
let bounding_sphere = extrusion.bounding_sphere(isometry);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(bounding_sphere.radius(), 2.0615528);
}
#[test]
fn triangle() {
let triangle = Triangle2d::new(
Vec2::new(0.0, 1.0),
Vec2::new(-10.0, -1.0),
Vec2::new(10.0, -1.0),
);
let extrusion = Extrusion::new(triangle, 3.0);
let translation = Vec3::new(3., 4., 5.);
let rotation = Quat::from_rotation_x(FRAC_PI_4);
let isometry = Isometry3d::new(translation, rotation);
let aabb = extrusion.aabb_3d(isometry);
assert_eq!(aabb.center(), translation.into());
assert_eq!(aabb.half_size(), Vec3A::new(10., 1.7677668, 1.7677668));
let bounding_sphere = extrusion.bounding_sphere(isometry);
assert_eq!(
bounding_sphere.center,
Vec3A::new(3.0, 3.2928934, 4.2928934)
);
assert_eq!(bounding_sphere.radius(), 10.111875);
}
#[test]
fn polygon() {
let polygon = Polygon::new([
Vec2::ONE,
Vec2::new(-1.0, 1.0),
Vec2::NEG_ONE,
Vec2::new(1.0, -1.0),
]);
let extrusion = Extrusion::new(polygon, 3.0);
let translation = Vec3::new(3., 4., 5.);
let rotation = Quat::from_rotation_x(FRAC_PI_4);
let isometry = Isometry3d::new(translation, rotation);
let aabb = extrusion.aabb_3d(isometry);
assert_eq!(aabb.center(), translation.into());
assert_eq!(aabb.half_size(), Vec3A::new(1., 1.7677668, 1.7677668));
let bounding_sphere = extrusion.bounding_sphere(isometry);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(bounding_sphere.radius(), 2.0615528);
}
#[test]
fn regular_polygon() {
let extrusion = Extrusion::new(RegularPolygon::new(2.0, 7), 4.0);
let translation = Vec3::new(3., 4., 5.);
let rotation = Quat::from_rotation_x(FRAC_PI_4);
let isometry = Isometry3d::new(translation, rotation);
let aabb = extrusion.aabb_3d(isometry);
assert_eq!(
aabb.center(),
Vec3A::from(translation) + Vec3A::new(0., 0.0700254, 0.0700254)
);
assert_eq!(
aabb.half_size(),
Vec3A::new(1.9498558, 2.7584014, 2.7584019)
);
let bounding_sphere = extrusion.bounding_sphere(isometry);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(bounding_sphere.radius(), ops::sqrt(8f32));
}
#[test]
fn capsule() {
let extrusion = Extrusion::new(Capsule2d::new(0.5, 2.0), 4.0);
let translation = Vec3::new(3., 4., 5.);
let rotation = Quat::from_rotation_x(FRAC_PI_4);
let isometry = Isometry3d::new(translation, rotation);
let aabb = extrusion.aabb_3d(isometry);
assert_eq!(aabb.center(), translation.into());
assert_eq!(aabb.half_size(), Vec3A::new(0.5, 2.4748735, 2.4748735));
let bounding_sphere = extrusion.bounding_sphere(isometry);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(bounding_sphere.radius(), 2.5);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/bounding/bounded3d/mod.rs | crates/bevy_math/src/bounding/bounded3d/mod.rs | mod extrusion;
mod primitive_impls;
use glam::Mat3;
use super::{BoundingVolume, IntersectsVolume};
use crate::{
ops::{self, FloatPow},
primitives::Cuboid,
Isometry3d, Quat, Vec3A,
};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
#[cfg(all(feature = "bevy_reflect", feature = "serialize"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};
pub use extrusion::BoundedExtrusion;
/// Computes the geometric center of the given set of points.
#[inline]
fn point_cloud_3d_center(points: impl Iterator<Item = impl Into<Vec3A>>) -> Vec3A {
let (acc, len) = points.fold((Vec3A::ZERO, 0), |(acc, len), point| {
(acc + point.into(), len + 1)
});
assert!(
len > 0,
"cannot compute the center of an empty set of points"
);
acc / len as f32
}
/// A trait with methods that return 3D bounding volumes for a shape.
pub trait Bounded3d {
/// Get an axis-aligned bounding box for the shape translated and rotated by the given isometry.
fn aabb_3d(&self, isometry: impl Into<Isometry3d>) -> Aabb3d;
/// Get a bounding sphere for the shape translated and rotated by the given isometry.
fn bounding_sphere(&self, isometry: impl Into<Isometry3d>) -> BoundingSphere;
}
/// A 3D axis-aligned bounding box
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
#[cfg_attr(feature = "serialize", derive(Serialize), derive(Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Aabb3d {
/// The minimum point of the box
pub min: Vec3A,
/// The maximum point of the box
pub max: Vec3A,
}
impl Aabb3d {
/// Constructs an AABB from its center and half-size.
#[inline]
pub fn new(center: impl Into<Vec3A>, half_size: impl Into<Vec3A>) -> Self {
let (center, half_size) = (center.into(), half_size.into());
debug_assert!(half_size.x >= 0.0 && half_size.y >= 0.0 && half_size.z >= 0.0);
Self {
min: center - half_size,
max: center + half_size,
}
}
/// Constructs an AABB from its minimum and maximum extent.
#[inline]
pub fn from_min_max(min: impl Into<Vec3A>, max: impl Into<Vec3A>) -> Self {
let (min, max) = (min.into(), max.into());
debug_assert!(min.x <= max.x && min.y <= max.y && min.z <= max.z);
Self { min, max }
}
/// Computes the smallest [`Aabb3d`] containing the given set of points,
/// transformed by the rotation and translation of the given isometry.
///
/// # Panics
///
/// Panics if the given set of points is empty.
#[inline]
pub fn from_point_cloud(
isometry: impl Into<Isometry3d>,
points: impl Iterator<Item = impl Into<Vec3A>>,
) -> Aabb3d {
let isometry = isometry.into();
// Transform all points by rotation
let mut iter = points.map(|point| isometry.rotation * point.into());
let first = iter
.next()
.expect("point cloud must contain at least one point for Aabb3d construction");
let (min, max) = iter.fold((first, first), |(prev_min, prev_max), point| {
(point.min(prev_min), point.max(prev_max))
});
Aabb3d {
min: min + isometry.translation,
max: max + isometry.translation,
}
}
/// Computes the smallest [`BoundingSphere`] containing this [`Aabb3d`].
#[inline]
pub fn bounding_sphere(&self) -> BoundingSphere {
let radius = self.min.distance(self.max) / 2.0;
BoundingSphere::new(self.center(), radius)
}
/// Finds the point on the AABB that is closest to the given `point`.
///
/// If the point is outside the AABB, the returned point will be on the surface of the AABB.
/// Otherwise, it will be inside the AABB and returned as is.
#[inline]
pub fn closest_point(&self, point: impl Into<Vec3A>) -> Vec3A {
// Clamp point coordinates to the AABB
point.into().clamp(self.min, self.max)
}
}
impl From<Cuboid> for Aabb3d {
fn from(value: Cuboid) -> Self {
Aabb3d {
min: (-value.half_size).into(),
max: value.half_size.into(),
}
}
}
impl BoundingVolume for Aabb3d {
type Translation = Vec3A;
type Rotation = Quat;
type HalfSize = Vec3A;
#[inline]
fn center(&self) -> Self::Translation {
(self.min + self.max) / 2.
}
#[inline]
fn half_size(&self) -> Self::HalfSize {
(self.max - self.min) / 2.
}
#[inline]
fn visible_area(&self) -> f32 {
let b = (self.max - self.min).max(Vec3A::ZERO);
b.x * (b.y + b.z) + b.y * b.z
}
#[inline]
fn contains(&self, other: &Self) -> bool {
other.min.cmpge(self.min).all() && other.max.cmple(self.max).all()
}
#[inline]
fn merge(&self, other: &Self) -> Self {
Self {
min: self.min.min(other.min),
max: self.max.max(other.max),
}
}
#[inline]
fn grow(&self, amount: impl Into<Self::HalfSize>) -> Self {
let amount = amount.into();
let b = Self {
min: self.min - amount,
max: self.max + amount,
};
debug_assert!(b.min.cmple(b.max).all());
b
}
#[inline]
fn shrink(&self, amount: impl Into<Self::HalfSize>) -> Self {
let amount = amount.into();
let b = Self {
min: self.min + amount,
max: self.max - amount,
};
debug_assert!(b.min.cmple(b.max).all());
b
}
#[inline]
fn scale_around_center(&self, scale: impl Into<Self::HalfSize>) -> Self {
let scale = scale.into();
let b = Self {
min: self.center() - (self.half_size() * scale),
max: self.center() + (self.half_size() * scale),
};
debug_assert!(b.min.cmple(b.max).all());
b
}
/// Transforms the bounding volume by first rotating it around the origin and then applying a translation.
///
/// The result is an Axis-Aligned Bounding Box that encompasses the rotated shape.
///
/// Note that the result may not be as tightly fitting as the original, and repeated rotations
/// can cause the AABB to grow indefinitely. Avoid applying multiple rotations to the same AABB,
/// and consider storing the original AABB and rotating that every time instead.
#[inline]
fn transformed_by(
mut self,
translation: impl Into<Self::Translation>,
rotation: impl Into<Self::Rotation>,
) -> Self {
self.transform_by(translation, rotation);
self
}
/// Transforms the bounding volume by first rotating it around the origin and then applying a translation.
///
/// The result is an Axis-Aligned Bounding Box that encompasses the rotated shape.
///
/// Note that the result may not be as tightly fitting as the original, and repeated rotations
/// can cause the AABB to grow indefinitely. Avoid applying multiple rotations to the same AABB,
/// and consider storing the original AABB and rotating that every time instead.
#[inline]
fn transform_by(
&mut self,
translation: impl Into<Self::Translation>,
rotation: impl Into<Self::Rotation>,
) {
self.rotate_by(rotation);
self.translate_by(translation);
}
#[inline]
fn translate_by(&mut self, translation: impl Into<Self::Translation>) {
let translation = translation.into();
self.min += translation;
self.max += translation;
}
/// Rotates the bounding volume around the origin by the given rotation.
///
/// The result is an Axis-Aligned Bounding Box that encompasses the rotated shape.
///
/// Note that the result may not be as tightly fitting as the original, and repeated rotations
/// can cause the AABB to grow indefinitely. Avoid applying multiple rotations to the same AABB,
/// and consider storing the original AABB and rotating that every time instead.
#[inline]
fn rotated_by(mut self, rotation: impl Into<Self::Rotation>) -> Self {
self.rotate_by(rotation);
self
}
/// Rotates the bounding volume around the origin by the given rotation.
///
/// The result is an Axis-Aligned Bounding Box that encompasses the rotated shape.
///
/// Note that the result may not be as tightly fitting as the original, and repeated rotations
/// can cause the AABB to grow indefinitely. Avoid applying multiple rotations to the same AABB,
/// and consider storing the original AABB and rotating that every time instead.
#[inline]
fn rotate_by(&mut self, rotation: impl Into<Self::Rotation>) {
let rot_mat = Mat3::from_quat(rotation.into());
let half_size = rot_mat.abs() * self.half_size();
*self = Self::new(rot_mat * self.center(), half_size);
}
}
impl IntersectsVolume<Self> for Aabb3d {
#[inline]
fn intersects(&self, other: &Self) -> bool {
self.min.cmple(other.max).all() && self.max.cmpge(other.min).all()
}
}
impl IntersectsVolume<BoundingSphere> for Aabb3d {
#[inline]
fn intersects(&self, sphere: &BoundingSphere) -> bool {
let closest_point = self.closest_point(sphere.center);
let distance_squared = sphere.center.distance_squared(closest_point);
let radius_squared = sphere.radius().squared();
distance_squared <= radius_squared
}
}
#[cfg(test)]
mod aabb3d_tests {
use approx::assert_relative_eq;
use super::Aabb3d;
use crate::{
bounding::{BoundingSphere, BoundingVolume, IntersectsVolume},
ops, Quat, Vec3, Vec3A,
};
#[test]
fn center() {
let aabb = Aabb3d {
min: Vec3A::new(-0.5, -1., -0.5),
max: Vec3A::new(1., 1., 2.),
};
assert!((aabb.center() - Vec3A::new(0.25, 0., 0.75)).length() < f32::EPSILON);
let aabb = Aabb3d {
min: Vec3A::new(5., 5., -10.),
max: Vec3A::new(10., 10., -5.),
};
assert!((aabb.center() - Vec3A::new(7.5, 7.5, -7.5)).length() < f32::EPSILON);
}
#[test]
fn half_size() {
let aabb = Aabb3d {
min: Vec3A::new(-0.5, -1., -0.5),
max: Vec3A::new(1., 1., 2.),
};
assert!((aabb.half_size() - Vec3A::new(0.75, 1., 1.25)).length() < f32::EPSILON);
}
#[test]
fn area() {
let aabb = Aabb3d {
min: Vec3A::new(-1., -1., -1.),
max: Vec3A::new(1., 1., 1.),
};
assert!(ops::abs(aabb.visible_area() - 12.) < f32::EPSILON);
let aabb = Aabb3d {
min: Vec3A::new(0., 0., 0.),
max: Vec3A::new(1., 0.5, 0.25),
};
assert!(ops::abs(aabb.visible_area() - 0.875) < f32::EPSILON);
}
#[test]
fn contains() {
let a = Aabb3d {
min: Vec3A::new(-1., -1., -1.),
max: Vec3A::new(1., 1., 1.),
};
let b = Aabb3d {
min: Vec3A::new(-2., -1., -1.),
max: Vec3A::new(1., 1., 1.),
};
assert!(!a.contains(&b));
let b = Aabb3d {
min: Vec3A::new(-0.25, -0.8, -0.9),
max: Vec3A::new(1., 1., 0.9),
};
assert!(a.contains(&b));
}
#[test]
fn merge() {
let a = Aabb3d {
min: Vec3A::new(-1., -1., -1.),
max: Vec3A::new(1., 0.5, 1.),
};
let b = Aabb3d {
min: Vec3A::new(-2., -0.5, -0.),
max: Vec3A::new(0.75, 1., 2.),
};
let merged = a.merge(&b);
assert!((merged.min - Vec3A::new(-2., -1., -1.)).length() < f32::EPSILON);
assert!((merged.max - Vec3A::new(1., 1., 2.)).length() < f32::EPSILON);
assert!(merged.contains(&a));
assert!(merged.contains(&b));
assert!(!a.contains(&merged));
assert!(!b.contains(&merged));
}
#[test]
fn grow() {
let a = Aabb3d {
min: Vec3A::new(-1., -1., -1.),
max: Vec3A::new(1., 1., 1.),
};
let padded = a.grow(Vec3A::ONE);
assert!((padded.min - Vec3A::new(-2., -2., -2.)).length() < f32::EPSILON);
assert!((padded.max - Vec3A::new(2., 2., 2.)).length() < f32::EPSILON);
assert!(padded.contains(&a));
assert!(!a.contains(&padded));
}
#[test]
fn shrink() {
let a = Aabb3d {
min: Vec3A::new(-2., -2., -2.),
max: Vec3A::new(2., 2., 2.),
};
let shrunk = a.shrink(Vec3A::ONE);
assert!((shrunk.min - Vec3A::new(-1., -1., -1.)).length() < f32::EPSILON);
assert!((shrunk.max - Vec3A::new(1., 1., 1.)).length() < f32::EPSILON);
assert!(a.contains(&shrunk));
assert!(!shrunk.contains(&a));
}
#[test]
fn scale_around_center() {
let a = Aabb3d {
min: Vec3A::NEG_ONE,
max: Vec3A::ONE,
};
let scaled = a.scale_around_center(Vec3A::splat(2.));
assert!((scaled.min - Vec3A::splat(-2.)).length() < f32::EPSILON);
assert!((scaled.max - Vec3A::splat(2.)).length() < f32::EPSILON);
assert!(!a.contains(&scaled));
assert!(scaled.contains(&a));
}
#[test]
fn rotate() {
use core::f32::consts::PI;
let a = Aabb3d {
min: Vec3A::new(-2.0, -2.0, -2.0),
max: Vec3A::new(2.0, 2.0, 2.0),
};
let rotation = Quat::from_euler(glam::EulerRot::XYZ, PI, PI, 0.0);
let rotated = a.rotated_by(rotation);
assert_relative_eq!(rotated.min, a.min);
assert_relative_eq!(rotated.max, a.max);
}
#[test]
fn transform() {
let a = Aabb3d {
min: Vec3A::new(-2.0, -2.0, -2.0),
max: Vec3A::new(2.0, 2.0, 2.0),
};
let transformed = a.transformed_by(
Vec3A::new(2.0, -2.0, 4.0),
Quat::from_rotation_z(core::f32::consts::FRAC_PI_4),
);
let half_length = ops::hypot(2.0, 2.0);
assert_eq!(
transformed.min,
Vec3A::new(2.0 - half_length, -half_length - 2.0, 2.0)
);
assert_eq!(
transformed.max,
Vec3A::new(2.0 + half_length, half_length - 2.0, 6.0)
);
}
#[test]
fn closest_point() {
let aabb = Aabb3d {
min: Vec3A::NEG_ONE,
max: Vec3A::ONE,
};
assert_eq!(aabb.closest_point(Vec3A::X * 10.0), Vec3A::X);
assert_eq!(aabb.closest_point(Vec3A::NEG_ONE * 10.0), Vec3A::NEG_ONE);
assert_eq!(
aabb.closest_point(Vec3A::new(0.25, 0.1, 0.3)),
Vec3A::new(0.25, 0.1, 0.3)
);
}
#[test]
fn intersect_aabb() {
let aabb = Aabb3d {
min: Vec3A::NEG_ONE,
max: Vec3A::ONE,
};
assert!(aabb.intersects(&aabb));
assert!(aabb.intersects(&Aabb3d {
min: Vec3A::splat(0.5),
max: Vec3A::splat(2.0),
}));
assert!(aabb.intersects(&Aabb3d {
min: Vec3A::splat(-2.0),
max: Vec3A::splat(-0.5),
}));
assert!(!aabb.intersects(&Aabb3d {
min: Vec3A::new(1.1, 0.0, 0.0),
max: Vec3A::new(2.0, 0.5, 0.25),
}));
}
#[test]
fn intersect_bounding_sphere() {
let aabb = Aabb3d {
min: Vec3A::NEG_ONE,
max: Vec3A::ONE,
};
assert!(aabb.intersects(&BoundingSphere::new(Vec3::ZERO, 1.0)));
assert!(aabb.intersects(&BoundingSphere::new(Vec3::ONE * 1.5, 1.0)));
assert!(aabb.intersects(&BoundingSphere::new(Vec3::NEG_ONE * 1.5, 1.0)));
assert!(!aabb.intersects(&BoundingSphere::new(Vec3::ONE * 1.75, 1.0)));
}
}
use crate::primitives::Sphere;
/// A bounding sphere
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
#[cfg_attr(feature = "serialize", derive(Serialize), derive(Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct BoundingSphere {
/// The center of the bounding sphere
pub center: Vec3A,
/// The sphere
pub sphere: Sphere,
}
impl BoundingSphere {
/// Constructs a bounding sphere from its center and radius.
pub fn new(center: impl Into<Vec3A>, radius: f32) -> Self {
debug_assert!(radius >= 0.);
Self {
center: center.into(),
sphere: Sphere { radius },
}
}
/// Computes a [`BoundingSphere`] containing the given set of points,
/// transformed by the rotation and translation of the given isometry.
///
/// The bounding sphere is not guaranteed to be the smallest possible.
#[inline]
pub fn from_point_cloud(
isometry: impl Into<Isometry3d>,
points: &[impl Copy + Into<Vec3A>],
) -> BoundingSphere {
let isometry = isometry.into();
let center = point_cloud_3d_center(points.iter().map(|v| Into::<Vec3A>::into(*v)));
let mut radius_squared: f32 = 0.0;
for point in points {
// Get squared version to avoid unnecessary sqrt calls
let distance_squared = Into::<Vec3A>::into(*point).distance_squared(center);
if distance_squared > radius_squared {
radius_squared = distance_squared;
}
}
BoundingSphere::new(isometry * center, ops::sqrt(radius_squared))
}
/// Get the radius of the bounding sphere
#[inline]
pub fn radius(&self) -> f32 {
self.sphere.radius
}
/// Computes the smallest [`Aabb3d`] containing this [`BoundingSphere`].
#[inline]
pub fn aabb_3d(&self) -> Aabb3d {
Aabb3d {
min: self.center - self.radius(),
max: self.center + self.radius(),
}
}
/// Finds the point on the bounding sphere that is closest to the given `point`.
///
/// If the point is outside the sphere, the returned point will be on the surface of the sphere.
/// Otherwise, it will be inside the sphere and returned as is.
#[inline]
pub fn closest_point(&self, point: impl Into<Vec3A>) -> Vec3A {
let point = point.into();
let radius = self.radius();
let distance_squared = (point - self.center).length_squared();
if distance_squared <= radius.squared() {
// The point is inside the sphere.
point
} else {
// The point is outside the sphere.
// Find the closest point on the surface of the sphere.
let dir_to_point = point / ops::sqrt(distance_squared);
self.center + radius * dir_to_point
}
}
}
impl BoundingVolume for BoundingSphere {
type Translation = Vec3A;
type Rotation = Quat;
type HalfSize = f32;
#[inline]
fn center(&self) -> Self::Translation {
self.center
}
#[inline]
fn half_size(&self) -> Self::HalfSize {
self.radius()
}
#[inline]
fn visible_area(&self) -> f32 {
2. * core::f32::consts::PI * self.radius() * self.radius()
}
#[inline]
fn contains(&self, other: &Self) -> bool {
let diff = self.radius() - other.radius();
self.center.distance_squared(other.center) <= ops::copysign(diff.squared(), diff)
}
#[inline]
fn merge(&self, other: &Self) -> Self {
let diff = other.center - self.center;
let length = diff.length();
if self.radius() >= length + other.radius() {
return *self;
}
if other.radius() >= length + self.radius() {
return *other;
}
let dir = diff / length;
Self::new(
(self.center + other.center) / 2. + dir * ((other.radius() - self.radius()) / 2.),
(length + self.radius() + other.radius()) / 2.,
)
}
#[inline]
fn grow(&self, amount: impl Into<Self::HalfSize>) -> Self {
let amount = amount.into();
debug_assert!(amount >= 0.);
Self {
center: self.center,
sphere: Sphere {
radius: self.radius() + amount,
},
}
}
#[inline]
fn shrink(&self, amount: impl Into<Self::HalfSize>) -> Self {
let amount = amount.into();
debug_assert!(amount >= 0.);
debug_assert!(self.radius() >= amount);
Self {
center: self.center,
sphere: Sphere {
radius: self.radius() - amount,
},
}
}
#[inline]
fn scale_around_center(&self, scale: impl Into<Self::HalfSize>) -> Self {
let scale = scale.into();
debug_assert!(scale >= 0.);
Self::new(self.center, self.radius() * scale)
}
#[inline]
fn translate_by(&mut self, translation: impl Into<Self::Translation>) {
self.center += translation.into();
}
#[inline]
fn rotate_by(&mut self, rotation: impl Into<Self::Rotation>) {
let rotation: Quat = rotation.into();
self.center = rotation * self.center;
}
}
impl IntersectsVolume<Self> for BoundingSphere {
#[inline]
fn intersects(&self, other: &Self) -> bool {
let center_distance_squared = self.center.distance_squared(other.center);
let radius_sum_squared = (self.radius() + other.radius()).squared();
center_distance_squared <= radius_sum_squared
}
}
impl IntersectsVolume<Aabb3d> for BoundingSphere {
#[inline]
fn intersects(&self, aabb: &Aabb3d) -> bool {
aabb.intersects(self)
}
}
#[cfg(test)]
mod bounding_sphere_tests {
use approx::assert_relative_eq;
use super::BoundingSphere;
use crate::{
bounding::{BoundingVolume, IntersectsVolume},
ops, Quat, Vec3, Vec3A,
};
#[test]
fn area() {
let sphere = BoundingSphere::new(Vec3::ONE, 5.);
// Since this number is messy we check it with a higher threshold
assert!(ops::abs(sphere.visible_area() - 157.0796) < 0.001);
}
#[test]
fn contains() {
let a = BoundingSphere::new(Vec3::ONE, 5.);
let b = BoundingSphere::new(Vec3::new(5.5, 1., 1.), 1.);
assert!(!a.contains(&b));
let b = BoundingSphere::new(Vec3::new(1., -3.5, 1.), 0.5);
assert!(a.contains(&b));
}
#[test]
fn contains_identical() {
let a = BoundingSphere::new(Vec3::ONE, 5.);
assert!(a.contains(&a));
}
#[test]
fn merge() {
// When merging two circles that don't contain each other, we find a center position that
// contains both
let a = BoundingSphere::new(Vec3::ONE, 5.);
let b = BoundingSphere::new(Vec3::new(1., 1., -4.), 1.);
let merged = a.merge(&b);
assert!((merged.center - Vec3A::new(1., 1., 0.5)).length() < f32::EPSILON);
assert!(ops::abs(merged.radius() - 5.5) < f32::EPSILON);
assert!(merged.contains(&a));
assert!(merged.contains(&b));
assert!(!a.contains(&merged));
assert!(!b.contains(&merged));
// When one circle contains the other circle, we use the bigger circle
let b = BoundingSphere::new(Vec3::ZERO, 3.);
assert!(a.contains(&b));
let merged = a.merge(&b);
assert_eq!(merged.center, a.center);
assert_eq!(merged.radius(), a.radius());
// When two circles are at the same point, we use the bigger radius
let b = BoundingSphere::new(Vec3::ONE, 6.);
let merged = a.merge(&b);
assert_eq!(merged.center, a.center);
assert_eq!(merged.radius(), b.radius());
}
#[test]
fn merge_identical() {
let a = BoundingSphere::new(Vec3::ONE, 5.);
let merged = a.merge(&a);
assert_eq!(merged.center, a.center);
assert_eq!(merged.radius(), a.radius());
}
#[test]
fn grow() {
let a = BoundingSphere::new(Vec3::ONE, 5.);
let padded = a.grow(1.25);
assert!(ops::abs(padded.radius() - 6.25) < f32::EPSILON);
assert!(padded.contains(&a));
assert!(!a.contains(&padded));
}
#[test]
fn shrink() {
let a = BoundingSphere::new(Vec3::ONE, 5.);
let shrunk = a.shrink(0.5);
assert!(ops::abs(shrunk.radius() - 4.5) < f32::EPSILON);
assert!(a.contains(&shrunk));
assert!(!shrunk.contains(&a));
}
#[test]
fn scale_around_center() {
let a = BoundingSphere::new(Vec3::ONE, 5.);
let scaled = a.scale_around_center(2.);
assert!(ops::abs(scaled.radius() - 10.) < f32::EPSILON);
assert!(!a.contains(&scaled));
assert!(scaled.contains(&a));
}
#[test]
fn transform() {
let a = BoundingSphere::new(Vec3::ONE, 5.0);
let transformed = a.transformed_by(
Vec3::new(2.0, -2.0, 4.0),
Quat::from_rotation_z(core::f32::consts::FRAC_PI_4),
);
assert_relative_eq!(
transformed.center,
Vec3A::new(2.0, core::f32::consts::SQRT_2 - 2.0, 5.0)
);
assert_eq!(transformed.radius(), 5.0);
}
#[test]
fn closest_point() {
let sphere = BoundingSphere::new(Vec3::ZERO, 1.0);
assert_eq!(sphere.closest_point(Vec3::X * 10.0), Vec3A::X);
assert_eq!(
sphere.closest_point(Vec3::NEG_ONE * 10.0),
Vec3A::NEG_ONE.normalize()
);
assert_eq!(
sphere.closest_point(Vec3::new(0.25, 0.1, 0.3)),
Vec3A::new(0.25, 0.1, 0.3)
);
}
#[test]
fn intersect_bounding_sphere() {
let sphere = BoundingSphere::new(Vec3::ZERO, 1.0);
assert!(sphere.intersects(&BoundingSphere::new(Vec3::ZERO, 1.0)));
assert!(sphere.intersects(&BoundingSphere::new(Vec3::ONE * 1.1, 1.0)));
assert!(sphere.intersects(&BoundingSphere::new(Vec3::NEG_ONE * 1.1, 1.0)));
assert!(!sphere.intersects(&BoundingSphere::new(Vec3::ONE * 1.2, 1.0)));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/bounding/bounded3d/primitive_impls.rs | crates/bevy_math/src/bounding/bounded3d/primitive_impls.rs | //! Contains [`Bounded3d`] implementations for [geometric primitives](crate::primitives).
use crate::{
bounding::{Bounded2d, BoundingCircle, BoundingVolume},
ops,
primitives::{
Capsule3d, Cone, ConicalFrustum, Cuboid, Cylinder, InfinitePlane3d, Line3d, Segment3d,
Sphere, Torus, Triangle2d, Triangle3d,
},
Isometry2d, Isometry3d, Mat3, Vec2, Vec3, Vec3A,
};
#[cfg(feature = "alloc")]
use crate::primitives::Polyline3d;
use super::{Aabb3d, Bounded3d, BoundingSphere};
impl Bounded3d for Sphere {
fn aabb_3d(&self, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
Aabb3d::new(isometry.translation, Vec3::splat(self.radius))
}
fn bounding_sphere(&self, isometry: impl Into<Isometry3d>) -> BoundingSphere {
let isometry = isometry.into();
BoundingSphere::new(isometry.translation, self.radius)
}
}
impl Bounded3d for InfinitePlane3d {
fn aabb_3d(&self, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
let normal = isometry.rotation * *self.normal;
let facing_x = normal == Vec3::X || normal == Vec3::NEG_X;
let facing_y = normal == Vec3::Y || normal == Vec3::NEG_Y;
let facing_z = normal == Vec3::Z || normal == Vec3::NEG_Z;
// Dividing `f32::MAX` by 2.0 is helpful so that we can do operations
// like growing or shrinking the AABB without breaking things.
let half_width = if facing_x { 0.0 } else { f32::MAX / 2.0 };
let half_height = if facing_y { 0.0 } else { f32::MAX / 2.0 };
let half_depth = if facing_z { 0.0 } else { f32::MAX / 2.0 };
let half_size = Vec3A::new(half_width, half_height, half_depth);
Aabb3d::new(isometry.translation, half_size)
}
fn bounding_sphere(&self, isometry: impl Into<Isometry3d>) -> BoundingSphere {
let isometry = isometry.into();
BoundingSphere::new(isometry.translation, f32::MAX / 2.0)
}
}
impl Bounded3d for Line3d {
fn aabb_3d(&self, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
let direction = isometry.rotation * *self.direction;
// Dividing `f32::MAX` by 2.0 is helpful so that we can do operations
// like growing or shrinking the AABB without breaking things.
let max = f32::MAX / 2.0;
let half_width = if direction.x == 0.0 { 0.0 } else { max };
let half_height = if direction.y == 0.0 { 0.0 } else { max };
let half_depth = if direction.z == 0.0 { 0.0 } else { max };
let half_size = Vec3A::new(half_width, half_height, half_depth);
Aabb3d::new(isometry.translation, half_size)
}
fn bounding_sphere(&self, isometry: impl Into<Isometry3d>) -> BoundingSphere {
let isometry = isometry.into();
BoundingSphere::new(isometry.translation, f32::MAX / 2.0)
}
}
impl Bounded3d for Segment3d {
fn aabb_3d(&self, isometry: impl Into<Isometry3d>) -> Aabb3d {
Aabb3d::from_point_cloud(isometry, [self.point1(), self.point2()].iter().copied())
}
fn bounding_sphere(&self, isometry: impl Into<Isometry3d>) -> BoundingSphere {
let isometry = isometry.into();
let local_sphere = BoundingSphere::new(self.center(), self.length() / 2.);
local_sphere.transformed_by(isometry.translation, isometry.rotation)
}
}
#[cfg(feature = "alloc")]
impl Bounded3d for Polyline3d {
fn aabb_3d(&self, isometry: impl Into<Isometry3d>) -> Aabb3d {
Aabb3d::from_point_cloud(isometry, self.vertices.iter().copied())
}
fn bounding_sphere(&self, isometry: impl Into<Isometry3d>) -> BoundingSphere {
BoundingSphere::from_point_cloud(isometry, &self.vertices)
}
}
impl Bounded3d for Cuboid {
fn aabb_3d(&self, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
// Compute the AABB of the rotated cuboid by transforming the half-size
// by an absolute rotation matrix.
let rot_mat = Mat3::from_quat(isometry.rotation);
let abs_rot_mat = Mat3::from_cols(
rot_mat.x_axis.abs(),
rot_mat.y_axis.abs(),
rot_mat.z_axis.abs(),
);
let half_size = abs_rot_mat * self.half_size;
Aabb3d::new(isometry.translation, half_size)
}
fn bounding_sphere(&self, isometry: impl Into<Isometry3d>) -> BoundingSphere {
let isometry = isometry.into();
BoundingSphere::new(isometry.translation, self.half_size.length())
}
}
impl Bounded3d for Cylinder {
fn aabb_3d(&self, isometry: impl Into<Isometry3d>) -> Aabb3d {
// Reference: http://iquilezles.org/articles/diskbbox/
let isometry = isometry.into();
let segment_dir = isometry.rotation * Vec3A::Y;
let top = segment_dir * self.half_height;
let bottom = -top;
let e = (Vec3A::ONE - segment_dir * segment_dir).max(Vec3A::ZERO);
let half_size = self.radius * Vec3A::new(ops::sqrt(e.x), ops::sqrt(e.y), ops::sqrt(e.z));
Aabb3d {
min: isometry.translation + (top - half_size).min(bottom - half_size),
max: isometry.translation + (top + half_size).max(bottom + half_size),
}
}
fn bounding_sphere(&self, isometry: impl Into<Isometry3d>) -> BoundingSphere {
let isometry = isometry.into();
let radius = ops::hypot(self.radius, self.half_height);
BoundingSphere::new(isometry.translation, radius)
}
}
impl Bounded3d for Capsule3d {
fn aabb_3d(&self, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
// Get the line segment between the hemispheres of the rotated capsule
let segment_dir = isometry.rotation * Vec3A::Y;
let top = segment_dir * self.half_length;
let bottom = -top;
// Expand the line segment by the capsule radius to get the capsule half-extents
let min = bottom.min(top) - Vec3A::splat(self.radius);
let max = bottom.max(top) + Vec3A::splat(self.radius);
Aabb3d {
min: min + isometry.translation,
max: max + isometry.translation,
}
}
fn bounding_sphere(&self, isometry: impl Into<Isometry3d>) -> BoundingSphere {
let isometry = isometry.into();
BoundingSphere::new(isometry.translation, self.radius + self.half_length)
}
}
impl Bounded3d for Cone {
fn aabb_3d(&self, isometry: impl Into<Isometry3d>) -> Aabb3d {
// Reference: http://iquilezles.org/articles/diskbbox/
let isometry = isometry.into();
let segment_dir = isometry.rotation * Vec3A::Y;
let top = segment_dir * 0.5 * self.height;
let bottom = -top;
let e = (Vec3A::ONE - segment_dir * segment_dir).max(Vec3A::ZERO);
let half_extents = Vec3A::new(ops::sqrt(e.x), ops::sqrt(e.y), ops::sqrt(e.z));
Aabb3d {
min: isometry.translation + top.min(bottom - self.radius * half_extents),
max: isometry.translation + top.max(bottom + self.radius * half_extents),
}
}
fn bounding_sphere(&self, isometry: impl Into<Isometry3d>) -> BoundingSphere {
let isometry = isometry.into();
// Get the triangular cross-section of the cone.
let half_height = 0.5 * self.height;
let triangle = Triangle2d::new(
half_height * Vec2::Y,
Vec2::new(-self.radius, -half_height),
Vec2::new(self.radius, -half_height),
);
// Because of circular symmetry, we can use the bounding circle of the triangle
// for the bounding sphere of the cone.
let BoundingCircle { circle, center } = triangle.bounding_circle(Isometry2d::IDENTITY);
BoundingSphere::new(
isometry.rotation * Vec3A::from(center.extend(0.0)) + isometry.translation,
circle.radius,
)
}
}
impl Bounded3d for ConicalFrustum {
fn aabb_3d(&self, isometry: impl Into<Isometry3d>) -> Aabb3d {
// Reference: http://iquilezles.org/articles/diskbbox/
let isometry = isometry.into();
let segment_dir = isometry.rotation * Vec3A::Y;
let top = segment_dir * 0.5 * self.height;
let bottom = -top;
let e = (Vec3A::ONE - segment_dir * segment_dir).max(Vec3A::ZERO);
let half_extents = Vec3A::new(ops::sqrt(e.x), ops::sqrt(e.y), ops::sqrt(e.z));
Aabb3d {
min: isometry.translation
+ (top - self.radius_top * half_extents)
.min(bottom - self.radius_bottom * half_extents),
max: isometry.translation
+ (top + self.radius_top * half_extents)
.max(bottom + self.radius_bottom * half_extents),
}
}
fn bounding_sphere(&self, isometry: impl Into<Isometry3d>) -> BoundingSphere {
let isometry = isometry.into();
let half_height = 0.5 * self.height;
// To compute the bounding sphere, we'll get the center and radius of the circumcircle
// passing through all four vertices of the trapezoidal cross-section of the conical frustum.
//
// If the circumcenter is inside the trapezoid, we can use that for the bounding sphere.
// Otherwise, we clamp it to the longer parallel side to get a more tightly fitting bounding sphere.
//
// The circumcenter is at the intersection of the bisectors perpendicular to the sides.
// For the isosceles trapezoid, the X coordinate is zero at the center, so a single bisector is enough.
//
// A
// *-------*
// / | \
// / | \
// AB / \ | / \
// / \ | / \
// / C \
// *-------------------*
// B
let a = Vec2::new(-self.radius_top, half_height);
let b = Vec2::new(-self.radius_bottom, -half_height);
let ab = a - b;
let ab_midpoint = b + 0.5 * ab;
let bisector = ab.perp();
// Compute intersection between bisector and vertical line at x = 0.
//
// x = ab_midpoint.x + t * bisector.x = 0
// y = ab_midpoint.y + t * bisector.y = ?
//
// Because ab_midpoint.y = 0 for our conical frustum, we get:
// y = t * bisector.y
//
// Solve x for t:
// t = -ab_midpoint.x / bisector.x
//
// Substitute t to solve for y:
// y = -ab_midpoint.x / bisector.x * bisector.y
let circumcenter_y = -ab_midpoint.x / bisector.x * bisector.y;
// If the circumcenter is outside the trapezoid, the bounding circle is too large.
// In those cases, we clamp it to the longer parallel side.
let (center, radius) = if circumcenter_y <= -half_height {
(Vec2::new(0.0, -half_height), self.radius_bottom)
} else if circumcenter_y >= half_height {
(Vec2::new(0.0, half_height), self.radius_top)
} else {
let circumcenter = Vec2::new(0.0, circumcenter_y);
// We can use the distance from an arbitrary vertex because they all lie on the circumcircle.
(circumcenter, a.distance(circumcenter))
};
BoundingSphere::new(
isometry.translation + isometry.rotation * Vec3A::from(center.extend(0.0)),
radius,
)
}
}
impl Bounded3d for Torus {
fn aabb_3d(&self, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
// Compute the AABB of a flat disc with the major radius of the torus.
// Reference: http://iquilezles.org/articles/diskbbox/
let normal = isometry.rotation * Vec3A::Y;
let e = (Vec3A::ONE - normal * normal).max(Vec3A::ZERO);
let disc_half_size =
self.major_radius * Vec3A::new(ops::sqrt(e.x), ops::sqrt(e.y), ops::sqrt(e.z));
// Expand the disc by the minor radius to get the torus half-size
let half_size = disc_half_size + Vec3A::splat(self.minor_radius);
Aabb3d::new(isometry.translation, half_size)
}
fn bounding_sphere(&self, isometry: impl Into<Isometry3d>) -> BoundingSphere {
let isometry = isometry.into();
BoundingSphere::new(isometry.translation, self.outer_radius())
}
}
impl Bounded3d for Triangle3d {
/// Get the bounding box of the triangle.
fn aabb_3d(&self, isometry: impl Into<Isometry3d>) -> Aabb3d {
let isometry = isometry.into();
let [a, b, c] = self.vertices;
let a = isometry.rotation * a;
let b = isometry.rotation * b;
let c = isometry.rotation * c;
let min = Vec3A::from(a.min(b).min(c));
let max = Vec3A::from(a.max(b).max(c));
let bounding_center = (max + min) / 2.0 + isometry.translation;
let half_extents = (max - min) / 2.0;
Aabb3d::new(bounding_center, half_extents)
}
/// Get the bounding sphere of the triangle.
///
/// The [`Triangle3d`] implements the minimal bounding sphere calculation. For acute triangles, the circumcenter is used as
/// the center of the sphere. For the others, the bounding sphere is the minimal sphere
/// that contains the largest side of the triangle.
fn bounding_sphere(&self, isometry: impl Into<Isometry3d>) -> BoundingSphere {
let isometry = isometry.into();
if self.is_degenerate() || self.is_obtuse() {
let (p1, p2) = self.largest_side();
let (p1, p2) = (Vec3A::from(p1), Vec3A::from(p2));
let mid_point = (p1 + p2) / 2.0;
let radius = mid_point.distance(p1);
BoundingSphere::new(mid_point + isometry.translation, radius)
} else {
let [a, _, _] = self.vertices;
let circumcenter = self.circumcenter();
let radius = circumcenter.distance(a);
BoundingSphere::new(Vec3A::from(circumcenter) + isometry.translation, radius)
}
}
}
#[cfg(test)]
mod tests {
use crate::{bounding::BoundingVolume, ops, Isometry3d};
use glam::{Quat, Vec3, Vec3A};
use crate::{
bounding::Bounded3d,
primitives::{
Capsule3d, Cone, ConicalFrustum, Cuboid, Cylinder, InfinitePlane3d, Line3d, Polyline3d,
Segment3d, Sphere, Torus, Triangle3d,
},
Dir3,
};
#[test]
fn sphere() {
let sphere = Sphere { radius: 1.0 };
let translation = Vec3::new(2.0, 1.0, 0.0);
let aabb = sphere.aabb_3d(translation);
assert_eq!(aabb.min, Vec3A::new(1.0, 0.0, -1.0));
assert_eq!(aabb.max, Vec3A::new(3.0, 2.0, 1.0));
let bounding_sphere = sphere.bounding_sphere(translation);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(bounding_sphere.radius(), 1.0);
}
#[test]
fn plane() {
let translation = Vec3::new(2.0, 1.0, 0.0);
let aabb1 = InfinitePlane3d::new(Vec3::X).aabb_3d(translation);
assert_eq!(aabb1.min, Vec3A::new(2.0, -f32::MAX / 2.0, -f32::MAX / 2.0));
assert_eq!(aabb1.max, Vec3A::new(2.0, f32::MAX / 2.0, f32::MAX / 2.0));
let aabb2 = InfinitePlane3d::new(Vec3::Y).aabb_3d(translation);
assert_eq!(aabb2.min, Vec3A::new(-f32::MAX / 2.0, 1.0, -f32::MAX / 2.0));
assert_eq!(aabb2.max, Vec3A::new(f32::MAX / 2.0, 1.0, f32::MAX / 2.0));
let aabb3 = InfinitePlane3d::new(Vec3::Z).aabb_3d(translation);
assert_eq!(aabb3.min, Vec3A::new(-f32::MAX / 2.0, -f32::MAX / 2.0, 0.0));
assert_eq!(aabb3.max, Vec3A::new(f32::MAX / 2.0, f32::MAX / 2.0, 0.0));
let aabb4 = InfinitePlane3d::new(Vec3::ONE).aabb_3d(translation);
assert_eq!(aabb4.min, Vec3A::splat(-f32::MAX / 2.0));
assert_eq!(aabb4.max, Vec3A::splat(f32::MAX / 2.0));
let bounding_sphere = InfinitePlane3d::new(Vec3::Y).bounding_sphere(translation);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(bounding_sphere.radius(), f32::MAX / 2.0);
}
#[test]
fn line() {
let translation = Vec3::new(2.0, 1.0, 0.0);
let aabb1 = Line3d { direction: Dir3::Y }.aabb_3d(translation);
assert_eq!(aabb1.min, Vec3A::new(2.0, -f32::MAX / 2.0, 0.0));
assert_eq!(aabb1.max, Vec3A::new(2.0, f32::MAX / 2.0, 0.0));
let aabb2 = Line3d { direction: Dir3::X }.aabb_3d(translation);
assert_eq!(aabb2.min, Vec3A::new(-f32::MAX / 2.0, 1.0, 0.0));
assert_eq!(aabb2.max, Vec3A::new(f32::MAX / 2.0, 1.0, 0.0));
let aabb3 = Line3d { direction: Dir3::Z }.aabb_3d(translation);
assert_eq!(aabb3.min, Vec3A::new(2.0, 1.0, -f32::MAX / 2.0));
assert_eq!(aabb3.max, Vec3A::new(2.0, 1.0, f32::MAX / 2.0));
let aabb4 = Line3d {
direction: Dir3::from_xyz(1.0, 1.0, 1.0).unwrap(),
}
.aabb_3d(translation);
assert_eq!(aabb4.min, Vec3A::splat(-f32::MAX / 2.0));
assert_eq!(aabb4.max, Vec3A::splat(f32::MAX / 2.0));
let bounding_sphere = Line3d { direction: Dir3::Y }.bounding_sphere(translation);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(bounding_sphere.radius(), f32::MAX / 2.0);
}
#[test]
fn segment() {
let segment = Segment3d::new(Vec3::new(-1.0, -0.5, 0.0), Vec3::new(1.0, 0.5, 0.0));
let translation = Vec3::new(2.0, 1.0, 0.0);
let aabb = segment.aabb_3d(translation);
assert_eq!(aabb.min, Vec3A::new(1.0, 0.5, 0.0));
assert_eq!(aabb.max, Vec3A::new(3.0, 1.5, 0.0));
let bounding_sphere = segment.bounding_sphere(translation);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(bounding_sphere.radius(), ops::hypot(1.0, 0.5));
}
#[test]
fn polyline() {
let polyline = Polyline3d::new([
Vec3::ONE,
Vec3::new(-1.0, 1.0, 1.0),
Vec3::NEG_ONE,
Vec3::new(1.0, -1.0, -1.0),
]);
let translation = Vec3::new(2.0, 1.0, 0.0);
let aabb = polyline.aabb_3d(translation);
assert_eq!(aabb.min, Vec3A::new(1.0, 0.0, -1.0));
assert_eq!(aabb.max, Vec3A::new(3.0, 2.0, 1.0));
let bounding_sphere = polyline.bounding_sphere(translation);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(
bounding_sphere.radius(),
ops::hypot(ops::hypot(1.0, 1.0), 1.0)
);
}
#[test]
fn cuboid() {
let cuboid = Cuboid::new(2.0, 1.0, 1.0);
let translation = Vec3::new(2.0, 1.0, 0.0);
let aabb = cuboid.aabb_3d(Isometry3d::new(
translation,
Quat::from_rotation_z(core::f32::consts::FRAC_PI_4),
));
let expected_half_size = Vec3A::new(1.0606601, 1.0606601, 0.5);
assert_eq!(aabb.min, Vec3A::from(translation) - expected_half_size);
assert_eq!(aabb.max, Vec3A::from(translation) + expected_half_size);
let bounding_sphere = cuboid.bounding_sphere(translation);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(
bounding_sphere.radius(),
ops::hypot(ops::hypot(1.0, 0.5), 0.5)
);
}
#[test]
fn cylinder() {
let cylinder = Cylinder::new(0.5, 2.0);
let translation = Vec3::new(2.0, 1.0, 0.0);
let aabb = cylinder.aabb_3d(translation);
assert_eq!(
aabb.min,
Vec3A::from(translation) - Vec3A::new(0.5, 1.0, 0.5)
);
assert_eq!(
aabb.max,
Vec3A::from(translation) + Vec3A::new(0.5, 1.0, 0.5)
);
let bounding_sphere = cylinder.bounding_sphere(translation);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(bounding_sphere.radius(), ops::hypot(1.0, 0.5));
}
#[test]
fn capsule() {
let capsule = Capsule3d::new(0.5, 2.0);
let translation = Vec3::new(2.0, 1.0, 0.0);
let aabb = capsule.aabb_3d(translation);
assert_eq!(
aabb.min,
Vec3A::from(translation) - Vec3A::new(0.5, 1.5, 0.5)
);
assert_eq!(
aabb.max,
Vec3A::from(translation) + Vec3A::new(0.5, 1.5, 0.5)
);
let bounding_sphere = capsule.bounding_sphere(translation);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(bounding_sphere.radius(), 1.5);
}
#[test]
fn cone() {
let cone = Cone {
radius: 1.0,
height: 2.0,
};
let translation = Vec3::new(2.0, 1.0, 0.0);
let aabb = cone.aabb_3d(translation);
assert_eq!(aabb.min, Vec3A::new(1.0, 0.0, -1.0));
assert_eq!(aabb.max, Vec3A::new(3.0, 2.0, 1.0));
let bounding_sphere = cone.bounding_sphere(translation);
assert_eq!(
bounding_sphere.center,
Vec3A::from(translation) + Vec3A::NEG_Y * 0.25
);
assert_eq!(bounding_sphere.radius(), 1.25);
}
#[test]
fn conical_frustum() {
let conical_frustum = ConicalFrustum {
radius_top: 0.5,
radius_bottom: 1.0,
height: 2.0,
};
let translation = Vec3::new(2.0, 1.0, 0.0);
let aabb = conical_frustum.aabb_3d(translation);
assert_eq!(aabb.min, Vec3A::new(1.0, 0.0, -1.0));
assert_eq!(aabb.max, Vec3A::new(3.0, 2.0, 1.0));
let bounding_sphere = conical_frustum.bounding_sphere(translation);
assert_eq!(
bounding_sphere.center,
Vec3A::from(translation) + Vec3A::NEG_Y * 0.1875
);
assert_eq!(bounding_sphere.radius(), 1.2884705);
}
#[test]
fn wide_conical_frustum() {
let conical_frustum = ConicalFrustum {
radius_top: 0.5,
radius_bottom: 5.0,
height: 1.0,
};
let translation = Vec3::new(2.0, 1.0, 0.0);
let aabb = conical_frustum.aabb_3d(translation);
assert_eq!(aabb.min, Vec3A::new(-3.0, 0.5, -5.0));
assert_eq!(aabb.max, Vec3A::new(7.0, 1.5, 5.0));
// For wide conical frusta like this, the circumcenter can be outside the frustum,
// so the center and radius should be clamped to the longest side.
let bounding_sphere = conical_frustum.bounding_sphere(translation);
assert_eq!(
bounding_sphere.center,
Vec3A::from(translation) + Vec3A::NEG_Y * 0.5
);
assert_eq!(bounding_sphere.radius(), 5.0);
}
#[test]
fn torus() {
let torus = Torus {
minor_radius: 0.5,
major_radius: 1.0,
};
let translation = Vec3::new(2.0, 1.0, 0.0);
let aabb = torus.aabb_3d(translation);
assert_eq!(aabb.min, Vec3A::new(0.5, 0.5, -1.5));
assert_eq!(aabb.max, Vec3A::new(3.5, 1.5, 1.5));
let bounding_sphere = torus.bounding_sphere(translation);
assert_eq!(bounding_sphere.center, translation.into());
assert_eq!(bounding_sphere.radius(), 1.5);
}
#[test]
fn triangle3d() {
let zero_degenerate_triangle = Triangle3d::new(Vec3::ZERO, Vec3::ZERO, Vec3::ZERO);
let br = zero_degenerate_triangle.aabb_3d(Isometry3d::IDENTITY);
assert_eq!(
br.center(),
Vec3::ZERO.into(),
"incorrect bounding box center"
);
assert_eq!(
br.half_size(),
Vec3::ZERO.into(),
"incorrect bounding box half extents"
);
let bs = zero_degenerate_triangle.bounding_sphere(Isometry3d::IDENTITY);
assert_eq!(
bs.center,
Vec3::ZERO.into(),
"incorrect bounding sphere center"
);
assert_eq!(bs.sphere.radius, 0.0, "incorrect bounding sphere radius");
let dup_degenerate_triangle = Triangle3d::new(Vec3::ZERO, Vec3::X, Vec3::X);
let bs = dup_degenerate_triangle.bounding_sphere(Isometry3d::IDENTITY);
assert_eq!(
bs.center,
Vec3::new(0.5, 0.0, 0.0).into(),
"incorrect bounding sphere center"
);
assert_eq!(bs.sphere.radius, 0.5, "incorrect bounding sphere radius");
let br = dup_degenerate_triangle.aabb_3d(Isometry3d::IDENTITY);
assert_eq!(
br.center(),
Vec3::new(0.5, 0.0, 0.0).into(),
"incorrect bounding box center"
);
assert_eq!(
br.half_size(),
Vec3::new(0.5, 0.0, 0.0).into(),
"incorrect bounding box half extents"
);
let collinear_degenerate_triangle = Triangle3d::new(Vec3::NEG_X, Vec3::ZERO, Vec3::X);
let bs = collinear_degenerate_triangle.bounding_sphere(Isometry3d::IDENTITY);
assert_eq!(
bs.center,
Vec3::ZERO.into(),
"incorrect bounding sphere center"
);
assert_eq!(bs.sphere.radius, 1.0, "incorrect bounding sphere radius");
let br = collinear_degenerate_triangle.aabb_3d(Isometry3d::IDENTITY);
assert_eq!(
br.center(),
Vec3::ZERO.into(),
"incorrect bounding box center"
);
assert_eq!(
br.half_size(),
Vec3::new(1.0, 0.0, 0.0).into(),
"incorrect bounding box half extents"
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/bounding/bounded2d/mod.rs | crates/bevy_math/src/bounding/bounded2d/mod.rs | mod primitive_impls;
use super::{BoundingVolume, IntersectsVolume};
use crate::{
ops,
prelude::{Mat2, Rot2, Vec2},
FloatPow, Isometry2d,
};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
#[cfg(all(feature = "bevy_reflect", feature = "serialize"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};
/// Computes the geometric center of the given set of points.
#[inline]
fn point_cloud_2d_center(points: &[Vec2]) -> Vec2 {
assert!(
!points.is_empty(),
"cannot compute the center of an empty set of points"
);
let denom = 1.0 / points.len() as f32;
points.iter().fold(Vec2::ZERO, |acc, point| acc + *point) * denom
}
/// A trait with methods that return 2D bounding volumes for a shape.
pub trait Bounded2d {
/// Get an axis-aligned bounding box for the shape translated and rotated by the given isometry.
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d;
/// Get a bounding circle for the shape translated and rotated by the given isometry.
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle;
}
/// A 2D axis-aligned bounding box, or bounding rectangle
#[doc(alias = "BoundingRectangle")]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
#[cfg_attr(feature = "serialize", derive(Serialize), derive(Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Aabb2d {
/// The minimum, conventionally bottom-left, point of the box
pub min: Vec2,
/// The maximum, conventionally top-right, point of the box
pub max: Vec2,
}
impl Aabb2d {
/// Constructs an AABB from its center and half-size.
#[inline]
pub fn new(center: Vec2, half_size: Vec2) -> Self {
debug_assert!(half_size.x >= 0.0 && half_size.y >= 0.0);
Self {
min: center - half_size,
max: center + half_size,
}
}
/// Computes the smallest [`Aabb2d`] containing the given set of points,
/// transformed by the rotation and translation of the given isometry.
///
/// # Panics
///
/// Panics if the given set of points is empty.
#[inline]
pub fn from_point_cloud(isometry: impl Into<Isometry2d>, points: &[Vec2]) -> Aabb2d {
let isometry = isometry.into();
// Transform all points by rotation
let mut iter = points.iter().map(|point| isometry.rotation * *point);
let first = iter
.next()
.expect("point cloud must contain at least one point for Aabb2d construction");
let (min, max) = iter.fold((first, first), |(prev_min, prev_max), point| {
(point.min(prev_min), point.max(prev_max))
});
Aabb2d {
min: min + isometry.translation,
max: max + isometry.translation,
}
}
/// Computes the smallest [`BoundingCircle`] containing this [`Aabb2d`].
#[inline]
pub fn bounding_circle(&self) -> BoundingCircle {
let radius = self.min.distance(self.max) / 2.0;
BoundingCircle::new(self.center(), radius)
}
/// Finds the point on the AABB that is closest to the given `point`.
///
/// If the point is outside the AABB, the returned point will be on the perimeter of the AABB.
/// Otherwise, it will be inside the AABB and returned as is.
#[inline]
pub fn closest_point(&self, point: Vec2) -> Vec2 {
// Clamp point coordinates to the AABB
point.clamp(self.min, self.max)
}
}
impl BoundingVolume for Aabb2d {
type Translation = Vec2;
type Rotation = Rot2;
type HalfSize = Vec2;
#[inline]
fn center(&self) -> Self::Translation {
(self.min + self.max) / 2.
}
#[inline]
fn half_size(&self) -> Self::HalfSize {
(self.max - self.min) / 2.
}
#[inline]
fn visible_area(&self) -> f32 {
let b = (self.max - self.min).max(Vec2::ZERO);
b.x * b.y
}
#[inline]
fn contains(&self, other: &Self) -> bool {
other.min.x >= self.min.x
&& other.min.y >= self.min.y
&& other.max.x <= self.max.x
&& other.max.y <= self.max.y
}
#[inline]
fn merge(&self, other: &Self) -> Self {
Self {
min: self.min.min(other.min),
max: self.max.max(other.max),
}
}
#[inline]
fn grow(&self, amount: impl Into<Self::HalfSize>) -> Self {
let amount = amount.into();
let b = Self {
min: self.min - amount,
max: self.max + amount,
};
debug_assert!(b.min.x <= b.max.x && b.min.y <= b.max.y);
b
}
#[inline]
fn shrink(&self, amount: impl Into<Self::HalfSize>) -> Self {
let amount = amount.into();
let b = Self {
min: self.min + amount,
max: self.max - amount,
};
debug_assert!(b.min.x <= b.max.x && b.min.y <= b.max.y);
b
}
#[inline]
fn scale_around_center(&self, scale: impl Into<Self::HalfSize>) -> Self {
let scale = scale.into();
let b = Self {
min: self.center() - (self.half_size() * scale),
max: self.center() + (self.half_size() * scale),
};
debug_assert!(b.min.x <= b.max.x && b.min.y <= b.max.y);
b
}
/// Transforms the bounding volume by first rotating it around the origin and then applying a translation.
///
/// The result is an Axis-Aligned Bounding Box that encompasses the rotated shape.
///
/// Note that the result may not be as tightly fitting as the original, and repeated rotations
/// can cause the AABB to grow indefinitely. Avoid applying multiple rotations to the same AABB,
/// and consider storing the original AABB and rotating that every time instead.
#[inline]
fn transformed_by(
mut self,
translation: impl Into<Self::Translation>,
rotation: impl Into<Self::Rotation>,
) -> Self {
self.transform_by(translation, rotation);
self
}
/// Transforms the bounding volume by first rotating it around the origin and then applying a translation.
///
/// The result is an Axis-Aligned Bounding Box that encompasses the rotated shape.
///
/// Note that the result may not be as tightly fitting as the original, and repeated rotations
/// can cause the AABB to grow indefinitely. Avoid applying multiple rotations to the same AABB,
/// and consider storing the original AABB and rotating that every time instead.
#[inline]
fn transform_by(
&mut self,
translation: impl Into<Self::Translation>,
rotation: impl Into<Self::Rotation>,
) {
self.rotate_by(rotation);
self.translate_by(translation);
}
#[inline]
fn translate_by(&mut self, translation: impl Into<Self::Translation>) {
let translation = translation.into();
self.min += translation;
self.max += translation;
}
/// Rotates the bounding volume around the origin by the given rotation.
///
/// The result is an Axis-Aligned Bounding Box that encompasses the rotated shape.
///
/// Note that the result may not be as tightly fitting as the original, and repeated rotations
/// can cause the AABB to grow indefinitely. Avoid applying multiple rotations to the same AABB,
/// and consider storing the original AABB and rotating that every time instead.
#[inline]
fn rotated_by(mut self, rotation: impl Into<Self::Rotation>) -> Self {
self.rotate_by(rotation);
self
}
/// Rotates the bounding volume around the origin by the given rotation.
///
/// The result is an Axis-Aligned Bounding Box that encompasses the rotated shape.
///
/// Note that the result may not be as tightly fitting as the original, and repeated rotations
/// can cause the AABB to grow indefinitely. Avoid applying multiple rotations to the same AABB,
/// and consider storing the original AABB and rotating that every time instead.
#[inline]
fn rotate_by(&mut self, rotation: impl Into<Self::Rotation>) {
let rot_mat = Mat2::from(rotation.into());
let half_size = rot_mat.abs() * self.half_size();
*self = Self::new(rot_mat * self.center(), half_size);
}
}
impl IntersectsVolume<Self> for Aabb2d {
#[inline]
fn intersects(&self, other: &Self) -> bool {
let x_overlaps = self.min.x <= other.max.x && self.max.x >= other.min.x;
let y_overlaps = self.min.y <= other.max.y && self.max.y >= other.min.y;
x_overlaps && y_overlaps
}
}
impl IntersectsVolume<BoundingCircle> for Aabb2d {
#[inline]
fn intersects(&self, circle: &BoundingCircle) -> bool {
let closest_point = self.closest_point(circle.center);
let distance_squared = circle.center.distance_squared(closest_point);
let radius_squared = circle.radius().squared();
distance_squared <= radius_squared
}
}
#[cfg(test)]
mod aabb2d_tests {
use approx::assert_relative_eq;
use super::Aabb2d;
use crate::{
bounding::{BoundingCircle, BoundingVolume, IntersectsVolume},
ops, Vec2,
};
#[test]
fn center() {
let aabb = Aabb2d {
min: Vec2::new(-0.5, -1.),
max: Vec2::new(1., 1.),
};
assert!((aabb.center() - Vec2::new(0.25, 0.)).length() < f32::EPSILON);
let aabb = Aabb2d {
min: Vec2::new(5., -10.),
max: Vec2::new(10., -5.),
};
assert!((aabb.center() - Vec2::new(7.5, -7.5)).length() < f32::EPSILON);
}
#[test]
fn half_size() {
let aabb = Aabb2d {
min: Vec2::new(-0.5, -1.),
max: Vec2::new(1., 1.),
};
let half_size = aabb.half_size();
assert!((half_size - Vec2::new(0.75, 1.)).length() < f32::EPSILON);
}
#[test]
fn area() {
let aabb = Aabb2d {
min: Vec2::new(-1., -1.),
max: Vec2::new(1., 1.),
};
assert!(ops::abs(aabb.visible_area() - 4.) < f32::EPSILON);
let aabb = Aabb2d {
min: Vec2::new(0., 0.),
max: Vec2::new(1., 0.5),
};
assert!(ops::abs(aabb.visible_area() - 0.5) < f32::EPSILON);
}
#[test]
fn contains() {
let a = Aabb2d {
min: Vec2::new(-1., -1.),
max: Vec2::new(1., 1.),
};
let b = Aabb2d {
min: Vec2::new(-2., -1.),
max: Vec2::new(1., 1.),
};
assert!(!a.contains(&b));
let b = Aabb2d {
min: Vec2::new(-0.25, -0.8),
max: Vec2::new(1., 1.),
};
assert!(a.contains(&b));
}
#[test]
fn merge() {
let a = Aabb2d {
min: Vec2::new(-1., -1.),
max: Vec2::new(1., 0.5),
};
let b = Aabb2d {
min: Vec2::new(-2., -0.5),
max: Vec2::new(0.75, 1.),
};
let merged = a.merge(&b);
assert!((merged.min - Vec2::new(-2., -1.)).length() < f32::EPSILON);
assert!((merged.max - Vec2::new(1., 1.)).length() < f32::EPSILON);
assert!(merged.contains(&a));
assert!(merged.contains(&b));
assert!(!a.contains(&merged));
assert!(!b.contains(&merged));
}
#[test]
fn grow() {
let a = Aabb2d {
min: Vec2::new(-1., -1.),
max: Vec2::new(1., 1.),
};
let padded = a.grow(Vec2::ONE);
assert!((padded.min - Vec2::new(-2., -2.)).length() < f32::EPSILON);
assert!((padded.max - Vec2::new(2., 2.)).length() < f32::EPSILON);
assert!(padded.contains(&a));
assert!(!a.contains(&padded));
}
#[test]
fn shrink() {
let a = Aabb2d {
min: Vec2::new(-2., -2.),
max: Vec2::new(2., 2.),
};
let shrunk = a.shrink(Vec2::ONE);
assert!((shrunk.min - Vec2::new(-1., -1.)).length() < f32::EPSILON);
assert!((shrunk.max - Vec2::new(1., 1.)).length() < f32::EPSILON);
assert!(a.contains(&shrunk));
assert!(!shrunk.contains(&a));
}
#[test]
fn scale_around_center() {
let a = Aabb2d {
min: Vec2::NEG_ONE,
max: Vec2::ONE,
};
let scaled = a.scale_around_center(Vec2::splat(2.));
assert!((scaled.min - Vec2::splat(-2.)).length() < f32::EPSILON);
assert!((scaled.max - Vec2::splat(2.)).length() < f32::EPSILON);
assert!(!a.contains(&scaled));
assert!(scaled.contains(&a));
}
#[test]
fn rotate() {
let a = Aabb2d {
min: Vec2::new(-2.0, -2.0),
max: Vec2::new(2.0, 2.0),
};
let rotated = a.rotated_by(core::f32::consts::PI);
assert_relative_eq!(rotated.min, a.min);
assert_relative_eq!(rotated.max, a.max);
}
#[test]
fn transform() {
let a = Aabb2d {
min: Vec2::new(-2.0, -2.0),
max: Vec2::new(2.0, 2.0),
};
let transformed = a.transformed_by(Vec2::new(2.0, -2.0), core::f32::consts::FRAC_PI_4);
let half_length = ops::hypot(2.0, 2.0);
assert_eq!(
transformed.min,
Vec2::new(2.0 - half_length, -half_length - 2.0)
);
assert_eq!(
transformed.max,
Vec2::new(2.0 + half_length, half_length - 2.0)
);
}
#[test]
fn closest_point() {
let aabb = Aabb2d {
min: Vec2::NEG_ONE,
max: Vec2::ONE,
};
assert_eq!(aabb.closest_point(Vec2::X * 10.0), Vec2::X);
assert_eq!(aabb.closest_point(Vec2::NEG_ONE * 10.0), Vec2::NEG_ONE);
assert_eq!(
aabb.closest_point(Vec2::new(0.25, 0.1)),
Vec2::new(0.25, 0.1)
);
}
#[test]
fn intersect_aabb() {
let aabb = Aabb2d {
min: Vec2::NEG_ONE,
max: Vec2::ONE,
};
assert!(aabb.intersects(&aabb));
assert!(aabb.intersects(&Aabb2d {
min: Vec2::new(0.5, 0.5),
max: Vec2::new(2.0, 2.0),
}));
assert!(aabb.intersects(&Aabb2d {
min: Vec2::new(-2.0, -2.0),
max: Vec2::new(-0.5, -0.5),
}));
assert!(!aabb.intersects(&Aabb2d {
min: Vec2::new(1.1, 0.0),
max: Vec2::new(2.0, 0.5),
}));
}
#[test]
fn intersect_bounding_circle() {
let aabb = Aabb2d {
min: Vec2::NEG_ONE,
max: Vec2::ONE,
};
assert!(aabb.intersects(&BoundingCircle::new(Vec2::ZERO, 1.0)));
assert!(aabb.intersects(&BoundingCircle::new(Vec2::ONE * 1.5, 1.0)));
assert!(aabb.intersects(&BoundingCircle::new(Vec2::NEG_ONE * 1.5, 1.0)));
assert!(!aabb.intersects(&BoundingCircle::new(Vec2::ONE * 1.75, 1.0)));
}
}
use crate::primitives::Circle;
/// A bounding circle
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
#[cfg_attr(feature = "serialize", derive(Serialize), derive(Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct BoundingCircle {
/// The center of the bounding circle
pub center: Vec2,
/// The circle
pub circle: Circle,
}
impl BoundingCircle {
/// Constructs a bounding circle from its center and radius.
#[inline]
pub fn new(center: Vec2, radius: f32) -> Self {
debug_assert!(radius >= 0.);
Self {
center,
circle: Circle { radius },
}
}
/// Computes a [`BoundingCircle`] containing the given set of points,
/// transformed by the rotation and translation of the given isometry.
///
/// The bounding circle is not guaranteed to be the smallest possible.
#[inline]
pub fn from_point_cloud(isometry: impl Into<Isometry2d>, points: &[Vec2]) -> BoundingCircle {
let isometry = isometry.into();
let center = point_cloud_2d_center(points);
let mut radius_squared = 0.0;
for point in points {
// Get squared version to avoid unnecessary sqrt calls
let distance_squared = point.distance_squared(center);
if distance_squared > radius_squared {
radius_squared = distance_squared;
}
}
BoundingCircle::new(isometry * center, ops::sqrt(radius_squared))
}
/// Get the radius of the bounding circle
#[inline]
pub fn radius(&self) -> f32 {
self.circle.radius
}
/// Computes the smallest [`Aabb2d`] containing this [`BoundingCircle`].
#[inline]
pub fn aabb_2d(&self) -> Aabb2d {
Aabb2d {
min: self.center - Vec2::splat(self.radius()),
max: self.center + Vec2::splat(self.radius()),
}
}
/// Finds the point on the bounding circle that is closest to the given `point`.
///
/// If the point is outside the circle, the returned point will be on the perimeter of the circle.
/// Otherwise, it will be inside the circle and returned as is.
#[inline]
pub fn closest_point(&self, point: Vec2) -> Vec2 {
self.circle.closest_point(point - self.center) + self.center
}
}
impl BoundingVolume for BoundingCircle {
type Translation = Vec2;
type Rotation = Rot2;
type HalfSize = f32;
#[inline]
fn center(&self) -> Self::Translation {
self.center
}
#[inline]
fn half_size(&self) -> Self::HalfSize {
self.radius()
}
#[inline]
fn visible_area(&self) -> f32 {
core::f32::consts::PI * self.radius() * self.radius()
}
#[inline]
fn contains(&self, other: &Self) -> bool {
let diff = self.radius() - other.radius();
self.center.distance_squared(other.center) <= ops::copysign(diff.squared(), diff)
}
#[inline]
fn merge(&self, other: &Self) -> Self {
let diff = other.center - self.center;
let length = diff.length();
if self.radius() >= length + other.radius() {
return *self;
}
if other.radius() >= length + self.radius() {
return *other;
}
let dir = diff / length;
Self::new(
(self.center + other.center) / 2. + dir * ((other.radius() - self.radius()) / 2.),
(length + self.radius() + other.radius()) / 2.,
)
}
#[inline]
fn grow(&self, amount: impl Into<Self::HalfSize>) -> Self {
let amount = amount.into();
debug_assert!(amount >= 0.);
Self::new(self.center, self.radius() + amount)
}
#[inline]
fn shrink(&self, amount: impl Into<Self::HalfSize>) -> Self {
let amount = amount.into();
debug_assert!(amount >= 0.);
debug_assert!(self.radius() >= amount);
Self::new(self.center, self.radius() - amount)
}
#[inline]
fn scale_around_center(&self, scale: impl Into<Self::HalfSize>) -> Self {
let scale = scale.into();
debug_assert!(scale >= 0.);
Self::new(self.center, self.radius() * scale)
}
#[inline]
fn translate_by(&mut self, translation: impl Into<Self::Translation>) {
self.center += translation.into();
}
#[inline]
fn rotate_by(&mut self, rotation: impl Into<Self::Rotation>) {
let rotation: Rot2 = rotation.into();
self.center = rotation * self.center;
}
}
impl IntersectsVolume<Self> for BoundingCircle {
#[inline]
fn intersects(&self, other: &Self) -> bool {
let center_distance_squared = self.center.distance_squared(other.center);
let radius_sum_squared = (self.radius() + other.radius()).squared();
center_distance_squared <= radius_sum_squared
}
}
impl IntersectsVolume<Aabb2d> for BoundingCircle {
#[inline]
fn intersects(&self, aabb: &Aabb2d) -> bool {
aabb.intersects(self)
}
}
#[cfg(test)]
mod bounding_circle_tests {
use super::BoundingCircle;
use crate::{
bounding::{BoundingVolume, IntersectsVolume},
ops, Vec2,
};
#[test]
fn area() {
let circle = BoundingCircle::new(Vec2::ONE, 5.);
// Since this number is messy we check it with a higher threshold
assert!(ops::abs(circle.visible_area() - 78.5398) < 0.001);
}
#[test]
fn contains() {
let a = BoundingCircle::new(Vec2::ONE, 5.);
let b = BoundingCircle::new(Vec2::new(5.5, 1.), 1.);
assert!(!a.contains(&b));
let b = BoundingCircle::new(Vec2::new(1., -3.5), 0.5);
assert!(a.contains(&b));
}
#[test]
fn contains_identical() {
let a = BoundingCircle::new(Vec2::ONE, 5.);
assert!(a.contains(&a));
}
#[test]
fn merge() {
// When merging two circles that don't contain each other, we find a center position that
// contains both
let a = BoundingCircle::new(Vec2::ONE, 5.);
let b = BoundingCircle::new(Vec2::new(1., -4.), 1.);
let merged = a.merge(&b);
assert!((merged.center - Vec2::new(1., 0.5)).length() < f32::EPSILON);
assert!(ops::abs(merged.radius() - 5.5) < f32::EPSILON);
assert!(merged.contains(&a));
assert!(merged.contains(&b));
assert!(!a.contains(&merged));
assert!(!b.contains(&merged));
// When one circle contains the other circle, we use the bigger circle
let b = BoundingCircle::new(Vec2::ZERO, 3.);
assert!(a.contains(&b));
let merged = a.merge(&b);
assert_eq!(merged.center, a.center);
assert_eq!(merged.radius(), a.radius());
// When two circles are at the same point, we use the bigger radius
let b = BoundingCircle::new(Vec2::ONE, 6.);
let merged = a.merge(&b);
assert_eq!(merged.center, a.center);
assert_eq!(merged.radius(), b.radius());
}
#[test]
fn merge_identical() {
let a = BoundingCircle::new(Vec2::ONE, 5.);
let merged = a.merge(&a);
assert_eq!(merged.center, a.center);
assert_eq!(merged.radius(), a.radius());
}
#[test]
fn grow() {
let a = BoundingCircle::new(Vec2::ONE, 5.);
let padded = a.grow(1.25);
assert!(ops::abs(padded.radius() - 6.25) < f32::EPSILON);
assert!(padded.contains(&a));
assert!(!a.contains(&padded));
}
#[test]
fn shrink() {
let a = BoundingCircle::new(Vec2::ONE, 5.);
let shrunk = a.shrink(0.5);
assert!(ops::abs(shrunk.radius() - 4.5) < f32::EPSILON);
assert!(a.contains(&shrunk));
assert!(!shrunk.contains(&a));
}
#[test]
fn scale_around_center() {
let a = BoundingCircle::new(Vec2::ONE, 5.);
let scaled = a.scale_around_center(2.);
assert!(ops::abs(scaled.radius() - 10.) < f32::EPSILON);
assert!(!a.contains(&scaled));
assert!(scaled.contains(&a));
}
#[test]
fn transform() {
let a = BoundingCircle::new(Vec2::ONE, 5.0);
let transformed = a.transformed_by(Vec2::new(2.0, -2.0), core::f32::consts::FRAC_PI_4);
assert_eq!(
transformed.center,
Vec2::new(2.0, core::f32::consts::SQRT_2 - 2.0)
);
assert_eq!(transformed.radius(), 5.0);
}
#[test]
fn closest_point() {
let circle = BoundingCircle::new(Vec2::ZERO, 1.0);
assert_eq!(circle.closest_point(Vec2::X * 10.0), Vec2::X);
assert_eq!(
circle.closest_point(Vec2::NEG_ONE * 10.0),
Vec2::NEG_ONE.normalize()
);
assert_eq!(
circle.closest_point(Vec2::new(0.25, 0.1)),
Vec2::new(0.25, 0.1)
);
}
#[test]
fn intersect_bounding_circle() {
let circle = BoundingCircle::new(Vec2::ZERO, 1.0);
assert!(circle.intersects(&BoundingCircle::new(Vec2::ZERO, 1.0)));
assert!(circle.intersects(&BoundingCircle::new(Vec2::ONE * 1.25, 1.0)));
assert!(circle.intersects(&BoundingCircle::new(Vec2::NEG_ONE * 1.25, 1.0)));
assert!(!circle.intersects(&BoundingCircle::new(Vec2::ONE * 1.5, 1.0)));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/bounding/bounded2d/primitive_impls.rs | crates/bevy_math/src/bounding/bounded2d/primitive_impls.rs | //! Contains [`Bounded2d`] implementations for [geometric primitives](crate::primitives).
use crate::{
bounding::BoundingVolume,
ops,
primitives::{
Annulus, Arc2d, Capsule2d, Circle, CircularSector, CircularSegment, Ellipse, Line2d,
Plane2d, Primitive2d, Rectangle, RegularPolygon, Rhombus, Ring, Segment2d, Triangle2d,
},
Dir2, Isometry2d, Mat2, Rot2, Vec2,
};
use core::f32::consts::{FRAC_PI_2, PI, TAU};
#[cfg(feature = "alloc")]
use crate::primitives::{ConvexPolygon, Polygon, Polyline2d};
use arrayvec::ArrayVec;
use super::{Aabb2d, Bounded2d, BoundingCircle};
impl Bounded2d for Circle {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
let isometry = isometry.into();
Aabb2d::new(isometry.translation, Vec2::splat(self.radius))
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
let isometry = isometry.into();
BoundingCircle::new(isometry.translation, self.radius)
}
}
// Compute the axis-aligned bounding points of a rotated arc, used for computing the AABB of arcs and derived shapes.
// The return type has room for 7 points so that the CircularSector code can add an additional point.
#[inline]
fn arc_bounding_points(arc: Arc2d, rotation: impl Into<Rot2>) -> ArrayVec<Vec2, 7> {
// Otherwise, the extreme points will always be either the endpoints or the axis-aligned extrema of the arc's circle.
// We need to compute which axis-aligned extrema are actually contained within the rotated arc.
let mut bounds = ArrayVec::<Vec2, 7>::new();
let rotation = rotation.into();
bounds.push(rotation * arc.left_endpoint());
bounds.push(rotation * arc.right_endpoint());
// The half-angles are measured from a starting point of π/2, being the angle of Vec2::Y.
// Compute the normalized angles of the endpoints with the rotation taken into account, and then
// check if we are looking for an angle that is between or outside them.
let left_angle = ops::rem_euclid(FRAC_PI_2 + arc.half_angle + rotation.as_radians(), TAU);
let right_angle = ops::rem_euclid(FRAC_PI_2 - arc.half_angle + rotation.as_radians(), TAU);
let inverted = left_angle < right_angle;
for extremum in [Vec2::X, Vec2::Y, Vec2::NEG_X, Vec2::NEG_Y] {
let angle = ops::rem_euclid(extremum.to_angle(), TAU);
// If inverted = true, then right_angle > left_angle, so we are looking for an angle that is not between them.
// There's a chance that this condition fails due to rounding error, if the endpoint angle is juuuust shy of the axis.
// But in that case, the endpoint itself is within rounding error of the axis and will define the bounds just fine.
let angle_within_parameters = if inverted {
angle >= right_angle || angle <= left_angle
} else {
angle >= right_angle && angle <= left_angle
};
if angle_within_parameters {
bounds.push(extremum * arc.radius);
}
}
bounds
}
impl Bounded2d for Arc2d {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
// If our arc covers more than a circle, just return the bounding box of the circle.
if self.half_angle >= PI {
return Circle::new(self.radius).aabb_2d(isometry);
}
let isometry = isometry.into();
Aabb2d::from_point_cloud(
Isometry2d::from_translation(isometry.translation),
&arc_bounding_points(*self, isometry.rotation),
)
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
let isometry = isometry.into();
// There are two possibilities for the bounding circle.
if self.is_major() {
// If the arc is major, then the widest distance between two points is a diameter of the arc's circle;
// therefore, that circle is the bounding radius.
BoundingCircle::new(isometry.translation, self.radius)
} else {
// Otherwise, the widest distance between two points is the chord,
// so a circle of that diameter around the midpoint will contain the entire arc.
let center = isometry.rotation * self.chord_midpoint();
BoundingCircle::new(center + isometry.translation, self.half_chord_length())
}
}
}
impl Bounded2d for CircularSector {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
let isometry = isometry.into();
// If our sector covers more than a circle, just return the bounding box of the circle.
if self.half_angle() >= PI {
return Circle::new(self.radius()).aabb_2d(isometry);
}
// Otherwise, we use the same logic as for Arc2d, above, just with the circle's center as an additional possibility.
let mut bounds = arc_bounding_points(self.arc, isometry.rotation);
bounds.push(Vec2::ZERO);
Aabb2d::from_point_cloud(Isometry2d::from_translation(isometry.translation), &bounds)
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
if self.arc.is_major() {
let isometry = isometry.into();
// If the arc is major, that is, greater than a semicircle,
// then bounding circle is just the circle defining the sector.
BoundingCircle::new(isometry.translation, self.arc.radius)
} else {
// However, when the arc is minor,
// we need our bounding circle to include both endpoints of the arc as well as the circle center.
// This means we need the circumcircle of those three points.
// The circumcircle will always have a greater curvature than the circle itself, so it will contain
// the entire circular sector.
Triangle2d::new(
Vec2::ZERO,
self.arc.left_endpoint(),
self.arc.right_endpoint(),
)
.bounding_circle(isometry)
}
}
}
impl Bounded2d for CircularSegment {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
self.arc.aabb_2d(isometry)
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
self.arc.bounding_circle(isometry)
}
}
impl Bounded2d for Ellipse {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
let isometry = isometry.into();
// V = (hh * cos(beta), hh * sin(beta))
// #####*#####
// ### | ###
// # hh | #
// # *---------* U = (hw * cos(alpha), hw * sin(alpha))
// # hw #
// ### ###
// ###########
let (hw, hh) = (self.half_size.x, self.half_size.y);
// Sine and cosine of rotation angle alpha.
let (alpha_sin, alpha_cos) = isometry.rotation.sin_cos();
// Sine and cosine of alpha + pi/2. We can avoid the trigonometric functions:
// sin(beta) = sin(alpha + pi/2) = cos(alpha)
// cos(beta) = cos(alpha + pi/2) = -sin(alpha)
let (beta_sin, beta_cos) = (alpha_cos, -alpha_sin);
// Compute points U and V, the extremes of the ellipse
let (ux, uy) = (hw * alpha_cos, hw * alpha_sin);
let (vx, vy) = (hh * beta_cos, hh * beta_sin);
let half_size = Vec2::new(ops::hypot(ux, vx), ops::hypot(uy, vy));
Aabb2d::new(isometry.translation, half_size)
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
let isometry = isometry.into();
BoundingCircle::new(isometry.translation, self.semi_major())
}
}
impl Bounded2d for Annulus {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
let isometry = isometry.into();
Aabb2d::new(isometry.translation, Vec2::splat(self.outer_circle.radius))
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
let isometry = isometry.into();
BoundingCircle::new(isometry.translation, self.outer_circle.radius)
}
}
impl Bounded2d for Rhombus {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
let isometry = isometry.into();
let [rotated_x_half_diagonal, rotated_y_half_diagonal] = [
isometry.rotation * Vec2::new(self.half_diagonals.x, 0.0),
isometry.rotation * Vec2::new(0.0, self.half_diagonals.y),
];
let aabb_half_extent = rotated_x_half_diagonal
.abs()
.max(rotated_y_half_diagonal.abs());
Aabb2d {
min: -aabb_half_extent + isometry.translation,
max: aabb_half_extent + isometry.translation,
}
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
let isometry = isometry.into();
BoundingCircle::new(isometry.translation, self.circumradius())
}
}
impl Bounded2d for Plane2d {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
let isometry = isometry.into();
let normal = isometry.rotation * *self.normal;
let facing_x = normal == Vec2::X || normal == Vec2::NEG_X;
let facing_y = normal == Vec2::Y || normal == Vec2::NEG_Y;
// Dividing `f32::MAX` by 2.0 is helpful so that we can do operations
// like growing or shrinking the AABB without breaking things.
let half_width = if facing_x { 0.0 } else { f32::MAX / 2.0 };
let half_height = if facing_y { 0.0 } else { f32::MAX / 2.0 };
let half_size = Vec2::new(half_width, half_height);
Aabb2d::new(isometry.translation, half_size)
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
let isometry = isometry.into();
BoundingCircle::new(isometry.translation, f32::MAX / 2.0)
}
}
impl Bounded2d for Line2d {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
let isometry = isometry.into();
let direction = isometry.rotation * *self.direction;
// Dividing `f32::MAX` by 2.0 is helpful so that we can do operations
// like growing or shrinking the AABB without breaking things.
let max = f32::MAX / 2.0;
let half_width = if direction.x == 0.0 { 0.0 } else { max };
let half_height = if direction.y == 0.0 { 0.0 } else { max };
let half_size = Vec2::new(half_width, half_height);
Aabb2d::new(isometry.translation, half_size)
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
let isometry = isometry.into();
BoundingCircle::new(isometry.translation, f32::MAX / 2.0)
}
}
impl Bounded2d for Segment2d {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
Aabb2d::from_point_cloud(isometry, &[self.point1(), self.point2()])
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
let isometry: Isometry2d = isometry.into();
let local_center = self.center();
let radius = local_center.distance(self.point1());
let local_circle = BoundingCircle::new(local_center, radius);
local_circle.transformed_by(isometry.translation, isometry.rotation)
}
}
#[cfg(feature = "alloc")]
impl Bounded2d for Polyline2d {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
Aabb2d::from_point_cloud(isometry, &self.vertices)
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
BoundingCircle::from_point_cloud(isometry, &self.vertices)
}
}
impl Bounded2d for Triangle2d {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
let isometry = isometry.into();
let [a, b, c] = self.vertices.map(|vtx| isometry.rotation * vtx);
let min = Vec2::new(a.x.min(b.x).min(c.x), a.y.min(b.y).min(c.y));
let max = Vec2::new(a.x.max(b.x).max(c.x), a.y.max(b.y).max(c.y));
Aabb2d {
min: min + isometry.translation,
max: max + isometry.translation,
}
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
let isometry = isometry.into();
let [a, b, c] = self.vertices;
// The points of the segment opposite to the obtuse or right angle if one exists
let side_opposite_to_non_acute = if (b - a).dot(c - a) <= 0.0 {
Some((b, c))
} else if (c - b).dot(a - b) <= 0.0 {
Some((c, a))
} else if (a - c).dot(b - c) <= 0.0 {
Some((a, b))
} else {
// The triangle is acute.
None
};
// Find the minimum bounding circle. If the triangle is obtuse, the circle passes through two vertices.
// Otherwise, it's the circumcircle and passes through all three.
if let Some((point1, point2)) = side_opposite_to_non_acute {
// The triangle is obtuse or right, so the minimum bounding circle's diameter is equal to the longest side.
// We can compute the minimum bounding circle from the line segment of the longest side.
let segment = Segment2d::new(point1, point2);
segment.bounding_circle(isometry)
} else {
// The triangle is acute, so the smallest bounding circle is the circumcircle.
let (Circle { radius }, circumcenter) = self.circumcircle();
BoundingCircle::new(isometry * circumcenter, radius)
}
}
}
impl Bounded2d for Rectangle {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
let isometry = isometry.into();
// Compute the AABB of the rotated rectangle by transforming the half-extents
// by an absolute rotation matrix.
let (sin, cos) = isometry.rotation.sin_cos();
let abs_rot_mat =
Mat2::from_cols_array(&[ops::abs(cos), ops::abs(sin), ops::abs(sin), ops::abs(cos)]);
let half_size = abs_rot_mat * self.half_size;
Aabb2d::new(isometry.translation, half_size)
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
let isometry = isometry.into();
let radius = self.half_size.length();
BoundingCircle::new(isometry.translation, radius)
}
}
#[cfg(feature = "alloc")]
impl Bounded2d for Polygon {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
Aabb2d::from_point_cloud(isometry, &self.vertices)
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
BoundingCircle::from_point_cloud(isometry, &self.vertices)
}
}
#[cfg(feature = "alloc")]
impl Bounded2d for ConvexPolygon {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
Aabb2d::from_point_cloud(isometry, self.vertices())
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
BoundingCircle::from_point_cloud(isometry, self.vertices())
}
}
impl Bounded2d for RegularPolygon {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
let isometry = isometry.into();
let mut min = Vec2::ZERO;
let mut max = Vec2::ZERO;
for vertex in self.vertices(isometry.rotation.as_radians()) {
min = min.min(vertex);
max = max.max(vertex);
}
Aabb2d {
min: min + isometry.translation,
max: max + isometry.translation,
}
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
let isometry = isometry.into();
BoundingCircle::new(isometry.translation, self.circumcircle.radius)
}
}
impl Bounded2d for Capsule2d {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
let isometry = isometry.into();
// Get the line segment between the semicircles of the rotated capsule
let segment = Segment2d::from_direction_and_length(
isometry.rotation * Dir2::Y,
self.half_length * 2.,
);
let (a, b) = (segment.point1(), segment.point2());
// Expand the line segment by the capsule radius to get the capsule half-extents
let min = a.min(b) - Vec2::splat(self.radius);
let max = a.max(b) + Vec2::splat(self.radius);
Aabb2d {
min: min + isometry.translation,
max: max + isometry.translation,
}
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
let isometry = isometry.into();
BoundingCircle::new(isometry.translation, self.radius + self.half_length)
}
}
impl<P: Bounded2d + Primitive2d> Bounded2d for Ring<P> {
fn aabb_2d(&self, isometry: impl Into<Isometry2d>) -> Aabb2d {
self.outer_shape.aabb_2d(isometry)
}
fn bounding_circle(&self, isometry: impl Into<Isometry2d>) -> BoundingCircle {
self.outer_shape.bounding_circle(isometry)
}
}
#[cfg(test)]
#[expect(clippy::print_stdout, reason = "Allowed in tests.")]
mod tests {
use core::f32::consts::{FRAC_PI_2, FRAC_PI_3, FRAC_PI_4, FRAC_PI_6, TAU};
use std::println;
use approx::assert_abs_diff_eq;
use glam::Vec2;
use crate::{
bounding::Bounded2d,
ops::{self, FloatPow},
primitives::{
Annulus, Arc2d, Capsule2d, Circle, CircularSector, CircularSegment, Ellipse, Line2d,
Plane2d, Polygon, Polyline2d, Rectangle, RegularPolygon, Rhombus, Segment2d,
Triangle2d,
},
Dir2, Isometry2d, Rot2,
};
#[test]
fn circle() {
let circle = Circle { radius: 1.0 };
let translation = Vec2::new(2.0, 1.0);
let isometry = Isometry2d::from_translation(translation);
let aabb = circle.aabb_2d(isometry);
assert_eq!(aabb.min, Vec2::new(1.0, 0.0));
assert_eq!(aabb.max, Vec2::new(3.0, 2.0));
let bounding_circle = circle.bounding_circle(isometry);
assert_eq!(bounding_circle.center, translation);
assert_eq!(bounding_circle.radius(), 1.0);
}
#[test]
// Arcs and circular segments have the same bounding shapes so they share test cases.
fn arc_and_segment() {
struct TestCase {
name: &'static str,
arc: Arc2d,
translation: Vec2,
rotation: f32,
aabb_min: Vec2,
aabb_max: Vec2,
bounding_circle_center: Vec2,
bounding_circle_radius: f32,
}
impl TestCase {
fn isometry(&self) -> Isometry2d {
Isometry2d::new(self.translation, self.rotation.into())
}
}
// The apothem of an arc covering 1/6th of a circle.
let apothem = ops::sqrt(3.0) / 2.0;
let tests = [
// Test case: a basic minor arc
TestCase {
name: "1/6th circle untransformed",
arc: Arc2d::from_radians(1.0, FRAC_PI_3),
translation: Vec2::ZERO,
rotation: 0.0,
aabb_min: Vec2::new(-0.5, apothem),
aabb_max: Vec2::new(0.5, 1.0),
bounding_circle_center: Vec2::new(0.0, apothem),
bounding_circle_radius: 0.5,
},
// Test case: a smaller arc, verifying that radius scaling works
TestCase {
name: "1/6th circle with radius 0.5",
arc: Arc2d::from_radians(0.5, FRAC_PI_3),
translation: Vec2::ZERO,
rotation: 0.0,
aabb_min: Vec2::new(-0.25, apothem / 2.0),
aabb_max: Vec2::new(0.25, 0.5),
bounding_circle_center: Vec2::new(0.0, apothem / 2.0),
bounding_circle_radius: 0.25,
},
// Test case: a larger arc, verifying that radius scaling works
TestCase {
name: "1/6th circle with radius 2.0",
arc: Arc2d::from_radians(2.0, FRAC_PI_3),
translation: Vec2::ZERO,
rotation: 0.0,
aabb_min: Vec2::new(-1.0, 2.0 * apothem),
aabb_max: Vec2::new(1.0, 2.0),
bounding_circle_center: Vec2::new(0.0, 2.0 * apothem),
bounding_circle_radius: 1.0,
},
// Test case: translation of a minor arc
TestCase {
name: "1/6th circle translated",
arc: Arc2d::from_radians(1.0, FRAC_PI_3),
translation: Vec2::new(2.0, 3.0),
rotation: 0.0,
aabb_min: Vec2::new(1.5, 3.0 + apothem),
aabb_max: Vec2::new(2.5, 4.0),
bounding_circle_center: Vec2::new(2.0, 3.0 + apothem),
bounding_circle_radius: 0.5,
},
// Test case: rotation of a minor arc
TestCase {
name: "1/6th circle rotated",
arc: Arc2d::from_radians(1.0, FRAC_PI_3),
translation: Vec2::ZERO,
// Rotate left by 1/12 of a circle, so the right endpoint is on the y-axis.
rotation: FRAC_PI_6,
aabb_min: Vec2::new(-apothem, 0.5),
aabb_max: Vec2::new(0.0, 1.0),
// The exact coordinates here are not obvious, but can be computed by constructing
// an altitude from the midpoint of the chord to the y-axis and using the right triangle
// similarity theorem.
bounding_circle_center: Vec2::new(-apothem / 2.0, apothem.squared()),
bounding_circle_radius: 0.5,
},
// Test case: handling of axis-aligned extrema
TestCase {
name: "1/4er circle rotated to be axis-aligned",
arc: Arc2d::from_radians(1.0, FRAC_PI_2),
translation: Vec2::ZERO,
// Rotate right by 1/8 of a circle, so the right endpoint is on the x-axis and the left endpoint is on the y-axis.
rotation: -FRAC_PI_4,
aabb_min: Vec2::ZERO,
aabb_max: Vec2::splat(1.0),
bounding_circle_center: Vec2::splat(0.5),
bounding_circle_radius: ops::sqrt(2.0) / 2.0,
},
// Test case: a basic major arc
TestCase {
name: "5/6th circle untransformed",
arc: Arc2d::from_radians(1.0, 5.0 * FRAC_PI_3),
translation: Vec2::ZERO,
rotation: 0.0,
aabb_min: Vec2::new(-1.0, -apothem),
aabb_max: Vec2::new(1.0, 1.0),
bounding_circle_center: Vec2::ZERO,
bounding_circle_radius: 1.0,
},
// Test case: a translated major arc
TestCase {
name: "5/6th circle translated",
arc: Arc2d::from_radians(1.0, 5.0 * FRAC_PI_3),
translation: Vec2::new(2.0, 3.0),
rotation: 0.0,
aabb_min: Vec2::new(1.0, 3.0 - apothem),
aabb_max: Vec2::new(3.0, 4.0),
bounding_circle_center: Vec2::new(2.0, 3.0),
bounding_circle_radius: 1.0,
},
// Test case: a rotated major arc, with inverted left/right angles
TestCase {
name: "5/6th circle rotated",
arc: Arc2d::from_radians(1.0, 5.0 * FRAC_PI_3),
translation: Vec2::ZERO,
// Rotate left by 1/12 of a circle, so the left endpoint is on the y-axis.
rotation: FRAC_PI_6,
aabb_min: Vec2::new(-1.0, -1.0),
aabb_max: Vec2::new(1.0, 1.0),
bounding_circle_center: Vec2::ZERO,
bounding_circle_radius: 1.0,
},
];
for test in tests {
#[cfg(feature = "std")]
println!("subtest case: {}", test.name);
let segment: CircularSegment = test.arc.into();
let arc_aabb = test.arc.aabb_2d(test.isometry());
assert_abs_diff_eq!(test.aabb_min, arc_aabb.min);
assert_abs_diff_eq!(test.aabb_max, arc_aabb.max);
let segment_aabb = segment.aabb_2d(test.isometry());
assert_abs_diff_eq!(test.aabb_min, segment_aabb.min);
assert_abs_diff_eq!(test.aabb_max, segment_aabb.max);
let arc_bounding_circle = test.arc.bounding_circle(test.isometry());
assert_abs_diff_eq!(test.bounding_circle_center, arc_bounding_circle.center);
assert_abs_diff_eq!(test.bounding_circle_radius, arc_bounding_circle.radius());
let segment_bounding_circle = segment.bounding_circle(test.isometry());
assert_abs_diff_eq!(test.bounding_circle_center, segment_bounding_circle.center);
assert_abs_diff_eq!(
test.bounding_circle_radius,
segment_bounding_circle.radius()
);
}
}
#[test]
fn circular_sector() {
struct TestCase {
name: &'static str,
arc: Arc2d,
translation: Vec2,
rotation: f32,
aabb_min: Vec2,
aabb_max: Vec2,
bounding_circle_center: Vec2,
bounding_circle_radius: f32,
}
impl TestCase {
fn isometry(&self) -> Isometry2d {
Isometry2d::new(self.translation, self.rotation.into())
}
}
// The apothem of an arc covering 1/6th of a circle.
let apothem = ops::sqrt(3.0) / 2.0;
let inv_sqrt_3 = ops::sqrt(3.0).recip();
let tests = [
// Test case: A sector whose arc is minor, but whose bounding circle is not the circumcircle of the endpoints and center
TestCase {
name: "1/3rd circle",
arc: Arc2d::from_radians(1.0, TAU / 3.0),
translation: Vec2::ZERO,
rotation: 0.0,
aabb_min: Vec2::new(-apothem, 0.0),
aabb_max: Vec2::new(apothem, 1.0),
bounding_circle_center: Vec2::new(0.0, 0.5),
bounding_circle_radius: apothem,
},
// The remaining test cases are selected as for arc_and_segment.
TestCase {
name: "1/6th circle untransformed",
arc: Arc2d::from_radians(1.0, FRAC_PI_3),
translation: Vec2::ZERO,
rotation: 0.0,
aabb_min: Vec2::new(-0.5, 0.0),
aabb_max: Vec2::new(0.5, 1.0),
// The bounding circle is a circumcircle of an equilateral triangle with side length 1.
// The distance from the corner to the center of such a triangle is 1/sqrt(3).
bounding_circle_center: Vec2::new(0.0, inv_sqrt_3),
bounding_circle_radius: inv_sqrt_3,
},
TestCase {
name: "1/6th circle with radius 0.5",
arc: Arc2d::from_radians(0.5, FRAC_PI_3),
translation: Vec2::ZERO,
rotation: 0.0,
aabb_min: Vec2::new(-0.25, 0.0),
aabb_max: Vec2::new(0.25, 0.5),
bounding_circle_center: Vec2::new(0.0, inv_sqrt_3 / 2.0),
bounding_circle_radius: inv_sqrt_3 / 2.0,
},
TestCase {
name: "1/6th circle with radius 2.0",
arc: Arc2d::from_radians(2.0, FRAC_PI_3),
translation: Vec2::ZERO,
rotation: 0.0,
aabb_min: Vec2::new(-1.0, 0.0),
aabb_max: Vec2::new(1.0, 2.0),
bounding_circle_center: Vec2::new(0.0, 2.0 * inv_sqrt_3),
bounding_circle_radius: 2.0 * inv_sqrt_3,
},
TestCase {
name: "1/6th circle translated",
arc: Arc2d::from_radians(1.0, FRAC_PI_3),
translation: Vec2::new(2.0, 3.0),
rotation: 0.0,
aabb_min: Vec2::new(1.5, 3.0),
aabb_max: Vec2::new(2.5, 4.0),
bounding_circle_center: Vec2::new(2.0, 3.0 + inv_sqrt_3),
bounding_circle_radius: inv_sqrt_3,
},
TestCase {
name: "1/6th circle rotated",
arc: Arc2d::from_radians(1.0, FRAC_PI_3),
translation: Vec2::ZERO,
// Rotate left by 1/12 of a circle, so the right endpoint is on the y-axis.
rotation: FRAC_PI_6,
aabb_min: Vec2::new(-apothem, 0.0),
aabb_max: Vec2::new(0.0, 1.0),
// The x-coordinate is now the inradius of the equilateral triangle, which is sqrt(3)/2.
bounding_circle_center: Vec2::new(-inv_sqrt_3 / 2.0, 0.5),
bounding_circle_radius: inv_sqrt_3,
},
TestCase {
name: "1/4er circle rotated to be axis-aligned",
arc: Arc2d::from_radians(1.0, FRAC_PI_2),
translation: Vec2::ZERO,
// Rotate right by 1/8 of a circle, so the right endpoint is on the x-axis and the left endpoint is on the y-axis.
rotation: -FRAC_PI_4,
aabb_min: Vec2::ZERO,
aabb_max: Vec2::splat(1.0),
bounding_circle_center: Vec2::splat(0.5),
bounding_circle_radius: ops::sqrt(2.0) / 2.0,
},
TestCase {
name: "5/6th circle untransformed",
arc: Arc2d::from_radians(1.0, 5.0 * FRAC_PI_3),
translation: Vec2::ZERO,
rotation: 0.0,
aabb_min: Vec2::new(-1.0, -apothem),
aabb_max: Vec2::new(1.0, 1.0),
bounding_circle_center: Vec2::ZERO,
bounding_circle_radius: 1.0,
},
TestCase {
name: "5/6th circle translated",
arc: Arc2d::from_radians(1.0, 5.0 * FRAC_PI_3),
translation: Vec2::new(2.0, 3.0),
rotation: 0.0,
aabb_min: Vec2::new(1.0, 3.0 - apothem),
aabb_max: Vec2::new(3.0, 4.0),
bounding_circle_center: Vec2::new(2.0, 3.0),
bounding_circle_radius: 1.0,
},
TestCase {
name: "5/6th circle rotated",
arc: Arc2d::from_radians(1.0, 5.0 * FRAC_PI_3),
translation: Vec2::ZERO,
// Rotate left by 1/12 of a circle, so the left endpoint is on the y-axis.
rotation: FRAC_PI_6,
aabb_min: Vec2::new(-1.0, -1.0),
aabb_max: Vec2::new(1.0, 1.0),
bounding_circle_center: Vec2::ZERO,
bounding_circle_radius: 1.0,
},
];
for test in tests {
#[cfg(feature = "std")]
println!("subtest case: {}", test.name);
let sector: CircularSector = test.arc.into();
let aabb = sector.aabb_2d(test.isometry());
assert_abs_diff_eq!(test.aabb_min, aabb.min);
assert_abs_diff_eq!(test.aabb_max, aabb.max);
let bounding_circle = sector.bounding_circle(test.isometry());
assert_abs_diff_eq!(test.bounding_circle_center, bounding_circle.center);
assert_abs_diff_eq!(test.bounding_circle_radius, bounding_circle.radius());
}
}
#[test]
fn ellipse() {
let ellipse = Ellipse::new(1.0, 0.5);
let translation = Vec2::new(2.0, 1.0);
let isometry = Isometry2d::from_translation(translation);
let aabb = ellipse.aabb_2d(isometry);
assert_eq!(aabb.min, Vec2::new(1.0, 0.5));
assert_eq!(aabb.max, Vec2::new(3.0, 1.5));
let bounding_circle = ellipse.bounding_circle(isometry);
assert_eq!(bounding_circle.center, translation);
assert_eq!(bounding_circle.radius(), 1.0);
}
#[test]
fn annulus() {
let annulus = Annulus::new(1.0, 2.0);
let translation = Vec2::new(2.0, 1.0);
let rotation = Rot2::radians(1.0);
let isometry = Isometry2d::new(translation, rotation);
let aabb = annulus.aabb_2d(isometry);
assert_eq!(aabb.min, Vec2::new(0.0, -1.0));
assert_eq!(aabb.max, Vec2::new(4.0, 3.0));
let bounding_circle = annulus.bounding_circle(isometry);
assert_eq!(bounding_circle.center, translation);
assert_eq!(bounding_circle.radius(), 2.0);
}
#[test]
fn rhombus() {
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/rects/urect.rs | crates/bevy_math/src/rects/urect.rs | use crate::{IRect, Rect, UVec2};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
#[cfg(all(feature = "serialize", feature = "bevy_reflect"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
/// A rectangle defined by two opposite corners.
///
/// The rectangle is axis aligned, and defined by its minimum and maximum coordinates,
/// stored in `URect::min` and `URect::max`, respectively. The minimum/maximum invariant
/// must be upheld by the user when directly assigning the fields, otherwise some methods
/// produce invalid results. It is generally recommended to use one of the constructor
/// methods instead, which will ensure this invariant is met, unless you already have
/// the minimum and maximum corners.
#[repr(C)]
#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Hash, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct URect {
/// The minimum corner point of the rect.
pub min: UVec2,
/// The maximum corner point of the rect.
pub max: UVec2,
}
impl URect {
/// An empty `URect`, represented by maximum and minimum corner points
/// with `max == UVec2::MIN` and `min == UVec2::MAX`, so the
/// rect has an extremely large negative size.
/// This is useful, because when taking a union B of a non-empty `URect` A and
/// this empty `URect`, B will simply equal A.
pub const EMPTY: Self = Self {
max: UVec2::MIN,
min: UVec2::MAX,
};
/// Create a new rectangle from two corner points.
///
/// The two points do not need to be the minimum and/or maximum corners.
/// They only need to be two opposite corners.
///
/// # Examples
///
/// ```
/// # use bevy_math::URect;
/// let r = URect::new(0, 4, 10, 6); // w=10 h=2
/// let r = URect::new(2, 4, 5, 0); // w=3 h=4
/// ```
#[inline]
pub fn new(x0: u32, y0: u32, x1: u32, y1: u32) -> Self {
Self::from_corners(UVec2::new(x0, y0), UVec2::new(x1, y1))
}
/// Create a new rectangle from two corner points.
///
/// The two points do not need to be the minimum and/or maximum corners.
/// They only need to be two opposite corners.
///
/// # Examples
///
/// ```
/// # use bevy_math::{URect, UVec2};
/// // Unit rect from [0,0] to [1,1]
/// let r = URect::from_corners(UVec2::ZERO, UVec2::ONE); // w=1 h=1
/// // Same; the points do not need to be ordered
/// let r = URect::from_corners(UVec2::ONE, UVec2::ZERO); // w=1 h=1
/// ```
#[inline]
pub fn from_corners(p0: UVec2, p1: UVec2) -> Self {
Self {
min: p0.min(p1),
max: p0.max(p1),
}
}
/// Create a new rectangle from its center and size.
///
/// # Rounding Behavior
///
/// If the size contains odd numbers they will be rounded down to the nearest whole number.
///
/// # Panics
///
/// This method panics if any of the components of the size is negative or if `origin - (size / 2)` results in any negatives.
///
/// # Examples
///
/// ```
/// # use bevy_math::{URect, UVec2};
/// let r = URect::from_center_size(UVec2::ONE, UVec2::splat(2)); // w=2 h=2
/// assert_eq!(r.min, UVec2::splat(0));
/// assert_eq!(r.max, UVec2::splat(2));
/// ```
#[inline]
pub fn from_center_size(origin: UVec2, size: UVec2) -> Self {
assert!(origin.cmpge(size / 2).all(), "Origin must always be greater than or equal to (size / 2) otherwise the rectangle is undefined! Origin was {origin} and size was {size}");
let half_size = size / 2;
Self::from_center_half_size(origin, half_size)
}
/// Create a new rectangle from its center and half-size.
///
/// # Panics
///
/// This method panics if any of the components of the half-size is negative or if `origin - half_size` results in any negatives.
///
/// # Examples
///
/// ```
/// # use bevy_math::{URect, UVec2};
/// let r = URect::from_center_half_size(UVec2::ONE, UVec2::ONE); // w=2 h=2
/// assert_eq!(r.min, UVec2::splat(0));
/// assert_eq!(r.max, UVec2::splat(2));
/// ```
#[inline]
pub fn from_center_half_size(origin: UVec2, half_size: UVec2) -> Self {
assert!(origin.cmpge(half_size).all(), "Origin must always be greater than or equal to half_size otherwise the rectangle is undefined! Origin was {origin} and half_size was {half_size}");
Self {
min: origin - half_size,
max: origin + half_size,
}
}
/// Check if the rectangle is empty.
///
/// # Examples
///
/// ```
/// # use bevy_math::{URect, UVec2};
/// let r = URect::from_corners(UVec2::ZERO, UVec2::new(0, 1)); // w=0 h=1
/// assert!(r.is_empty());
/// ```
#[inline]
pub fn is_empty(&self) -> bool {
self.min.cmpge(self.max).any()
}
/// Rectangle width (max.x - min.x).
///
/// # Examples
///
/// ```
/// # use bevy_math::URect;
/// let r = URect::new(0, 0, 5, 1); // w=5 h=1
/// assert_eq!(r.width(), 5);
/// ```
#[inline]
pub const fn width(&self) -> u32 {
self.max.x - self.min.x
}
/// Rectangle height (max.y - min.y).
///
/// # Examples
///
/// ```
/// # use bevy_math::URect;
/// let r = URect::new(0, 0, 5, 1); // w=5 h=1
/// assert_eq!(r.height(), 1);
/// ```
#[inline]
pub const fn height(&self) -> u32 {
self.max.y - self.min.y
}
/// Rectangle size.
///
/// # Examples
///
/// ```
/// # use bevy_math::{URect, UVec2};
/// let r = URect::new(0, 0, 5, 1); // w=5 h=1
/// assert_eq!(r.size(), UVec2::new(5, 1));
/// ```
#[inline]
pub fn size(&self) -> UVec2 {
self.max - self.min
}
/// Rectangle half-size.
///
/// # Rounding Behavior
///
/// If the full size contains odd numbers they will be rounded down to the nearest whole number when calculating the half size.
///
/// # Examples
///
/// ```
/// # use bevy_math::{URect, UVec2};
/// let r = URect::new(0, 0, 4, 2); // w=4 h=2
/// assert_eq!(r.half_size(), UVec2::new(2, 1));
/// ```
#[inline]
pub fn half_size(&self) -> UVec2 {
self.size() / 2
}
/// The center point of the rectangle.
///
/// # Rounding Behavior
///
/// If the (min + max) contains odd numbers they will be rounded down to the nearest whole number when calculating the center.
///
/// # Examples
///
/// ```
/// # use bevy_math::{URect, UVec2};
/// let r = URect::new(0, 0, 4, 2); // w=4 h=2
/// assert_eq!(r.center(), UVec2::new(2, 1));
/// ```
#[inline]
pub fn center(&self) -> UVec2 {
(self.min + self.max) / 2
}
/// Check if a point lies within this rectangle, inclusive of its edges.
///
/// # Examples
///
/// ```
/// # use bevy_math::URect;
/// let r = URect::new(0, 0, 5, 1); // w=5 h=1
/// assert!(r.contains(r.center()));
/// assert!(r.contains(r.min));
/// assert!(r.contains(r.max));
/// ```
#[inline]
pub fn contains(&self, point: UVec2) -> bool {
(point.cmpge(self.min) & point.cmple(self.max)).all()
}
/// Build a new rectangle formed of the union of this rectangle and another rectangle.
///
/// The union is the smallest rectangle enclosing both rectangles.
///
/// # Examples
///
/// ```
/// # use bevy_math::{URect, UVec2};
/// let r1 = URect::new(0, 0, 5, 1); // w=5 h=1
/// let r2 = URect::new(1, 0, 3, 8); // w=2 h=4
/// let r = r1.union(r2);
/// assert_eq!(r.min, UVec2::new(0, 0));
/// assert_eq!(r.max, UVec2::new(5, 8));
/// ```
#[inline]
pub fn union(&self, other: Self) -> Self {
Self {
min: self.min.min(other.min),
max: self.max.max(other.max),
}
}
/// Build a new rectangle formed of the union of this rectangle and a point.
///
/// The union is the smallest rectangle enclosing both the rectangle and the point. If the
/// point is already inside the rectangle, this method returns a copy of the rectangle.
///
/// # Examples
///
/// ```
/// # use bevy_math::{URect, UVec2};
/// let r = URect::new(0, 0, 5, 1); // w=5 h=1
/// let u = r.union_point(UVec2::new(3, 6));
/// assert_eq!(u.min, UVec2::ZERO);
/// assert_eq!(u.max, UVec2::new(5, 6));
/// ```
#[inline]
pub fn union_point(&self, other: UVec2) -> Self {
Self {
min: self.min.min(other),
max: self.max.max(other),
}
}
/// Build a new rectangle formed of the intersection of this rectangle and another rectangle.
///
/// The intersection is the largest rectangle enclosed in both rectangles. If the intersection
/// is empty, this method returns an empty rectangle ([`URect::is_empty()`] returns `true`), but
/// the actual values of [`URect::min`] and [`URect::max`] are implementation-dependent.
///
/// # Examples
///
/// ```
/// # use bevy_math::{URect, UVec2};
/// let r1 = URect::new(0, 0, 2, 2); // w=2 h=2
/// let r2 = URect::new(1, 1, 3, 3); // w=2 h=2
/// let r = r1.intersect(r2);
/// assert_eq!(r.min, UVec2::new(1, 1));
/// assert_eq!(r.max, UVec2::new(2, 2));
/// ```
#[inline]
pub fn intersect(&self, other: Self) -> Self {
let mut r = Self {
min: self.min.max(other.min),
max: self.max.min(other.max),
};
// Collapse min over max to enforce invariants and ensure e.g. width() or
// height() never return a negative value.
r.min = r.min.min(r.max);
r
}
/// Create a new rectangle by expanding it evenly on all sides.
///
/// A positive expansion value produces a larger rectangle,
/// while a negative expansion value produces a smaller rectangle.
/// If this would result in zero width or height, [`URect::EMPTY`] is returned instead.
///
/// # Examples
///
/// ```
/// # use bevy_math::{URect, UVec2};
/// let r = URect::new(4, 4, 6, 6); // w=2 h=2
/// let r2 = r.inflate(1); // w=4 h=4
/// assert_eq!(r2.min, UVec2::splat(3));
/// assert_eq!(r2.max, UVec2::splat(7));
///
/// let r = URect::new(4, 4, 8, 8); // w=4 h=4
/// let r2 = r.inflate(-1); // w=2 h=2
/// assert_eq!(r2.min, UVec2::splat(5));
/// assert_eq!(r2.max, UVec2::splat(7));
/// ```
#[inline]
pub fn inflate(&self, expansion: i32) -> Self {
let mut r = Self {
min: UVec2::new(
self.min.x.saturating_add_signed(-expansion),
self.min.y.saturating_add_signed(-expansion),
),
max: UVec2::new(
self.max.x.saturating_add_signed(expansion),
self.max.y.saturating_add_signed(expansion),
),
};
// Collapse min over max to enforce invariants and ensure e.g. width() or
// height() never return a negative value.
r.min = r.min.min(r.max);
r
}
/// Returns self as [`Rect`] (f32)
#[inline]
pub fn as_rect(&self) -> Rect {
Rect::from_corners(self.min.as_vec2(), self.max.as_vec2())
}
/// Returns self as [`IRect`] (i32)
#[inline]
pub fn as_irect(&self) -> IRect {
IRect::from_corners(self.min.as_ivec2(), self.max.as_ivec2())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn well_formed() {
let r = URect::from_center_size(UVec2::new(10, 16), UVec2::new(8, 12));
assert_eq!(r.min, UVec2::new(6, 10));
assert_eq!(r.max, UVec2::new(14, 22));
assert_eq!(r.center(), UVec2::new(10, 16));
assert_eq!(r.width(), 8);
assert_eq!(r.height(), 12);
assert_eq!(r.size(), UVec2::new(8, 12));
assert_eq!(r.half_size(), UVec2::new(4, 6));
assert!(r.contains(UVec2::new(7, 10)));
assert!(r.contains(UVec2::new(14, 10)));
assert!(r.contains(UVec2::new(10, 22)));
assert!(r.contains(UVec2::new(6, 22)));
assert!(r.contains(UVec2::new(14, 22)));
assert!(!r.contains(UVec2::new(50, 5)));
}
#[test]
fn rect_union() {
let r = URect::from_center_size(UVec2::splat(4), UVec2::splat(4)); // [2, 2] - [6, 6]
// overlapping
let r2 = URect {
min: UVec2::new(0, 0),
max: UVec2::new(3, 3),
};
let u = r.union(r2);
assert_eq!(u.min, UVec2::new(0, 0));
assert_eq!(u.max, UVec2::new(6, 6));
// disjoint
let r2 = URect {
min: UVec2::new(4, 7),
max: UVec2::new(8, 8),
};
let u = r.union(r2);
assert_eq!(u.min, UVec2::new(2, 2));
assert_eq!(u.max, UVec2::new(8, 8));
// included
let r2 = URect::from_center_size(UVec2::splat(4), UVec2::splat(2));
let u = r.union(r2);
assert_eq!(u.min, r.min);
assert_eq!(u.max, r.max);
// including
let r2 = URect::from_center_size(UVec2::splat(4), UVec2::splat(6));
let u = r.union(r2);
assert_eq!(u.min, r2.min);
assert_eq!(u.min, r2.min);
}
#[test]
fn rect_union_pt() {
let r = URect::from_center_size(UVec2::splat(4), UVec2::splat(4)); // [2, 2] - [6, 6]
// inside
let v = UVec2::new(2, 5);
let u = r.union_point(v);
assert_eq!(u.min, r.min);
assert_eq!(u.max, r.max);
// outside
let v = UVec2::new(10, 5);
let u = r.union_point(v);
assert_eq!(u.min, UVec2::new(2, 2));
assert_eq!(u.max, UVec2::new(10, 6));
}
#[test]
fn rect_intersect() {
let r = URect::from_center_size(UVec2::splat(6), UVec2::splat(8)); // [2, 2] - [10, 10]
// overlapping
let r2 = URect {
min: UVec2::new(8, 8),
max: UVec2::new(12, 12),
};
let u = r.intersect(r2);
assert_eq!(u.min, UVec2::new(8, 8));
assert_eq!(u.max, UVec2::new(10, 10));
// disjoint
let r2 = URect {
min: UVec2::new(12, 12),
max: UVec2::new(14, 18),
};
let u = r.intersect(r2);
assert!(u.is_empty());
assert_eq!(u.width(), 0);
// included
let r2 = URect::from_center_size(UVec2::splat(6), UVec2::splat(2));
let u = r.intersect(r2);
assert_eq!(u.min, r2.min);
assert_eq!(u.max, r2.max);
// including
let r2 = URect::from_center_size(UVec2::splat(6), UVec2::splat(10));
let u = r.intersect(r2);
assert_eq!(u.min, r.min);
assert_eq!(u.max, r.max);
}
#[test]
fn rect_inflate() {
let r = URect::from_center_size(UVec2::splat(6), UVec2::splat(6)); // [3, 3] - [9, 9]
let r2 = r.inflate(2);
assert_eq!(r2.min, UVec2::new(1, 1));
assert_eq!(r2.max, UVec2::new(11, 11));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/rects/rect.rs | crates/bevy_math/src/rects/rect.rs | use crate::{IRect, URect, Vec2};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
#[cfg(all(feature = "serialize", feature = "bevy_reflect"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
/// A rectangle defined by two opposite corners.
///
/// The rectangle is axis aligned, and defined by its minimum and maximum coordinates,
/// stored in `Rect::min` and `Rect::max`, respectively. The minimum/maximum invariant
/// must be upheld by the user when directly assigning the fields, otherwise some methods
/// produce invalid results. It is generally recommended to use one of the constructor
/// methods instead, which will ensure this invariant is met, unless you already have
/// the minimum and maximum corners.
#[repr(C)]
#[derive(Default, Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Rect {
/// The minimum corner point of the rect.
pub min: Vec2,
/// The maximum corner point of the rect.
pub max: Vec2,
}
impl Rect {
/// An empty `Rect`, represented by maximum and minimum corner points
/// at `Vec2::NEG_INFINITY` and `Vec2::INFINITY`, respectively.
/// This is so the `Rect` has a infinitely negative size.
/// This is useful, because when taking a union B of a non-empty `Rect` A and
/// this empty `Rect`, B will simply equal A.
pub const EMPTY: Self = Self {
max: Vec2::NEG_INFINITY,
min: Vec2::INFINITY,
};
/// Create a new rectangle from two corner points.
///
/// The two points do not need to be the minimum and/or maximum corners.
/// They only need to be two opposite corners.
///
/// # Examples
///
/// ```
/// # use bevy_math::Rect;
/// let r = Rect::new(0., 4., 10., 6.); // w=10 h=2
/// let r = Rect::new(2., 3., 5., -1.); // w=3 h=4
/// ```
#[inline]
pub fn new(x0: f32, y0: f32, x1: f32, y1: f32) -> Self {
Self::from_corners(Vec2::new(x0, y0), Vec2::new(x1, y1))
}
/// Create a new rectangle from two corner points.
///
/// The two points do not need to be the minimum and/or maximum corners.
/// They only need to be two opposite corners.
///
/// # Examples
///
/// ```
/// # use bevy_math::{Rect, Vec2};
/// // Unit rect from [0,0] to [1,1]
/// let r = Rect::from_corners(Vec2::ZERO, Vec2::ONE); // w=1 h=1
/// // Same; the points do not need to be ordered
/// let r = Rect::from_corners(Vec2::ONE, Vec2::ZERO); // w=1 h=1
/// ```
#[inline]
pub fn from_corners(p0: Vec2, p1: Vec2) -> Self {
Self {
min: p0.min(p1),
max: p0.max(p1),
}
}
/// Create a new rectangle from its center and size.
///
/// # Panics
///
/// This method panics if any of the components of the size is negative.
///
/// # Examples
///
/// ```
/// # use bevy_math::{Rect, Vec2};
/// let r = Rect::from_center_size(Vec2::ZERO, Vec2::ONE); // w=1 h=1
/// assert!(r.min.abs_diff_eq(Vec2::splat(-0.5), 1e-5));
/// assert!(r.max.abs_diff_eq(Vec2::splat(0.5), 1e-5));
/// ```
#[inline]
pub fn from_center_size(origin: Vec2, size: Vec2) -> Self {
assert!(size.cmpge(Vec2::ZERO).all(), "Rect size must be positive");
let half_size = size / 2.;
Self::from_center_half_size(origin, half_size)
}
/// Create a new rectangle from its center and half-size.
///
/// # Panics
///
/// This method panics if any of the components of the half-size is negative.
///
/// # Examples
///
/// ```
/// # use bevy_math::{Rect, Vec2};
/// let r = Rect::from_center_half_size(Vec2::ZERO, Vec2::ONE); // w=2 h=2
/// assert!(r.min.abs_diff_eq(Vec2::splat(-1.), 1e-5));
/// assert!(r.max.abs_diff_eq(Vec2::splat(1.), 1e-5));
/// ```
#[inline]
pub fn from_center_half_size(origin: Vec2, half_size: Vec2) -> Self {
assert!(
half_size.cmpge(Vec2::ZERO).all(),
"Rect half_size must be positive"
);
Self {
min: origin - half_size,
max: origin + half_size,
}
}
/// Check if the rectangle is empty.
///
/// # Examples
///
/// ```
/// # use bevy_math::{Rect, Vec2};
/// let r = Rect::from_corners(Vec2::ZERO, Vec2::new(0., 1.)); // w=0 h=1
/// assert!(r.is_empty());
/// ```
#[inline]
pub fn is_empty(&self) -> bool {
self.min.cmpge(self.max).any()
}
/// Rectangle width (max.x - min.x).
///
/// # Examples
///
/// ```
/// # use bevy_math::Rect;
/// let r = Rect::new(0., 0., 5., 1.); // w=5 h=1
/// assert!((r.width() - 5.).abs() <= 1e-5);
/// ```
#[inline]
pub fn width(&self) -> f32 {
self.max.x - self.min.x
}
/// Rectangle height (max.y - min.y).
///
/// # Examples
///
/// ```
/// # use bevy_math::Rect;
/// let r = Rect::new(0., 0., 5., 1.); // w=5 h=1
/// assert!((r.height() - 1.).abs() <= 1e-5);
/// ```
#[inline]
pub fn height(&self) -> f32 {
self.max.y - self.min.y
}
/// Rectangle size.
///
/// # Examples
///
/// ```
/// # use bevy_math::{Rect, Vec2};
/// let r = Rect::new(0., 0., 5., 1.); // w=5 h=1
/// assert!(r.size().abs_diff_eq(Vec2::new(5., 1.), 1e-5));
/// ```
#[inline]
pub fn size(&self) -> Vec2 {
self.max - self.min
}
/// Rectangle half-size.
///
/// # Examples
///
/// ```
/// # use bevy_math::{Rect, Vec2};
/// let r = Rect::new(0., 0., 5., 1.); // w=5 h=1
/// assert!(r.half_size().abs_diff_eq(Vec2::new(2.5, 0.5), 1e-5));
/// ```
#[inline]
pub fn half_size(&self) -> Vec2 {
self.size() * 0.5
}
/// The center point of the rectangle.
///
/// # Examples
///
/// ```
/// # use bevy_math::{Rect, Vec2};
/// let r = Rect::new(0., 0., 5., 1.); // w=5 h=1
/// assert!(r.center().abs_diff_eq(Vec2::new(2.5, 0.5), 1e-5));
/// ```
#[inline]
pub fn center(&self) -> Vec2 {
(self.min + self.max) * 0.5
}
/// Check if a point lies within this rectangle, inclusive of its edges.
///
/// # Examples
///
/// ```
/// # use bevy_math::Rect;
/// let r = Rect::new(0., 0., 5., 1.); // w=5 h=1
/// assert!(r.contains(r.center()));
/// assert!(r.contains(r.min));
/// assert!(r.contains(r.max));
/// ```
#[inline]
pub fn contains(&self, point: Vec2) -> bool {
(point.cmpge(self.min) & point.cmple(self.max)).all()
}
/// Build a new rectangle formed of the union of this rectangle and another rectangle.
///
/// The union is the smallest rectangle enclosing both rectangles.
///
/// # Examples
///
/// ```
/// # use bevy_math::{Rect, Vec2};
/// let r1 = Rect::new(0., 0., 5., 1.); // w=5 h=1
/// let r2 = Rect::new(1., -1., 3., 3.); // w=2 h=4
/// let r = r1.union(r2);
/// assert!(r.min.abs_diff_eq(Vec2::new(0., -1.), 1e-5));
/// assert!(r.max.abs_diff_eq(Vec2::new(5., 3.), 1e-5));
/// ```
#[inline]
pub fn union(&self, other: Self) -> Self {
Self {
min: self.min.min(other.min),
max: self.max.max(other.max),
}
}
/// Build a new rectangle formed of the union of this rectangle and a point.
///
/// The union is the smallest rectangle enclosing both the rectangle and the point. If the
/// point is already inside the rectangle, this method returns a copy of the rectangle.
///
/// # Examples
///
/// ```
/// # use bevy_math::{Rect, Vec2};
/// let r = Rect::new(0., 0., 5., 1.); // w=5 h=1
/// let u = r.union_point(Vec2::new(3., 6.));
/// assert!(u.min.abs_diff_eq(Vec2::ZERO, 1e-5));
/// assert!(u.max.abs_diff_eq(Vec2::new(5., 6.), 1e-5));
/// ```
#[inline]
pub fn union_point(&self, other: Vec2) -> Self {
Self {
min: self.min.min(other),
max: self.max.max(other),
}
}
/// Build a new rectangle formed of the intersection of this rectangle and another rectangle.
///
/// The intersection is the largest rectangle enclosed in both rectangles. If the intersection
/// is empty, this method returns an empty rectangle ([`Rect::is_empty()`] returns `true`), but
/// the actual values of [`Rect::min`] and [`Rect::max`] are implementation-dependent.
///
/// # Examples
///
/// ```
/// # use bevy_math::{Rect, Vec2};
/// let r1 = Rect::new(0., 0., 5., 1.); // w=5 h=1
/// let r2 = Rect::new(1., -1., 3., 3.); // w=2 h=4
/// let r = r1.intersect(r2);
/// assert!(r.min.abs_diff_eq(Vec2::new(1., 0.), 1e-5));
/// assert!(r.max.abs_diff_eq(Vec2::new(3., 1.), 1e-5));
/// ```
#[inline]
pub fn intersect(&self, other: Self) -> Self {
let mut r = Self {
min: self.min.max(other.min),
max: self.max.min(other.max),
};
// Collapse min over max to enforce invariants and ensure e.g. width() or
// height() never return a negative value.
r.min = r.min.min(r.max);
r
}
/// Create a new rectangle by expanding it evenly on all sides.
///
/// A positive expansion value produces a larger rectangle,
/// while a negative expansion value produces a smaller rectangle.
/// If this would result in zero or negative width or height, [`Rect::EMPTY`] is returned instead.
///
/// # Examples
///
/// ```
/// # use bevy_math::{Rect, Vec2};
/// let r = Rect::new(0., 0., 5., 1.); // w=5 h=1
/// let r2 = r.inflate(3.); // w=11 h=7
/// assert!(r2.min.abs_diff_eq(Vec2::splat(-3.), 1e-5));
/// assert!(r2.max.abs_diff_eq(Vec2::new(8., 4.), 1e-5));
///
/// let r = Rect::new(0., -1., 6., 7.); // w=6 h=8
/// let r2 = r.inflate(-2.); // w=11 h=7
/// assert!(r2.min.abs_diff_eq(Vec2::new(2., 1.), 1e-5));
/// assert!(r2.max.abs_diff_eq(Vec2::new(4., 5.), 1e-5));
/// ```
#[inline]
pub fn inflate(&self, expansion: f32) -> Self {
let mut r = Self {
min: self.min - expansion,
max: self.max + expansion,
};
// Collapse min over max to enforce invariants and ensure e.g. width() or
// height() never return a negative value.
r.min = r.min.min(r.max);
r
}
/// Build a new rectangle from this one with its coordinates expressed
/// relative to `other` in a normalized ([0..1] x [0..1]) coordinate system.
///
/// # Examples
///
/// ```
/// # use bevy_math::{Rect, Vec2};
/// let r = Rect::new(2., 3., 4., 6.);
/// let s = Rect::new(0., 0., 10., 10.);
/// let n = r.normalize(s);
///
/// assert_eq!(n.min.x, 0.2);
/// assert_eq!(n.min.y, 0.3);
/// assert_eq!(n.max.x, 0.4);
/// assert_eq!(n.max.y, 0.6);
/// ```
pub fn normalize(&self, other: Self) -> Self {
let outer_size = other.size();
Self {
min: (self.min - other.min) / outer_size,
max: (self.max - other.min) / outer_size,
}
}
/// Return the area of this rectangle.
///
/// # Examples
///
/// ```
/// # use bevy_math::Rect;
/// let r = Rect::new(0., 0., 10., 10.); // w=10 h=10
/// assert_eq!(r.area(), 100.0);
/// ```
#[inline]
pub fn area(&self) -> f32 {
self.width() * self.height()
}
/// Returns self as [`IRect`] (i32)
#[inline]
pub fn as_irect(&self) -> IRect {
IRect::from_corners(self.min.as_ivec2(), self.max.as_ivec2())
}
/// Returns self as [`URect`] (u32)
#[inline]
pub fn as_urect(&self) -> URect {
URect::from_corners(self.min.as_uvec2(), self.max.as_uvec2())
}
}
#[cfg(test)]
mod tests {
use crate::ops;
use super::*;
#[test]
fn well_formed() {
let r = Rect::from_center_size(Vec2::new(3., -5.), Vec2::new(8., 11.));
assert!(r.min.abs_diff_eq(Vec2::new(-1., -10.5), 1e-5));
assert!(r.max.abs_diff_eq(Vec2::new(7., 0.5), 1e-5));
assert!(r.center().abs_diff_eq(Vec2::new(3., -5.), 1e-5));
assert!(ops::abs(r.width() - 8.) <= 1e-5);
assert!(ops::abs(r.height() - 11.) <= 1e-5);
assert!(r.size().abs_diff_eq(Vec2::new(8., 11.), 1e-5));
assert!(r.half_size().abs_diff_eq(Vec2::new(4., 5.5), 1e-5));
assert!(r.contains(Vec2::new(3., -5.)));
assert!(r.contains(Vec2::new(-1., -10.5)));
assert!(r.contains(Vec2::new(-1., 0.5)));
assert!(r.contains(Vec2::new(7., -10.5)));
assert!(r.contains(Vec2::new(7., 0.5)));
assert!(!r.contains(Vec2::new(50., -5.)));
}
#[test]
fn rect_union() {
let r = Rect::from_center_size(Vec2::ZERO, Vec2::ONE); // [-0.5,-0.5] - [0.5,0.5]
// overlapping
let r2 = Rect {
min: Vec2::new(-0.8, 0.3),
max: Vec2::new(0.1, 0.7),
};
let u = r.union(r2);
assert!(u.min.abs_diff_eq(Vec2::new(-0.8, -0.5), 1e-5));
assert!(u.max.abs_diff_eq(Vec2::new(0.5, 0.7), 1e-5));
// disjoint
let r2 = Rect {
min: Vec2::new(-1.8, -0.5),
max: Vec2::new(-1.5, 0.3),
};
let u = r.union(r2);
assert!(u.min.abs_diff_eq(Vec2::new(-1.8, -0.5), 1e-5));
assert!(u.max.abs_diff_eq(Vec2::new(0.5, 0.5), 1e-5));
// included
let r2 = Rect::from_center_size(Vec2::ZERO, Vec2::splat(0.5));
let u = r.union(r2);
assert!(u.min.abs_diff_eq(r.min, 1e-5));
assert!(u.max.abs_diff_eq(r.max, 1e-5));
// including
let r2 = Rect::from_center_size(Vec2::ZERO, Vec2::splat(1.5));
let u = r.union(r2);
assert!(u.min.abs_diff_eq(r2.min, 1e-5));
assert!(u.max.abs_diff_eq(r2.max, 1e-5));
}
#[test]
fn rect_union_pt() {
let r = Rect::from_center_size(Vec2::ZERO, Vec2::ONE); // [-0.5,-0.5] - [0.5,0.5]
// inside
let v = Vec2::new(0.3, -0.2);
let u = r.union_point(v);
assert!(u.min.abs_diff_eq(r.min, 1e-5));
assert!(u.max.abs_diff_eq(r.max, 1e-5));
// outside
let v = Vec2::new(10., -3.);
let u = r.union_point(v);
assert!(u.min.abs_diff_eq(Vec2::new(-0.5, -3.), 1e-5));
assert!(u.max.abs_diff_eq(Vec2::new(10., 0.5), 1e-5));
}
#[test]
fn rect_intersect() {
let r = Rect::from_center_size(Vec2::ZERO, Vec2::ONE); // [-0.5,-0.5] - [0.5,0.5]
// overlapping
let r2 = Rect {
min: Vec2::new(-0.8, 0.3),
max: Vec2::new(0.1, 0.7),
};
let u = r.intersect(r2);
assert!(u.min.abs_diff_eq(Vec2::new(-0.5, 0.3), 1e-5));
assert!(u.max.abs_diff_eq(Vec2::new(0.1, 0.5), 1e-5));
// disjoint
let r2 = Rect {
min: Vec2::new(-1.8, -0.5),
max: Vec2::new(-1.5, 0.3),
};
let u = r.intersect(r2);
assert!(u.is_empty());
assert!(u.width() <= 1e-5);
// included
let r2 = Rect::from_center_size(Vec2::ZERO, Vec2::splat(0.5));
let u = r.intersect(r2);
assert!(u.min.abs_diff_eq(r2.min, 1e-5));
assert!(u.max.abs_diff_eq(r2.max, 1e-5));
// including
let r2 = Rect::from_center_size(Vec2::ZERO, Vec2::splat(1.5));
let u = r.intersect(r2);
assert!(u.min.abs_diff_eq(r.min, 1e-5));
assert!(u.max.abs_diff_eq(r.max, 1e-5));
}
#[test]
fn rect_inflate() {
let r = Rect::from_center_size(Vec2::ZERO, Vec2::ONE); // [-0.5,-0.5] - [0.5,0.5]
let r2 = r.inflate(0.3);
assert!(r2.min.abs_diff_eq(Vec2::new(-0.8, -0.8), 1e-5));
assert!(r2.max.abs_diff_eq(Vec2::new(0.8, 0.8), 1e-5));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/rects/mod.rs | crates/bevy_math/src/rects/mod.rs | mod irect;
mod rect;
mod urect;
pub use irect::IRect;
pub use rect::Rect;
pub use urect::URect;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/rects/irect.rs | crates/bevy_math/src/rects/irect.rs | use crate::{IVec2, Rect, URect};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
#[cfg(all(feature = "serialize", feature = "bevy_reflect"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
/// A rectangle defined by two opposite corners.
///
/// The rectangle is axis aligned, and defined by its minimum and maximum coordinates,
/// stored in `IRect::min` and `IRect::max`, respectively. The minimum/maximum invariant
/// must be upheld by the user when directly assigning the fields, otherwise some methods
/// produce invalid results. It is generally recommended to use one of the constructor
/// methods instead, which will ensure this invariant is met, unless you already have
/// the minimum and maximum corners.
#[repr(C)]
#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Hash, Default, Clone)
)]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct IRect {
/// The minimum corner point of the rect.
pub min: IVec2,
/// The maximum corner point of the rect.
pub max: IVec2,
}
impl IRect {
/// An empty `IRect`, represented by maximum and minimum corner points
/// with `max == IVec2::MIN` and `min == IVec2::MAX`, so the
/// rect has an extremely large negative size.
/// This is useful, because when taking a union B of a non-empty `IRect` A and
/// this empty `IRect`, B will simply equal A.
pub const EMPTY: Self = Self {
max: IVec2::MIN,
min: IVec2::MAX,
};
/// Create a new rectangle from two corner points.
///
/// The two points do not need to be the minimum and/or maximum corners.
/// They only need to be two opposite corners.
///
/// # Examples
///
/// ```
/// # use bevy_math::IRect;
/// let r = IRect::new(0, 4, 10, 6); // w=10 h=2
/// let r = IRect::new(2, 3, 5, -1); // w=3 h=4
/// ```
#[inline]
pub fn new(x0: i32, y0: i32, x1: i32, y1: i32) -> Self {
Self::from_corners(IVec2::new(x0, y0), IVec2::new(x1, y1))
}
/// Create a new rectangle from two corner points.
///
/// The two points do not need to be the minimum and/or maximum corners.
/// They only need to be two opposite corners.
///
/// # Examples
///
/// ```
/// # use bevy_math::{IRect, IVec2};
/// // Unit rect from [0,0] to [1,1]
/// let r = IRect::from_corners(IVec2::ZERO, IVec2::ONE); // w=1 h=1
/// // Same; the points do not need to be ordered
/// let r = IRect::from_corners(IVec2::ONE, IVec2::ZERO); // w=1 h=1
/// ```
#[inline]
pub fn from_corners(p0: IVec2, p1: IVec2) -> Self {
Self {
min: p0.min(p1),
max: p0.max(p1),
}
}
/// Create a new rectangle from its center and size.
///
/// # Rounding Behavior
///
/// If the size contains odd numbers they will be rounded down to the nearest whole number.
///
/// # Panics
///
/// This method panics if any of the components of the size is negative.
///
/// # Examples
///
/// ```
/// # use bevy_math::{IRect, IVec2};
/// let r = IRect::from_center_size(IVec2::ZERO, IVec2::new(3, 2)); // w=2 h=2
/// assert_eq!(r.min, IVec2::splat(-1));
/// assert_eq!(r.max, IVec2::splat(1));
/// ```
#[inline]
pub fn from_center_size(origin: IVec2, size: IVec2) -> Self {
debug_assert!(size.cmpge(IVec2::ZERO).all(), "IRect size must be positive");
let half_size = size / 2;
Self::from_center_half_size(origin, half_size)
}
/// Create a new rectangle from its center and half-size.
///
/// # Panics
///
/// This method panics if any of the components of the half-size is negative.
///
/// # Examples
///
/// ```
/// # use bevy_math::{IRect, IVec2};
/// let r = IRect::from_center_half_size(IVec2::ZERO, IVec2::ONE); // w=2 h=2
/// assert_eq!(r.min, IVec2::splat(-1));
/// assert_eq!(r.max, IVec2::splat(1));
/// ```
#[inline]
pub fn from_center_half_size(origin: IVec2, half_size: IVec2) -> Self {
assert!(
half_size.cmpge(IVec2::ZERO).all(),
"IRect half_size must be positive"
);
Self {
min: origin - half_size,
max: origin + half_size,
}
}
/// Check if the rectangle is empty.
///
/// # Examples
///
/// ```
/// # use bevy_math::{IRect, IVec2};
/// let r = IRect::from_corners(IVec2::ZERO, IVec2::new(0, 1)); // w=0 h=1
/// assert!(r.is_empty());
/// ```
#[inline]
pub fn is_empty(&self) -> bool {
self.min.cmpge(self.max).any()
}
/// Rectangle width (max.x - min.x).
///
/// # Examples
///
/// ```
/// # use bevy_math::IRect;
/// let r = IRect::new(0, 0, 5, 1); // w=5 h=1
/// assert_eq!(r.width(), 5);
/// ```
#[inline]
pub fn width(&self) -> i32 {
self.max.x - self.min.x
}
/// Rectangle height (max.y - min.y).
///
/// # Examples
///
/// ```
/// # use bevy_math::IRect;
/// let r = IRect::new(0, 0, 5, 1); // w=5 h=1
/// assert_eq!(r.height(), 1);
/// ```
#[inline]
pub fn height(&self) -> i32 {
self.max.y - self.min.y
}
/// Rectangle size.
///
/// # Examples
///
/// ```
/// # use bevy_math::{IRect, IVec2};
/// let r = IRect::new(0, 0, 5, 1); // w=5 h=1
/// assert_eq!(r.size(), IVec2::new(5, 1));
/// ```
#[inline]
pub fn size(&self) -> IVec2 {
self.max - self.min
}
/// Rectangle half-size.
///
/// # Rounding Behavior
///
/// If the full size contains odd numbers they will be rounded down to the nearest whole number when calculating the half size.
///
/// # Examples
///
/// ```
/// # use bevy_math::{IRect, IVec2};
/// let r = IRect::new(0, 0, 4, 3); // w=4 h=3
/// assert_eq!(r.half_size(), IVec2::new(2, 1));
/// ```
#[inline]
pub fn half_size(&self) -> IVec2 {
self.size() / 2
}
/// The center point of the rectangle.
///
/// # Rounding Behavior
///
/// If the (min + max) contains odd numbers they will be rounded down to the nearest whole number when calculating the center.
///
/// # Examples
///
/// ```
/// # use bevy_math::{IRect, IVec2};
/// let r = IRect::new(0, 0, 5, 2); // w=5 h=2
/// assert_eq!(r.center(), IVec2::new(2, 1));
/// ```
#[inline]
pub fn center(&self) -> IVec2 {
(self.min + self.max) / 2
}
/// Check if a point lies within this rectangle, inclusive of its edges.
///
/// # Examples
///
/// ```
/// # use bevy_math::IRect;
/// let r = IRect::new(0, 0, 5, 1); // w=5 h=1
/// assert!(r.contains(r.center()));
/// assert!(r.contains(r.min));
/// assert!(r.contains(r.max));
/// ```
#[inline]
pub fn contains(&self, point: IVec2) -> bool {
(point.cmpge(self.min) & point.cmple(self.max)).all()
}
/// Build a new rectangle formed of the union of this rectangle and another rectangle.
///
/// The union is the smallest rectangle enclosing both rectangles.
///
/// # Examples
///
/// ```
/// # use bevy_math::{IRect, IVec2};
/// let r1 = IRect::new(0, 0, 5, 1); // w=5 h=1
/// let r2 = IRect::new(1, -1, 3, 3); // w=2 h=4
/// let r = r1.union(r2);
/// assert_eq!(r.min, IVec2::new(0, -1));
/// assert_eq!(r.max, IVec2::new(5, 3));
/// ```
#[inline]
pub fn union(&self, other: Self) -> Self {
Self {
min: self.min.min(other.min),
max: self.max.max(other.max),
}
}
/// Build a new rectangle formed of the union of this rectangle and a point.
///
/// The union is the smallest rectangle enclosing both the rectangle and the point. If the
/// point is already inside the rectangle, this method returns a copy of the rectangle.
///
/// # Examples
///
/// ```
/// # use bevy_math::{IRect, IVec2};
/// let r = IRect::new(0, 0, 5, 1); // w=5 h=1
/// let u = r.union_point(IVec2::new(3, 6));
/// assert_eq!(u.min, IVec2::ZERO);
/// assert_eq!(u.max, IVec2::new(5, 6));
/// ```
#[inline]
pub fn union_point(&self, other: IVec2) -> Self {
Self {
min: self.min.min(other),
max: self.max.max(other),
}
}
/// Build a new rectangle formed of the intersection of this rectangle and another rectangle.
///
/// The intersection is the largest rectangle enclosed in both rectangles. If the intersection
/// is empty, this method returns an empty rectangle ([`IRect::is_empty()`] returns `true`), but
/// the actual values of [`IRect::min`] and [`IRect::max`] are implementation-dependent.
///
/// # Examples
///
/// ```
/// # use bevy_math::{IRect, IVec2};
/// let r1 = IRect::new(0, 0, 5, 1); // w=5 h=1
/// let r2 = IRect::new(1, -1, 3, 3); // w=2 h=4
/// let r = r1.intersect(r2);
/// assert_eq!(r.min, IVec2::new(1, 0));
/// assert_eq!(r.max, IVec2::new(3, 1));
/// ```
#[inline]
pub fn intersect(&self, other: Self) -> Self {
let mut r = Self {
min: self.min.max(other.min),
max: self.max.min(other.max),
};
// Collapse min over max to enforce invariants and ensure e.g. width() or
// height() never return a negative value.
r.min = r.min.min(r.max);
r
}
/// Create a new rectangle by expanding it evenly on all sides.
///
/// A positive expansion value produces a larger rectangle,
/// while a negative expansion value produces a smaller rectangle.
/// If this would result in zero or negative width or height, [`IRect::EMPTY`] is returned instead.
///
/// # Examples
///
/// ```
/// # use bevy_math::{IRect, IVec2};
/// let r = IRect::new(0, 0, 5, 1); // w=5 h=1
/// let r2 = r.inflate(3); // w=11 h=7
/// assert_eq!(r2.min, IVec2::splat(-3));
/// assert_eq!(r2.max, IVec2::new(8, 4));
///
/// let r = IRect::new(0, -1, 4, 3); // w=4 h=4
/// let r2 = r.inflate(-1); // w=2 h=2
/// assert_eq!(r2.min, IVec2::new(1, 0));
/// assert_eq!(r2.max, IVec2::new(3, 2));
/// ```
#[inline]
pub fn inflate(&self, expansion: i32) -> Self {
let mut r = Self {
min: self.min - expansion,
max: self.max + expansion,
};
// Collapse min over max to enforce invariants and ensure e.g. width() or
// height() never return a negative value.
r.min = r.min.min(r.max);
r
}
/// Returns self as [`Rect`] (f32)
#[inline]
pub fn as_rect(&self) -> Rect {
Rect::from_corners(self.min.as_vec2(), self.max.as_vec2())
}
/// Returns self as [`URect`] (u32)
#[inline]
pub fn as_urect(&self) -> URect {
URect::from_corners(self.min.as_uvec2(), self.max.as_uvec2())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn well_formed() {
let r = IRect::from_center_size(IVec2::new(3, -5), IVec2::new(8, 12));
assert_eq!(r.min, IVec2::new(-1, -11));
assert_eq!(r.max, IVec2::new(7, 1));
assert_eq!(r.center(), IVec2::new(3, -5));
assert_eq!(r.width().abs(), 8);
assert_eq!(r.height().abs(), 12);
assert_eq!(r.size(), IVec2::new(8, 12));
assert_eq!(r.half_size(), IVec2::new(4, 6));
assert!(r.contains(IVec2::new(3, -5)));
assert!(r.contains(IVec2::new(-1, -10)));
assert!(r.contains(IVec2::new(-1, 0)));
assert!(r.contains(IVec2::new(7, -10)));
assert!(r.contains(IVec2::new(7, 0)));
assert!(!r.contains(IVec2::new(50, -5)));
}
#[test]
fn rect_union() {
let r = IRect::from_center_size(IVec2::ZERO, IVec2::splat(4)); // [-2, -2] - [2, 2]
// overlapping
let r2 = IRect {
min: IVec2::new(1, 1),
max: IVec2::new(3, 3),
};
let u = r.union(r2);
assert_eq!(u.min, IVec2::new(-2, -2));
assert_eq!(u.max, IVec2::new(3, 3));
// disjoint
let r2 = IRect {
min: IVec2::new(1, 4),
max: IVec2::new(4, 6),
};
let u = r.union(r2);
assert_eq!(u.min, IVec2::new(-2, -2));
assert_eq!(u.max, IVec2::new(4, 6));
// included
let r2 = IRect::from_center_size(IVec2::ZERO, IVec2::splat(2));
let u = r.union(r2);
assert_eq!(u.min, r.min);
assert_eq!(u.max, r.max);
// including
let r2 = IRect::from_center_size(IVec2::ZERO, IVec2::splat(6));
let u = r.union(r2);
assert_eq!(u.min, r2.min);
assert_eq!(u.min, r2.min);
}
#[test]
fn rect_union_pt() {
let r = IRect::from_center_size(IVec2::ZERO, IVec2::splat(4)); // [-2,-2] - [2,2]
// inside
let v = IVec2::new(1, -1);
let u = r.union_point(v);
assert_eq!(u.min, r.min);
assert_eq!(u.max, r.max);
// outside
let v = IVec2::new(10, -3);
let u = r.union_point(v);
assert_eq!(u.min, IVec2::new(-2, -3));
assert_eq!(u.max, IVec2::new(10, 2));
}
#[test]
fn rect_intersect() {
let r = IRect::from_center_size(IVec2::ZERO, IVec2::splat(8)); // [-4,-4] - [4,4]
// overlapping
let r2 = IRect {
min: IVec2::new(2, 2),
max: IVec2::new(6, 6),
};
let u = r.intersect(r2);
assert_eq!(u.min, IVec2::new(2, 2));
assert_eq!(u.max, IVec2::new(4, 4));
// disjoint
let r2 = IRect {
min: IVec2::new(-8, -2),
max: IVec2::new(-6, 2),
};
let u = r.intersect(r2);
assert!(u.is_empty());
assert_eq!(u.width(), 0);
// included
let r2 = IRect::from_center_size(IVec2::ZERO, IVec2::splat(2));
let u = r.intersect(r2);
assert_eq!(u.min, r2.min);
assert_eq!(u.max, r2.max);
// including
let r2 = IRect::from_center_size(IVec2::ZERO, IVec2::splat(10));
let u = r.intersect(r2);
assert_eq!(u.min, r.min);
assert_eq!(u.max, r.max);
}
#[test]
fn rect_inflate() {
let r = IRect::from_center_size(IVec2::ZERO, IVec2::splat(4)); // [-2,-2] - [2,2]
let r2 = r.inflate(2);
assert_eq!(r2.min, IVec2::new(-4, -4));
assert_eq!(r2.max, IVec2::new(4, 4));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/sampling/shape_sampling.rs | crates/bevy_math/src/sampling/shape_sampling.rs | //! The [`ShapeSample`] trait, allowing random sampling from geometric shapes.
//!
//! At the most basic level, this allows sampling random points from the interior and boundary of
//! geometric primitives. For example:
//! ```
//! # use bevy_math::primitives::*;
//! # use bevy_math::ShapeSample;
//! # use rand::SeedableRng;
//! # use rand::rngs::StdRng;
//! // Get some `Rng`:
//! let rng = &mut StdRng::from_os_rng();
//! // Make a circle of radius 2:
//! let circle = Circle::new(2.0);
//! // Get a point inside this circle uniformly at random:
//! let interior_pt = circle.sample_interior(rng);
//! // Get a point on the circle's boundary uniformly at random:
//! let boundary_pt = circle.sample_boundary(rng);
//! ```
//!
//! For repeated sampling, `ShapeSample` also includes methods for accessing a [`Distribution`]:
//! ```
//! # use bevy_math::primitives::*;
//! # use bevy_math::{Vec2, ShapeSample};
//! # use rand::SeedableRng;
//! # use rand::rngs::StdRng;
//! # use rand::distr::Distribution;
//! # let rng1 = StdRng::from_os_rng();
//! # let rng2 = StdRng::from_os_rng();
//! // Use a rectangle this time:
//! let rectangle = Rectangle::new(1.0, 2.0);
//! // Get an iterator that spits out random interior points:
//! let interior_iter = rectangle.interior_dist().sample_iter(rng1);
//! // Collect random interior points from the iterator:
//! let interior_pts: Vec<Vec2> = interior_iter.take(1000).collect();
//! // Similarly, get an iterator over many random boundary points and collect them:
//! let boundary_pts: Vec<Vec2> = rectangle.boundary_dist().sample_iter(rng2).take(1000).collect();
//! ```
//!
//! In any case, the [`Rng`] used as the source of randomness must be provided explicitly.
use core::f32::consts::{FRAC_PI_2, PI, TAU};
use crate::{ops, primitives::*, NormedVectorSpace, ScalarField, Vec2, Vec3};
use rand::{
distr::{
uniform::SampleUniform,
weighted::{Weight, WeightedIndex},
Distribution,
},
Rng,
};
/// Exposes methods to uniformly sample a variety of primitive shapes.
pub trait ShapeSample {
/// The type of vector returned by the sample methods, [`Vec2`] for 2D shapes and [`Vec3`] for 3D shapes.
type Output;
/// Uniformly sample a point from inside the area/volume of this shape, centered on 0.
///
/// Shapes like [`Cylinder`], [`Capsule2d`] and [`Capsule3d`] are oriented along the y-axis.
///
/// # Example
/// ```
/// # use bevy_math::prelude::*;
/// let square = Rectangle::new(2.0, 2.0);
///
/// // Returns a Vec2 with both x and y between -1 and 1.
/// println!("{}", square.sample_interior(&mut rand::rng()));
/// ```
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output;
/// Uniformly sample a point from the surface of this shape, centered on 0.
///
/// Shapes like [`Cylinder`], [`Capsule2d`] and [`Capsule3d`] are oriented along the y-axis.
///
/// # Example
/// ```
/// # use bevy_math::prelude::*;
/// let square = Rectangle::new(2.0, 2.0);
///
/// // Returns a Vec2 where one of the coordinates is at ±1,
/// // and the other is somewhere between -1 and 1.
/// println!("{}", square.sample_boundary(&mut rand::rng()));
/// ```
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output;
/// Extract a [`Distribution`] whose samples are points of this shape's interior, taken uniformly.
///
/// # Example
///
/// ```
/// # use bevy_math::prelude::*;
/// # use rand::distr::Distribution;
/// let square = Rectangle::new(2.0, 2.0);
/// let rng = rand::rng();
///
/// // Iterate over points randomly drawn from `square`'s interior:
/// for random_val in square.interior_dist().sample_iter(rng).take(5) {
/// println!("{}", random_val);
/// }
/// ```
fn interior_dist(self) -> impl Distribution<Self::Output>
where
Self: Sized,
{
InteriorOf(self)
}
/// Extract a [`Distribution`] whose samples are points of this shape's boundary, taken uniformly.
///
/// # Example
///
/// ```
/// # use bevy_math::prelude::*;
/// # use rand::distr::Distribution;
/// let square = Rectangle::new(2.0, 2.0);
/// let rng = rand::rng();
///
/// // Iterate over points randomly drawn from `square`'s boundary:
/// for random_val in square.boundary_dist().sample_iter(rng).take(5) {
/// println!("{}", random_val);
/// }
/// ```
fn boundary_dist(self) -> impl Distribution<Self::Output>
where
Self: Sized,
{
BoundaryOf(self)
}
}
#[derive(Clone, Copy)]
/// A wrapper struct that allows interior sampling from a [`ShapeSample`] type directly as
/// a [`Distribution`].
pub struct InteriorOf<T: ShapeSample>(pub T);
#[derive(Clone, Copy)]
/// A wrapper struct that allows boundary sampling from a [`ShapeSample`] type directly as
/// a [`Distribution`].
pub struct BoundaryOf<T: ShapeSample>(pub T);
impl<T: ShapeSample> Distribution<<T as ShapeSample>::Output> for InteriorOf<T> {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> <T as ShapeSample>::Output {
self.0.sample_interior(rng)
}
}
impl<T: ShapeSample> Distribution<<T as ShapeSample>::Output> for BoundaryOf<T> {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> <T as ShapeSample>::Output {
self.0.sample_boundary(rng)
}
}
impl ShapeSample for Circle {
type Output = Vec2;
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec2 {
// https://mathworld.wolfram.com/DiskPointPicking.html
let theta = rng.random_range(0.0..TAU);
let r_squared = rng.random_range(0.0..=(self.radius * self.radius));
let r = ops::sqrt(r_squared);
let (sin, cos) = ops::sin_cos(theta);
Vec2::new(r * cos, r * sin)
}
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec2 {
let theta = rng.random_range(0.0..TAU);
let (sin, cos) = ops::sin_cos(theta);
Vec2::new(self.radius * cos, self.radius * sin)
}
}
impl ShapeSample for CircularSector {
type Output = Vec2;
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec2 {
let theta = rng.random_range(-self.half_angle()..=self.half_angle());
let r_squared = rng.random_range(0.0..=(self.radius() * self.radius()));
let r = ops::sqrt(r_squared);
let (sin, cos) = ops::sin_cos(theta);
Vec2::new(r * sin, r * cos)
}
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec2 {
if rng.random_range(0.0..=1.0) <= self.arc_length() / self.perimeter() {
// Sample on the arc
let theta = FRAC_PI_2 + rng.random_range(-self.half_angle()..self.half_angle());
Vec2::from_angle(theta) * self.radius()
} else {
// Sample on the "inner" straight lines
let dir = self.radius() * Vec2::from_angle(FRAC_PI_2 + self.half_angle());
let r: f32 = rng.random_range(-1.0..1.0);
(-r).clamp(0.0, 1.0) * dir + r.clamp(0.0, 1.0) * dir * Vec2::new(-1.0, 1.0)
}
}
}
/// Boundary sampling for unit-spheres
#[inline]
fn sample_unit_sphere_boundary<R: Rng + ?Sized>(rng: &mut R) -> Vec3 {
let z = rng.random_range(-1f32..=1f32);
let (a_sin, a_cos) = ops::sin_cos(rng.random_range(-PI..=PI));
let c = ops::sqrt(1f32 - z * z);
let x = a_sin * c;
let y = a_cos * c;
Vec3::new(x, y, z)
}
impl ShapeSample for Sphere {
type Output = Vec3;
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 {
let r_cubed = rng.random_range(0.0..=(self.radius * self.radius * self.radius));
let r = ops::cbrt(r_cubed);
r * sample_unit_sphere_boundary(rng)
}
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 {
self.radius * sample_unit_sphere_boundary(rng)
}
}
impl ShapeSample for Annulus {
type Output = Vec2;
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output {
let inner_radius = self.inner_circle.radius;
let outer_radius = self.outer_circle.radius;
// Like random sampling for a circle, radius is weighted by the square.
let r_squared =
rng.random_range((inner_radius * inner_radius)..(outer_radius * outer_radius));
let r = ops::sqrt(r_squared);
let theta = rng.random_range(0.0..TAU);
let (sin, cos) = ops::sin_cos(theta);
Vec2::new(r * cos, r * sin)
}
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output {
let total_perimeter = self.inner_circle.perimeter() + self.outer_circle.perimeter();
let inner_prob = (self.inner_circle.perimeter() / total_perimeter) as f64;
// Sample from boundary circles, choosing which one by weighting by perimeter:
let inner = rng.random_bool(inner_prob);
if inner {
self.inner_circle.sample_boundary(rng)
} else {
self.outer_circle.sample_boundary(rng)
}
}
}
impl ShapeSample for Rhombus {
type Output = Vec2;
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec2 {
let x: f32 = rng.random_range(0.0..=1.0);
let y: f32 = rng.random_range(0.0..=1.0);
let unit_p = Vec2::NEG_X + x * Vec2::ONE + Vec2::new(y, -y);
unit_p * self.half_diagonals
}
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec2 {
let x: f32 = rng.random_range(-1.0..=1.0);
let y_sign = if rng.random() { -1.0 } else { 1.0 };
let y = (1.0 - ops::abs(x)) * y_sign;
Vec2::new(x, y) * self.half_diagonals
}
}
impl ShapeSample for Rectangle {
type Output = Vec2;
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec2 {
let x = rng.random_range(-self.half_size.x..=self.half_size.x);
let y = rng.random_range(-self.half_size.y..=self.half_size.y);
Vec2::new(x, y)
}
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec2 {
let primary_side = rng.random_range(-1.0..1.0);
let other_side = if rng.random() { -1.0 } else { 1.0 };
if self.half_size.x + self.half_size.y > 0.0 {
if rng.random_bool((self.half_size.x / (self.half_size.x + self.half_size.y)) as f64) {
Vec2::new(primary_side, other_side) * self.half_size
} else {
Vec2::new(other_side, primary_side) * self.half_size
}
} else {
Vec2::ZERO
}
}
}
impl ShapeSample for Cuboid {
type Output = Vec3;
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 {
let x = rng.random_range(-self.half_size.x..=self.half_size.x);
let y = rng.random_range(-self.half_size.y..=self.half_size.y);
let z = rng.random_range(-self.half_size.z..=self.half_size.z);
Vec3::new(x, y, z)
}
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 {
let primary_side1 = rng.random_range(-1.0..1.0);
let primary_side2 = rng.random_range(-1.0..1.0);
let other_side = if rng.random() { -1.0 } else { 1.0 };
if let Ok(dist) = WeightedIndex::new([
self.half_size.y * self.half_size.z,
self.half_size.x * self.half_size.z,
self.half_size.x * self.half_size.y,
]) {
match dist.sample(rng) {
0 => Vec3::new(other_side, primary_side1, primary_side2) * self.half_size,
1 => Vec3::new(primary_side1, other_side, primary_side2) * self.half_size,
2 => Vec3::new(primary_side1, primary_side2, other_side) * self.half_size,
_ => unreachable!(),
}
} else {
Vec3::ZERO
}
}
}
/// Interior sampling for triangles which doesn't depend on the ambient dimension.
fn sample_triangle_interior<P, R>(vertices: [P; 3], rng: &mut R) -> P
where
P: NormedVectorSpace,
P::Scalar: SampleUniform + PartialOrd,
R: Rng + ?Sized,
{
let [a, b, c] = vertices;
let ab = b - a;
let ac = c - a;
// Generate random points on a parallelepiped and reflect so that
// we can use the points that lie outside the triangle
let u = rng.random_range(P::Scalar::ZERO..=P::Scalar::ONE);
let v = rng.random_range(P::Scalar::ZERO..=P::Scalar::ONE);
if u + v > P::Scalar::ONE {
let u1 = P::Scalar::ONE - v;
let v1 = P::Scalar::ONE - u;
a + (ab * u1 + ac * v1)
} else {
a + (ab * u + ac * v)
}
}
/// Boundary sampling for triangles which doesn't depend on the ambient dimension.
fn sample_triangle_boundary<P, R>(vertices: [P; 3], rng: &mut R) -> P
where
P: NormedVectorSpace,
P::Scalar: Weight + SampleUniform + PartialOrd + for<'a> ::core::ops::AddAssign<&'a P::Scalar>,
R: Rng + ?Sized,
{
let [a, b, c] = vertices;
let ab = b - a;
let ac = c - a;
let bc = c - b;
let t = rng.random_range(<P::Scalar as ScalarField>::ZERO..=P::Scalar::ONE);
if let Ok(dist) = WeightedIndex::new([ab.norm(), ac.norm(), bc.norm()]) {
match dist.sample(rng) {
0 => a.lerp(b, t),
1 => a.lerp(c, t),
2 => b.lerp(c, t),
_ => unreachable!(),
}
} else {
// This should only occur when the triangle is 0-dimensional degenerate
// so this is actually the correct result.
a
}
}
impl ShapeSample for Triangle2d {
type Output = Vec2;
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output {
sample_triangle_interior(self.vertices, rng)
}
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output {
sample_triangle_boundary(self.vertices, rng)
}
}
impl ShapeSample for Triangle3d {
type Output = Vec3;
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output {
sample_triangle_interior(self.vertices, rng)
}
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output {
sample_triangle_boundary(self.vertices, rng)
}
}
impl ShapeSample for Tetrahedron {
type Output = Vec3;
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output {
let [v0, v1, v2, v3] = self.vertices;
// Generate a random point in a cube:
let mut coords: [f32; 3] = [
rng.random_range(0.0..1.0),
rng.random_range(0.0..1.0),
rng.random_range(0.0..1.0),
];
// The cube is broken into six tetrahedra of the form 0 <= c_0 <= c_1 <= c_2 <= 1,
// where c_i are the three euclidean coordinates in some permutation. (Since 3! = 6,
// there are six of them). Sorting the coordinates folds these six tetrahedra into the
// tetrahedron 0 <= x <= y <= z <= 1 (i.e. a fundamental domain of the permutation action).
coords.sort_by(|x, y| x.partial_cmp(y).unwrap());
// Now, convert a point from the fundamental tetrahedron into barycentric coordinates by
// taking the four successive differences of coordinates; note that these telescope to sum
// to 1, and this transformation is linear, hence preserves the probability density, since
// the latter comes from the Lebesgue measure.
//
// (See https://en.wikipedia.org/wiki/Lebesgue_measure#Properties — specifically, that
// Lebesgue measure of a linearly transformed set is its original measure times the
// determinant.)
let (a, b, c, d) = (
coords[0],
coords[1] - coords[0],
coords[2] - coords[1],
1. - coords[2],
);
// This is also a linear mapping, so probability density is still preserved.
v0 * a + v1 * b + v2 * c + v3 * d
}
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output {
let triangles = self.faces();
let areas = triangles.iter().map(Measured2d::area);
if areas.clone().sum::<f32>() > 0.0 {
// There is at least one triangle with nonzero area, so this unwrap succeeds.
let dist = WeightedIndex::new(areas).unwrap();
// Get a random index, then sample the interior of the associated triangle.
let idx = dist.sample(rng);
triangles[idx].sample_interior(rng)
} else {
// In this branch the tetrahedron has zero surface area; just return a point that's on
// the tetrahedron.
self.vertices[0]
}
}
}
impl ShapeSample for Cylinder {
type Output = Vec3;
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 {
let Vec2 { x, y: z } = self.base().sample_interior(rng);
let y = rng.random_range(-self.half_height..=self.half_height);
Vec3::new(x, y, z)
}
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 {
// This uses the area of the ends divided by the overall surface area (optimized)
// [2 (\pi r^2)]/[2 (\pi r^2) + 2 \pi r h] = r/(r + h)
if self.radius + 2.0 * self.half_height > 0.0 {
if rng.random_bool((self.radius / (self.radius + 2.0 * self.half_height)) as f64) {
let Vec2 { x, y: z } = self.base().sample_interior(rng);
if rng.random() {
Vec3::new(x, self.half_height, z)
} else {
Vec3::new(x, -self.half_height, z)
}
} else {
let Vec2 { x, y: z } = self.base().sample_boundary(rng);
let y = rng.random_range(-self.half_height..=self.half_height);
Vec3::new(x, y, z)
}
} else {
Vec3::ZERO
}
}
}
impl ShapeSample for Capsule2d {
type Output = Vec2;
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec2 {
let rectangle_area = self.half_length * self.radius * 4.0;
let capsule_area = rectangle_area + PI * self.radius * self.radius;
if capsule_area > 0.0 {
// Check if the random point should be inside the rectangle
if rng.random_bool((rectangle_area / capsule_area) as f64) {
self.to_inner_rectangle().sample_interior(rng)
} else {
let circle = Circle::new(self.radius);
let point = circle.sample_interior(rng);
// Add half length if it is the top semi-circle, otherwise subtract half
if point.y > 0.0 {
point + Vec2::Y * self.half_length
} else {
point - Vec2::Y * self.half_length
}
}
} else {
Vec2::ZERO
}
}
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec2 {
let rectangle_surface = 4.0 * self.half_length;
let capsule_surface = rectangle_surface + TAU * self.radius;
if capsule_surface > 0.0 {
if rng.random_bool((rectangle_surface / capsule_surface) as f64) {
let side_distance =
rng.random_range((-2.0 * self.half_length)..=(2.0 * self.half_length));
if side_distance < 0.0 {
Vec2::new(self.radius, side_distance + self.half_length)
} else {
Vec2::new(-self.radius, side_distance - self.half_length)
}
} else {
let circle = Circle::new(self.radius);
let point = circle.sample_boundary(rng);
// Add half length if it is the top semi-circle, otherwise subtract half
if point.y > 0.0 {
point + Vec2::Y * self.half_length
} else {
point - Vec2::Y * self.half_length
}
}
} else {
Vec2::ZERO
}
}
}
impl ShapeSample for Capsule3d {
type Output = Vec3;
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 {
let cylinder_vol = PI * self.radius * self.radius * 2.0 * self.half_length;
// Add 4/3 pi r^3
let capsule_vol = cylinder_vol + 4.0 / 3.0 * PI * self.radius * self.radius * self.radius;
if capsule_vol > 0.0 {
// Check if the random point should be inside the cylinder
if rng.random_bool((cylinder_vol / capsule_vol) as f64) {
self.to_cylinder().sample_interior(rng)
} else {
let sphere = Sphere::new(self.radius);
let point = sphere.sample_interior(rng);
// Add half length if it is the top semi-sphere, otherwise subtract half
if point.y > 0.0 {
point + Vec3::Y * self.half_length
} else {
point - Vec3::Y * self.half_length
}
}
} else {
Vec3::ZERO
}
}
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 {
let cylinder_surface = TAU * self.radius * 2.0 * self.half_length;
let capsule_surface = cylinder_surface + 4.0 * PI * self.radius * self.radius;
if capsule_surface > 0.0 {
if rng.random_bool((cylinder_surface / capsule_surface) as f64) {
let Vec2 { x, y: z } = Circle::new(self.radius).sample_boundary(rng);
let y = rng.random_range(-self.half_length..=self.half_length);
Vec3::new(x, y, z)
} else {
let sphere = Sphere::new(self.radius);
let point = sphere.sample_boundary(rng);
// Add half length if it is the top semi-sphere, otherwise subtract half
if point.y > 0.0 {
point + Vec3::Y * self.half_length
} else {
point - Vec3::Y * self.half_length
}
}
} else {
Vec3::ZERO
}
}
}
impl<P: Primitive2d + Measured2d + ShapeSample<Output = Vec2>> ShapeSample for Extrusion<P> {
type Output = Vec3;
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output {
let base_point = self.base_shape.sample_interior(rng);
let depth = rng.random_range(-self.half_depth..self.half_depth);
base_point.extend(depth)
}
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output {
let base_area = self.base_shape.area();
let total_area = self.area();
let random = rng.random_range(0.0..total_area);
match random {
x if x < base_area => self.base_shape.sample_interior(rng).extend(self.half_depth),
x if x < 2. * base_area => self
.base_shape
.sample_interior(rng)
.extend(-self.half_depth),
_ => self
.base_shape
.sample_boundary(rng)
.extend(rng.random_range(-self.half_depth..self.half_depth)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::SeedableRng;
use rand_chacha::ChaCha8Rng;
#[test]
fn circle_interior_sampling() {
let mut rng = ChaCha8Rng::from_seed(Default::default());
let circle = Circle::new(8.0);
let boxes = [
(-3.0, 3.0),
(1.0, 2.0),
(-1.0, -2.0),
(3.0, -2.0),
(1.0, -6.0),
(-3.0, -7.0),
(-7.0, -3.0),
(-6.0, 1.0),
];
let mut box_hits = [0; 8];
// Checks which boxes (if any) the sampled points are in
for _ in 0..5000 {
let point = circle.sample_interior(&mut rng);
for (i, box_) in boxes.iter().enumerate() {
if (point.x > box_.0 && point.x < box_.0 + 4.0)
&& (point.y > box_.1 && point.y < box_.1 + 4.0)
{
box_hits[i] += 1;
}
}
}
assert_eq!(
box_hits,
[396, 377, 415, 404, 366, 408, 408, 430],
"samples will occur across all array items at statistically equal chance"
);
}
#[test]
fn circle_boundary_sampling() {
let mut rng = ChaCha8Rng::from_seed(Default::default());
let circle = Circle::new(1.0);
let mut wedge_hits = [0; 8];
// Checks in which eighth of the circle each sampled point is in
for _ in 0..5000 {
let point = circle.sample_boundary(&mut rng);
let angle = ops::atan(point.y / point.x) + PI / 2.0;
let wedge = ops::floor(angle * 8.0 / PI) as usize;
wedge_hits[wedge] += 1;
}
assert_eq!(
wedge_hits,
[636, 608, 639, 603, 614, 650, 640, 610],
"samples will occur across all array items at statistically equal chance"
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/sampling/standard.rs | crates/bevy_math/src/sampling/standard.rs | //! This module holds local implementations of the [`Distribution`] trait for [`StandardUniform`], which
//! allow certain Bevy math types (those whose values can be randomly generated without additional
//! input other than an [`Rng`]) to be produced using [`rand`]'s APIs. It also holds [`FromRng`],
//! an ergonomic extension to that functionality which permits the omission of type annotations.
//!
//! For instance:
//! ```
//! # use rand::{random, Rng, SeedableRng, rngs::StdRng, distr::StandardUniform};
//! # use bevy_math::{Dir3, sampling::FromRng};
//! let mut rng = StdRng::seed_from_u64(7313429298);
//! // Random direction using thread-local rng
//! let random_direction1: Dir3 = random();
//!
//! // Random direction using the rng constructed above
//! let random_direction2: Dir3 = rng.random();
//!
//! // The same as the previous but with different syntax
//! let random_direction3 = Dir3::from_rng(&mut rng);
//!
//! // Five random directions, using StandardUniform explicitly
//! let many_random_directions: Vec<Dir3> = rng.sample_iter(StandardUniform).take(5).collect();
//! ```
use core::f32::consts::TAU;
use crate::{
primitives::{Circle, Sphere},
Dir2, Dir3, Dir3A, Quat, Rot2, ShapeSample, Vec3A,
};
use rand::{
distr::{Distribution, StandardUniform},
Rng,
};
/// Ergonomics trait for a type with a [`StandardUniform`] distribution, allowing values to be generated
/// uniformly from an [`Rng`] by a method in its own namespace.
///
/// Example
/// ```
/// # use rand::{Rng, SeedableRng, rngs::StdRng};
/// # use bevy_math::{Dir3, sampling::FromRng};
/// let mut rng = StdRng::seed_from_u64(451);
/// let random_dir = Dir3::from_rng(&mut rng);
/// ```
pub trait FromRng
where
Self: Sized,
StandardUniform: Distribution<Self>,
{
/// Construct a value of this type uniformly at random using `rng` as the source of randomness.
fn from_rng<R: Rng + ?Sized>(rng: &mut R) -> Self {
rng.random()
}
}
impl Distribution<Dir2> for StandardUniform {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Dir2 {
let circle = Circle::new(1.0);
let vector = circle.sample_boundary(rng);
Dir2::new_unchecked(vector)
}
}
impl FromRng for Dir2 {}
impl Distribution<Dir3> for StandardUniform {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Dir3 {
let sphere = Sphere::new(1.0);
let vector = sphere.sample_boundary(rng);
Dir3::new_unchecked(vector)
}
}
impl FromRng for Dir3 {}
impl Distribution<Dir3A> for StandardUniform {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Dir3A {
let sphere = Sphere::new(1.0);
let vector: Vec3A = sphere.sample_boundary(rng).into();
Dir3A::new_unchecked(vector)
}
}
impl FromRng for Dir3A {}
impl Distribution<Rot2> for StandardUniform {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Rot2 {
let angle = rng.random_range(0.0..TAU);
Rot2::radians(angle)
}
}
impl FromRng for Rot2 {}
impl FromRng for Quat {}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/sampling/mod.rs | crates/bevy_math/src/sampling/mod.rs | //! This module contains tools related to random sampling.
//!
//! To use this, the "rand" feature must be enabled.
#[cfg(feature = "alloc")]
pub mod mesh_sampling;
pub mod shape_sampling;
pub mod standard;
#[cfg(feature = "alloc")]
pub use mesh_sampling::*;
pub use shape_sampling::*;
pub use standard::*;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_math/src/sampling/mesh_sampling.rs | crates/bevy_math/src/sampling/mesh_sampling.rs | //! Functionality related to random sampling from triangle meshes.
use crate::{
primitives::{Measured2d, Triangle3d},
ShapeSample, Vec3,
};
use alloc::vec::Vec;
use rand::Rng;
use rand_distr::{
weighted::{Error as WeightedError, WeightedAliasIndex},
Distribution,
};
/// A [distribution] that caches data to allow fast sampling from a collection of triangles.
/// Generally used through [`sample`] or [`sample_iter`].
///
/// [distribution]: Distribution
/// [`sample`]: Distribution::sample
/// [`sample_iter`]: Distribution::sample_iter
///
/// Example
/// ```
/// # use bevy_math::{Vec3, primitives::*};
/// # use bevy_math::sampling::mesh_sampling::UniformMeshSampler;
/// # use rand::{SeedableRng, rngs::StdRng, distr::Distribution};
/// let faces = Tetrahedron::default().faces();
/// let sampler = UniformMeshSampler::try_new(faces).unwrap();
/// let rng = StdRng::seed_from_u64(8765309);
/// // 50 random points on the tetrahedron:
/// let samples: Vec<Vec3> = sampler.sample_iter(rng).take(50).collect();
/// ```
pub struct UniformMeshSampler {
triangles: Vec<Triangle3d>,
face_distribution: WeightedAliasIndex<f32>,
}
impl Distribution<Vec3> for UniformMeshSampler {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 {
let face_index = self.face_distribution.sample(rng);
self.triangles[face_index].sample_interior(rng)
}
}
impl UniformMeshSampler {
/// Construct a new [`UniformMeshSampler`] from a list of [triangles].
///
/// Returns an error if the distribution of areas for the collection of triangles could not be formed
/// (most notably if the collection has zero surface area).
///
/// [triangles]: Triangle3d
pub fn try_new<T: IntoIterator<Item = Triangle3d>>(
triangles: T,
) -> Result<Self, WeightedError> {
let triangles: Vec<Triangle3d> = triangles.into_iter().collect();
let areas = triangles.iter().map(Measured2d::area).collect();
WeightedAliasIndex::new(areas).map(|face_distribution| Self {
triangles,
face_distribution,
})
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_remote/src/builtin_methods.rs | crates/bevy_remote/src/builtin_methods.rs | //! Built-in verbs for the Bevy Remote Protocol.
use core::any::TypeId;
use anyhow::{anyhow, Result as AnyhowResult};
use bevy_ecs::{
component::ComponentId,
entity::Entity,
hierarchy::ChildOf,
lifecycle::RemovedComponentEntity,
message::MessageCursor,
query::QueryBuilder,
reflect::{AppTypeRegistry, ReflectComponent, ReflectEvent, ReflectResource},
system::{In, Local},
world::{EntityRef, EntityWorldMut, FilteredEntityRef, Mut, World},
};
use bevy_log::warn_once;
use bevy_platform::collections::HashMap;
use bevy_reflect::{
serde::{ReflectSerializer, TypedReflectDeserializer},
DynamicStruct, GetPath, PartialReflect, TypeRegistration, TypeRegistry,
};
use serde::{de::DeserializeSeed as _, de::IntoDeserializer, Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::{
error_codes,
schemas::{
json_schema::{export_type, JsonSchemaBevyType},
open_rpc::OpenRpcDocument,
},
BrpError, BrpResult,
};
#[cfg(all(feature = "http", not(target_family = "wasm")))]
use {crate::schemas::open_rpc::ServerObject, bevy_utils::default};
/// The method path for a `world.get_components` request.
pub const BRP_GET_COMPONENTS_METHOD: &str = "world.get_components";
/// The method path for a `world.query` request.
pub const BRP_QUERY_METHOD: &str = "world.query";
/// The method path for a `world.spawn_entity` request.
pub const BRP_SPAWN_ENTITY_METHOD: &str = "world.spawn_entity";
/// The method path for a `world.insert_components` request.
pub const BRP_INSERT_COMPONENTS_METHOD: &str = "world.insert_components";
/// The method path for a `world.remove_components` request.
pub const BRP_REMOVE_COMPONENTS_METHOD: &str = "world.remove_components";
/// The method path for a `world.despawn_entity` request.
pub const BRP_DESPAWN_COMPONENTS_METHOD: &str = "world.despawn_entity";
/// The method path for a `world.reparent_entities` request.
pub const BRP_REPARENT_ENTITIES_METHOD: &str = "world.reparent_entities";
/// The method path for a `world.list_components` request.
pub const BRP_LIST_COMPONENTS_METHOD: &str = "world.list_components";
/// The method path for a `world.mutate_components` request.
pub const BRP_MUTATE_COMPONENTS_METHOD: &str = "world.mutate_components";
/// The method path for a `world.get_components+watch` request.
pub const BRP_GET_COMPONENTS_AND_WATCH_METHOD: &str = "world.get_components+watch";
/// The method path for a `world.list_components+watch` request.
pub const BRP_LIST_COMPONENTS_AND_WATCH_METHOD: &str = "world.list_components+watch";
/// The method path for a `world.get_resources` request.
pub const BRP_GET_RESOURCE_METHOD: &str = "world.get_resources";
/// The method path for a `world.insert_resources` request.
pub const BRP_INSERT_RESOURCE_METHOD: &str = "world.insert_resources";
/// The method path for a `world.remove_resources` request.
pub const BRP_REMOVE_RESOURCE_METHOD: &str = "world.remove_resources";
/// The method path for a `world.mutate_resources` request.
pub const BRP_MUTATE_RESOURCE_METHOD: &str = "world.mutate_resources";
/// The method path for a `world.list_resources` request.
pub const BRP_LIST_RESOURCES_METHOD: &str = "world.list_resources";
/// The method path for a `world.trigger_event` request.
pub const BRP_TRIGGER_EVENT_METHOD: &str = "world.trigger_event";
/// The method path for a `registry.schema` request.
pub const BRP_REGISTRY_SCHEMA_METHOD: &str = "registry.schema";
/// The method path for a `rpc.discover` request.
pub const RPC_DISCOVER_METHOD: &str = "rpc.discover";
/// `world.get_components`: Retrieves one or more components from the entity with the given
/// ID.
///
/// The server responds with a [`BrpGetComponentsResponse`].
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpGetComponentsParams {
/// The ID of the entity from which components are to be requested.
pub entity: Entity,
/// The [full paths] of the component types that are to be requested
/// from the entity.
///
/// Note that these strings must consist of the *full* type paths: e.g.
/// `bevy_transform::components::transform::Transform`, not just
/// `Transform`.
///
/// [full paths]: bevy_reflect::TypePath::type_path
pub components: Vec<String>,
/// An optional flag to fail when encountering an invalid component rather
/// than skipping it. Defaults to false.
#[serde(default)]
pub strict: bool,
}
/// `world.get_resources`: Retrieves the value of a given resource.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpGetResourcesParams {
/// The [full path] of the resource type being requested.
///
/// [full path]: bevy_reflect::TypePath::type_path
pub resource: String,
}
/// `world.query`: Performs a query over components in the ECS, returning entities
/// and component values that match.
///
/// The server responds with a [`BrpQueryResponse`].
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpQueryParams {
/// The components to select.
pub data: BrpQuery,
/// An optional filter that specifies which entities to include or
/// exclude from the results.
#[serde(default)]
pub filter: BrpQueryFilter,
/// An optional flag to fail when encountering an invalid component rather
/// than skipping it. Defaults to false.
#[serde(default)]
pub strict: bool,
}
/// `world.spawn_entity`: Creates a new entity with the given components and responds
/// with its ID.
///
/// The server responds with a [`BrpSpawnEntityResponse`].
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpSpawnEntityParams {
/// A map from each component's full path to its serialized value.
///
/// These components will be added to the entity.
///
/// Note that the keys of the map must be the [full type paths]: e.g.
/// `bevy_transform::components::transform::Transform`, not just
/// `Transform`.
///
/// [full type paths]: bevy_reflect::TypePath::type_path
pub components: HashMap<String, Value>,
}
/// `world.despawn_entity`: Given an ID, despawns the entity with that ID.
///
/// The server responds with an okay.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpDespawnEntityParams {
/// The ID of the entity to despawn.
pub entity: Entity,
}
/// `world.remove_components`: Deletes one or more components from an entity.
///
/// The server responds with a null.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpRemoveComponentsParams {
/// The ID of the entity from which components are to be removed.
pub entity: Entity,
/// The full paths of the component types that are to be removed from
/// the entity.
///
/// Note that these strings must consist of the [full type paths]: e.g.
/// `bevy_transform::components::transform::Transform`, not just
/// `Transform`.
///
/// [full type paths]: bevy_reflect::TypePath::type_path
pub components: Vec<String>,
}
/// `world.remove_resources`: Removes the given resource from the world.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpRemoveResourcesParams {
/// The [full path] of the resource type to remove.
///
/// [full path]: bevy_reflect::TypePath::type_path
pub resource: String,
}
/// `world.insert_components`: Adds one or more components to an entity.
///
/// The server responds with a null.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpInsertComponentsParams {
/// The ID of the entity that components are to be added to.
pub entity: Entity,
/// A map from each component's full path to its serialized value.
///
/// These components will be added to the entity.
///
/// Note that the keys of the map must be the [full type paths]: e.g.
/// `bevy_transform::components::transform::Transform`, not just
/// `Transform`.
///
/// [full type paths]: bevy_reflect::TypePath::type_path
pub components: HashMap<String, Value>,
}
/// `world.insert_resources`: Inserts a resource into the world with a given
/// value.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpInsertResourcesParams {
/// The [full path] of the resource type to insert.
///
/// [full path]: bevy_reflect::TypePath::type_path
pub resource: String,
/// The serialized value of the resource to be inserted.
pub value: Value,
}
/// `world.reparent_entities`: Assign a new parent to one or more entities.
///
/// The server responds with a null.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpReparentEntitiesParams {
/// The IDs of the entities that are to become the new children of the
/// `parent`.
pub entities: Vec<Entity>,
/// The IDs of the entity that will become the new parent of the
/// `entities`.
///
/// If this is `None`, then the entities are removed from all parents.
#[serde(default)]
pub parent: Option<Entity>,
}
/// `world.list_components`: Returns a list of all type names of registered components in the
/// system (no params provided), or those on an entity (params provided).
///
/// The server responds with a [`BrpListComponentsResponse`]
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpListComponentsParams {
/// The entity to query.
pub entity: Entity,
}
/// `world.mutate_components`:
///
/// The server responds with a null.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpMutateComponentsParams {
/// The entity of the component to mutate.
pub entity: Entity,
/// The [full path] of the component to mutate.
///
/// [full path]: bevy_reflect::TypePath::type_path
pub component: String,
/// The [path] of the field within the component.
///
/// [path]: bevy_reflect::GetPath
pub path: String,
/// The value to insert at `path`.
pub value: Value,
}
/// `world.mutate_resources`:
///
/// The server responds with a null.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpMutateResourcesParams {
/// The [full path] of the resource to mutate.
///
/// [full path]: bevy_reflect::TypePath::type_path
pub resource: String,
/// The [path] of the field within the resource.
///
/// [path]: bevy_reflect::GetPath
pub path: String,
/// The value to insert at `path`.
pub value: Value,
}
/// `world.trigger_event`:
///
/// The server responds with a null.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
struct BrpTriggerEventParams {
/// The [full path] of the event to trigger.
///
/// [full path]: bevy_reflect::TypePath::type_path
pub event: String,
/// The serialized value of the event to be triggered, if any.
pub value: Option<Value>,
}
/// Describes the data that is to be fetched in a query.
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct BrpQuery {
/// The [full path] of the type name of each component that is to be
/// fetched.
///
/// [full path]: bevy_reflect::TypePath::type_path
#[serde(default)]
pub components: Vec<String>,
/// The [full path] of the type name of each component that is to be
/// optionally fetched.
///
/// [full path]: bevy_reflect::TypePath::type_path
#[serde(default)]
pub option: ComponentSelector,
/// The [full path] of the type name of each component that is to be checked
/// for presence.
///
/// [full path]: bevy_reflect::TypePath::type_path
#[serde(default)]
pub has: Vec<String>,
}
/// Additional constraints that can be placed on a query to include or exclude
/// certain entities.
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct BrpQueryFilter {
/// The [full path] of the type name of each component that must not be
/// present on the entity for it to be included in the results.
///
/// [full path]: bevy_reflect::TypePath::type_path
#[serde(default)]
pub without: Vec<String>,
/// The [full path] of the type name of each component that must be present
/// on the entity for it to be included in the results.
///
/// [full path]: bevy_reflect::TypePath::type_path
#[serde(default)]
pub with: Vec<String>,
}
/// Constraints that can be placed on a query to include or exclude
/// certain definitions.
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct BrpJsonSchemaQueryFilter {
/// The crate name of the type name of each component that must not be
/// present on the entity for it to be included in the results.
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub without_crates: Vec<String>,
/// The crate name of the type name of each component that must be present
/// on the entity for it to be included in the results.
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub with_crates: Vec<String>,
/// Constrain resource by type
#[serde(default)]
pub type_limit: JsonSchemaTypeLimit,
}
/// Additional [`BrpJsonSchemaQueryFilter`] constraints that can be placed on a query to include or exclude
/// certain definitions.
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct JsonSchemaTypeLimit {
/// Schema cannot have specified reflect types
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub without: Vec<String>,
/// Schema needs to have specified reflect types
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub with: Vec<String>,
}
/// A response from the world to the client that specifies a single entity.
///
/// This is sent in response to `world.spawn_entity`.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpSpawnEntityResponse {
/// The ID of the entity in question.
pub entity: Entity,
}
/// The response to a `world.get_components` request.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(untagged)]
pub enum BrpGetComponentsResponse {
/// The non-strict response that reports errors separately without failing the entire request.
Lenient {
/// A map of successful components with their values.
components: HashMap<String, Value>,
/// A map of unsuccessful components with their errors.
errors: HashMap<String, Value>,
},
/// The strict response that will fail if any components are not present or aren't
/// reflect-able.
Strict(HashMap<String, Value>),
}
/// The response to a `world.get_resources` request.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpGetResourcesResponse {
/// The value of the requested resource.
pub value: Value,
}
/// A single response from a `world.get_components+watch` request.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(untagged)]
pub enum BrpGetComponentsWatchingResponse {
/// The non-strict response that reports errors separately without failing the entire request.
Lenient {
/// A map of successful components with their values that were added or changes in the last
/// tick.
components: HashMap<String, Value>,
/// An array of components that were been removed in the last tick.
removed: Vec<String>,
/// A map of unsuccessful components with their errors.
errors: HashMap<String, Value>,
},
/// The strict response that will fail if any components are not present or aren't
/// reflect-able.
Strict {
/// A map of successful components with their values that were added or changes in the last
/// tick.
components: HashMap<String, Value>,
/// An array of components that were been removed in the last tick.
removed: Vec<String>,
},
}
/// The response to a `world.list_components` request.
pub type BrpListComponentsResponse = Vec<String>;
/// The response to a `world.list_resources` request.
pub type BrpListResourcesResponse = Vec<String>;
/// A single response from a `world.list_components+watch` request.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpListComponentsWatchingResponse {
added: Vec<String>,
removed: Vec<String>,
}
/// The response to a `world.query` request.
pub type BrpQueryResponse = Vec<BrpQueryRow>;
/// One query match result: a single entity paired with the requested components.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct BrpQueryRow {
/// The ID of the entity that matched.
pub entity: Entity,
/// The serialized values of the requested components.
pub components: HashMap<String, Value>,
/// The boolean-only containment query results.
#[serde(skip_serializing_if = "HashMap::is_empty", default)]
pub has: HashMap<String, Value>,
}
/// A helper function used to parse a `serde_json::Value`.
pub fn parse<T: for<'de> Deserialize<'de>>(value: Value) -> Result<T, BrpError> {
serde_json::from_value(value).map_err(|err| BrpError {
code: error_codes::INVALID_PARAMS,
message: err.to_string(),
data: None,
})
}
/// A helper function used to parse a `serde_json::Value` wrapped in an `Option`.
pub fn parse_some<T: for<'de> Deserialize<'de>>(value: Option<Value>) -> Result<T, BrpError> {
match value {
Some(value) => parse(value),
None => Err(BrpError {
code: error_codes::INVALID_PARAMS,
message: String::from("Params not provided"),
data: None,
}),
}
}
/// Handles a `world.get_components` request coming from a client.
pub fn process_remote_get_components_request(
In(params): In<Option<Value>>,
world: &World,
) -> BrpResult {
let BrpGetComponentsParams {
entity,
components,
strict,
} = parse_some(params)?;
let app_type_registry = world.resource::<AppTypeRegistry>();
let type_registry = app_type_registry.read();
let entity_ref = get_entity(world, entity)?;
let response =
reflect_components_to_response(components, strict, entity, entity_ref, &type_registry)?;
serde_json::to_value(response).map_err(BrpError::internal)
}
/// Handles a `world.get_resources` request coming from a client.
pub fn process_remote_get_resources_request(
In(params): In<Option<Value>>,
world: &World,
) -> BrpResult {
let BrpGetResourcesParams {
resource: resource_path,
} = parse_some(params)?;
let app_type_registry = world.resource::<AppTypeRegistry>();
let type_registry = app_type_registry.read();
let reflect_resource =
get_reflect_resource(&type_registry, &resource_path).map_err(BrpError::resource_error)?;
let Ok(reflected) = reflect_resource.reflect(world) else {
return Err(BrpError::resource_not_present(&resource_path));
};
// Use the `ReflectSerializer` to serialize the value of the resource;
// this produces a map with a single item.
let reflect_serializer = ReflectSerializer::new(reflected.as_partial_reflect(), &type_registry);
let Value::Object(serialized_object) =
serde_json::to_value(&reflect_serializer).map_err(BrpError::resource_error)?
else {
return Err(BrpError {
code: error_codes::RESOURCE_ERROR,
message: format!("Resource `{resource_path}` could not be serialized"),
data: None,
});
};
// Get the single value out of the map.
let value = serialized_object.into_values().next().ok_or_else(|| {
BrpError::internal(anyhow!("Unexpected format of serialized resource value"))
})?;
let response = BrpGetResourcesResponse { value };
serde_json::to_value(response).map_err(BrpError::internal)
}
/// Handles a `world.get_components+watch` request coming from a client.
pub fn process_remote_get_components_watching_request(
In(params): In<Option<Value>>,
world: &World,
mut removal_cursors: Local<HashMap<ComponentId, MessageCursor<RemovedComponentEntity>>>,
) -> BrpResult<Option<Value>> {
let BrpGetComponentsParams {
entity,
components,
strict,
} = parse_some(params)?;
let app_type_registry = world.resource::<AppTypeRegistry>();
let type_registry = app_type_registry.read();
let entity_ref = get_entity(world, entity)?;
let mut changed = Vec::new();
let mut removed = Vec::new();
let mut errors = <HashMap<_, _>>::default();
'component_loop: for component_path in components {
let Ok(type_registration) =
get_component_type_registration(&type_registry, &component_path)
else {
let err =
BrpError::component_error(format!("Unknown component type: `{component_path}`"));
if strict {
return Err(err);
}
errors.insert(
component_path,
serde_json::to_value(err).map_err(BrpError::internal)?,
);
continue;
};
let Some(component_id) = world.components().get_valid_id(type_registration.type_id())
else {
let err = BrpError::component_error(format!("Unknown component: `{component_path}`"));
if strict {
return Err(err);
}
errors.insert(
component_path,
serde_json::to_value(err).map_err(BrpError::internal)?,
);
continue;
};
if let Some(ticks) = entity_ref.get_change_ticks_by_id(component_id)
&& ticks.is_changed(world.last_change_tick(), world.read_change_tick())
{
changed.push(component_path);
continue;
};
let Some(events) = world.removed_components().get(component_id) else {
continue;
};
let cursor = removal_cursors
.entry(component_id)
.or_insert_with(|| events.get_cursor());
for event in cursor.read(events) {
if Entity::from(event.clone()) == entity {
removed.push(component_path);
continue 'component_loop;
}
}
}
if changed.is_empty() && removed.is_empty() {
return Ok(None);
}
let response =
reflect_components_to_response(changed, strict, entity, entity_ref, &type_registry)?;
let response = match response {
BrpGetComponentsResponse::Lenient {
components,
errors: mut errs,
} => BrpGetComponentsWatchingResponse::Lenient {
components,
removed,
errors: {
errs.extend(errors);
errs
},
},
BrpGetComponentsResponse::Strict(components) => BrpGetComponentsWatchingResponse::Strict {
components,
removed,
},
};
Ok(Some(
serde_json::to_value(response).map_err(BrpError::internal)?,
))
}
/// Reflect a list of components on an entity into a [`BrpGetComponentsResponse`].
fn reflect_components_to_response(
components: Vec<String>,
strict: bool,
entity: Entity,
entity_ref: EntityRef,
type_registry: &TypeRegistry,
) -> BrpResult<BrpGetComponentsResponse> {
let mut response = if strict {
BrpGetComponentsResponse::Strict(Default::default())
} else {
BrpGetComponentsResponse::Lenient {
components: Default::default(),
errors: Default::default(),
}
};
for component_path in components {
match reflect_component(&component_path, entity, entity_ref, type_registry) {
Ok(serialized_object) => match response {
BrpGetComponentsResponse::Strict(ref mut components)
| BrpGetComponentsResponse::Lenient {
ref mut components, ..
} => {
components.extend(serialized_object.into_iter());
}
},
Err(err) => match response {
BrpGetComponentsResponse::Strict(_) => return Err(err),
BrpGetComponentsResponse::Lenient { ref mut errors, .. } => {
let err_value = serde_json::to_value(err).map_err(BrpError::internal)?;
errors.insert(component_path, err_value);
}
},
}
}
Ok(response)
}
/// Reflect a single component on an entity with the given component path.
fn reflect_component(
component_path: &str,
entity: Entity,
entity_ref: EntityRef,
type_registry: &TypeRegistry,
) -> BrpResult<Map<String, Value>> {
let reflect_component =
get_reflect_component(type_registry, component_path).map_err(BrpError::component_error)?;
// Retrieve the reflected value for the given specified component on the given entity.
let Some(reflected) = reflect_component.reflect(entity_ref) else {
return Err(BrpError::component_not_present(component_path, entity));
};
// Each component value serializes to a map with a single entry.
let reflect_serializer = ReflectSerializer::new(reflected.as_partial_reflect(), type_registry);
let Value::Object(serialized_object) =
serde_json::to_value(&reflect_serializer).map_err(BrpError::component_error)?
else {
return Err(BrpError {
code: error_codes::COMPONENT_ERROR,
message: format!("Component `{component_path}` could not be serialized"),
data: None,
});
};
Ok(serialized_object)
}
/// A selector for components in a query.
///
/// This can either be a list of component paths or an "all" selector that
/// indicates that all components should be selected.
/// The "all" selector is useful when you want to retrieve all components
/// present on an entity without specifying each one individually.
/// The paths in the `Paths` variant must be the [full type paths]: e.g.
/// `bevy_transform::components::transform::Transform`, not just
/// `Transform`.
///
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ComponentSelector {
/// An "all" selector that indicates all components should be selected.
All,
/// A list of component paths to select as optional components.
#[serde(untagged)]
Paths(Vec<String>),
}
impl Default for ComponentSelector {
fn default() -> Self {
Self::Paths(Vec::default())
}
}
/// Handles a `world.query` request coming from a client.
pub fn process_remote_query_request(In(params): In<Option<Value>>, world: &mut World) -> BrpResult {
let BrpQueryParams {
data: BrpQuery {
components,
option,
has,
},
filter,
strict,
} = match params {
Some(params) => parse_some(Some(params))?,
None => BrpQueryParams {
data: BrpQuery {
components: Vec::new(),
option: ComponentSelector::default(),
has: Vec::new(),
},
filter: BrpQueryFilter::default(),
strict: false,
},
};
let app_type_registry = world.resource::<AppTypeRegistry>().clone();
let type_registry = app_type_registry.read();
// Required components: must be present
let (required, unregistered_in_required) =
get_component_ids(&type_registry, world, components.clone(), strict)
.map_err(BrpError::component_error)?;
// Optional components: Option<&T> or all reflectable if "all"
let (optional, _) = match &option {
ComponentSelector::Paths(paths) => {
get_component_ids(&type_registry, world, paths.clone(), strict)
.map_err(BrpError::component_error)?
}
ComponentSelector::All => (Vec::new(), Vec::new()),
};
// Has components: presence check
let (has_ids, unregistered_in_has) =
get_component_ids(&type_registry, world, has, strict).map_err(BrpError::component_error)?;
// Filters
let (without, _) = get_component_ids(&type_registry, world, filter.without.clone(), strict)
.map_err(BrpError::component_error)?;
let (with, unregistered_in_with) =
get_component_ids(&type_registry, world, filter.with.clone(), strict)
.map_err(BrpError::component_error)?;
// When "strict" is false:
// - Unregistered components in "option" and "without" are ignored.
// - Unregistered components in "has" are considered absent from the entity.
// - Unregistered components in "components" and "with" result in an empty
// response since they specify hard requirements.
// If strict, fail if any required or with components are unregistered
if !unregistered_in_required.is_empty() || !unregistered_in_with.is_empty() {
return serde_json::to_value(BrpQueryResponse::default()).map_err(BrpError::internal);
}
let mut query = QueryBuilder::<FilteredEntityRef>::new(world);
for (_, component) in &required {
query.ref_id(*component);
}
for (_, option) in &optional {
query.optional(|query| {
query.ref_id(*option);
});
}
for (_, has) in &has_ids {
query.optional(|query| {
query.ref_id(*has);
});
}
for (_, without) in without {
query.without_id(without);
}
for (_, with) in with {
query.with_id(with);
}
// Prepare has reflect info
let has_paths_and_reflect_components: Vec<(&str, &ReflectComponent)> = has_ids
.iter()
.map(|(type_id, _)| reflect_component_from_id(*type_id, &type_registry))
.collect::<AnyhowResult<Vec<(&str, &ReflectComponent)>>>()
.map_err(BrpError::component_error)?;
let mut response = BrpQueryResponse::default();
let mut query = query.build();
for row in query.iter(world) {
let entity_id = row.id();
let entity_ref = world.get_entity(entity_id).expect("Entity should exist");
// Required components
let mut components_map = serialize_components(
entity_ref,
&type_registry,
required
.iter()
.map(|(type_id, component_id)| (*type_id, Some(*component_id))),
);
// Optional components
match &option {
ComponentSelector::All => {
// Add all reflectable components present on the entity (as Option<&T>)
let all_optionals =
entity_ref
.archetype()
.components()
.iter()
.filter_map(|&component_id| {
let info = world.components().get_info(component_id)?;
let type_id = info.type_id()?;
// Skip required components (already included)
if required.iter().any(|(_, cid)| cid == &component_id) {
return None;
}
Some((type_id, Some(component_id)))
});
components_map.extend(serialize_components(
entity_ref,
&type_registry,
all_optionals,
));
}
ComponentSelector::Paths(_) => {
// Add only the requested optional components (as Option<&T>)
let optionals = optional.iter().filter(|(_, component_id)| {
// Skip required components (already included)
!required.iter().any(|(_, cid)| cid == component_id)
});
components_map.extend(serialize_components(
entity_ref,
&type_registry,
optionals
.clone()
.map(|(type_id, component_id)| (*type_id, Some(*component_id))),
));
}
}
// The map of boolean-valued component presences:
let has_map = build_has_map(
row,
has_paths_and_reflect_components.iter().copied(),
&unregistered_in_has,
);
let query_row = BrpQueryRow {
entity: row.id(),
components: components_map,
has: has_map,
};
response.push(query_row);
}
serde_json::to_value(response).map_err(BrpError::internal)
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_remote/src/lib.rs | crates/bevy_remote/src/lib.rs | //! An implementation of the Bevy Remote Protocol, to allow for remote control of a Bevy app.
//!
//! Adding the [`RemotePlugin`] to your [`App`] will setup everything needed without
//! starting any transports. To start accepting remote connections you will need to
//! add a second plugin like the [`RemoteHttpPlugin`](http::RemoteHttpPlugin) to enable communication
//! over HTTP. These *remote clients* can inspect and alter the state of the
//! entity-component system.
//!
//! The Bevy Remote Protocol is based on the JSON-RPC 2.0 protocol.
//!
//! ## Request objects
//!
//! A typical client request might look like this:
//!
//! ```json
//! {
//! "method": "world.get_components",
//! "id": 0,
//! "params": {
//! "entity": 4294967298,
//! "components": [
//! "bevy_transform::components::transform::Transform"
//! ]
//! }
//! }
//! ```
//!
//! The `id` and `method` fields are required. The `params` field may be omitted
//! for certain methods:
//!
//! * `id` is arbitrary JSON data. The server completely ignores its contents,
//! and the client may use it for any purpose. It will be copied via
//! serialization and deserialization (so object property order, etc. can't be
//! relied upon to be identical) and sent back to the client as part of the
//! response.
//!
//! * `method` is a string that specifies one of the possible [`BrpRequest`]
//! variants: `world.query`, `world.get_components`, `world.insert_components`, etc. It's case-sensitive.
//!
//! * `params` is parameter data specific to the request.
//!
//! For more information, see the documentation for [`BrpRequest`].
//! [`BrpRequest`] is serialized to JSON via `serde`, so [the `serde`
//! documentation] may be useful to clarify the correspondence between the Rust
//! structure and the JSON format.
//!
//! ## Response objects
//!
//! A response from the server to the client might look like this:
//!
//! ```json
//! {
//! "jsonrpc": "2.0",
//! "id": 0,
//! "result": {
//! "bevy_transform::components::transform::Transform": {
//! "rotation": { "x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0 },
//! "scale": { "x": 1.0, "y": 1.0, "z": 1.0 },
//! "translation": { "x": 0.0, "y": 0.5, "z": 0.0 }
//! }
//! }
//! }
//! ```
//!
//! The `id` field will always be present. The `result` field will be present if the
//! request was successful. Otherwise, an `error` field will replace it.
//!
//! * `id` is the arbitrary JSON data that was sent as part of the request. It
//! will be identical to the `id` data sent during the request, modulo
//! serialization and deserialization. If there's an error reading the `id` field,
//! it will be `null`.
//!
//! * `result` will be present if the request succeeded and will contain the response
//! specific to the request.
//!
//! * `error` will be present if the request failed and will contain an error object
//! with more information about the cause of failure.
//!
//! ## Error objects
//!
//! An error object might look like this:
//!
//! ```json
//! {
//! "code": -32602,
//! "message": "Missing \"entity\" field"
//! }
//! ```
//!
//! The `code` and `message` fields will always be present. There may also be a `data` field.
//!
//! * `code` is an integer representing the kind of an error that happened. Error codes documented
//! in the [`error_codes`] module.
//!
//! * `message` is a short, one-sentence human-readable description of the error.
//!
//! * `data` is an optional field of arbitrary type containing additional information about the error.
//!
//! ## Built-in methods
//!
//! The Bevy Remote Protocol includes a number of built-in methods for accessing and modifying data
//! in the ECS.
//!
//! ### `world.get_components`
//!
//! Retrieve the values of one or more components from an entity.
//!
//! `params`:
//! - `entity`: The ID of the entity whose components will be fetched.
//! - `components`: An array of [fully-qualified type names] of components to fetch.
//! - `strict` (optional): A flag to enable strict mode which will fail if any one of the
//! components is not present or can not be reflected. Defaults to false.
//!
//! If `strict` is false:
//!
//! `result`:
//! - `components`: A map associating each type name to its value on the requested entity.
//! - `errors`: A map associating each type name with an error if it was not on the entity
//! or could not be reflected.
//!
//! If `strict` is true:
//!
//! `result`: A map associating each type name to its value on the requested entity.
//!
//! ### `world.query`
//!
//! Perform a query over components in the ECS, returning all matching entities and their associated
//! component values.
//!
//! All of the arrays that comprise this request are optional, and when they are not provided, they
//! will be treated as if they were empty.
//!
//! `params`:
//! - `data`:
//! - `components` (optional): An array of [fully-qualified type names] of components to fetch,
//! see _below_ example for a query to list all the type names in **your** project.
//! - `option` (optional): An array of fully-qualified type names of components to fetch optionally.
//! to fetch all reflectable components, you can pass in the string `"all"`.
//! - `has` (optional): An array of fully-qualified type names of components whose presence will be
//! reported as boolean values.
//! - `filter` (optional):
//! - `with` (optional): An array of fully-qualified type names of components that must be present
//! on entities in order for them to be included in results.
//! - `without` (optional): An array of fully-qualified type names of components that must *not* be
//! present on entities in order for them to be included in results.
//! - `strict` (optional): A flag to enable strict mode which will fail if any one of the components
//! is not present or can not be reflected. Defaults to false.
//!
//! `result`: An array, each of which is an object containing:
//! - `entity`: The ID of a query-matching entity.
//! - `components`: A map associating each type name from `components`/`option` to its value on the matching
//! entity if the component is present.
//! - `has`: A map associating each type name from `has` to a boolean value indicating whether or not the
//! entity has that component. If `has` was empty or omitted, this key will be omitted in the response.
//!
//! #### Example
//! To use the query API and retrieve Transform data for all entities that have a Transform
//! use this query:
//!
//! ```json
//! {
//! "jsonrpc": "2.0",
//! "method": "bevy/query",
//! "id": 0,
//! "params": {
//! "data": {
//! "components": ["bevy_transform::components::transform::Transform"]
//! "option": [],
//! "has": []
//! },
//! "filter": {
//! "with": [],
//! "without": []
//! },
//! "strict": false
//! }
//! }
//! ```
//!
//!
//! To query all entities and all of their Reflectable components (and retrieve their values), you can pass in "all" for the option field:
//! ```json
//! {
//! "jsonrpc": "2.0",
//! "method": "bevy/query",
//! "id": 0,
//! "params": {
//! "data": {
//! "components": []
//! "option": "all",
//! "has": []
//! },
//! "filter": {
//! "with": [],
//! "without": []
//! },
//! "strict": false
//! }
//! }
//! ```
//!
//! This should return you something like the below (in a larger list):
//! ```json
//! {
//! "components": {
//! "bevy_camera::Camera3d": {
//! "depth_load_op": {
//! "Clear": 0.0
//! },
//! "depth_texture_usages": 16,
//! "screen_space_specular_transmission_quality": "Medium",
//! "screen_space_specular_transmission_steps": 1
//! },
//! "bevy_core_pipeline::tonemapping::DebandDither": "Enabled",
//! "bevy_core_pipeline::tonemapping::Tonemapping": "TonyMcMapface",
//! "bevy_light::cluster::ClusterConfig": {
//! "FixedZ": {
//! "dynamic_resizing": true,
//! "total": 4096,
//! "z_config": {
//! "far_z_mode": "MaxClusterableObjectRange",
//! "first_slice_depth": 5.0
//! },
//! "z_slices": 24
//! }
//! },
//! "bevy_camera::Camera": {
//! "clear_color": "Default",
//! "is_active": true,
//! "msaa_writeback": true,
//! "order": 0,
//! "sub_camera_view": null,
//! "target": {
//! "Window": "Primary"
//! },
//! "viewport": null
//! },
//! "bevy_camera::Projection": {
//! "Perspective": {
//! "aspect_ratio": 1.7777777910232544,
//! "far": 1000.0,
//! "fov": 0.7853981852531433,
//! "near": 0.10000000149011612
//! }
//! },
//! "bevy_camera::primitives::Frustum": {},
//! "bevy_render::sync_world::RenderEntity": 4294967291,
//! "bevy_render::sync_world::SyncToRenderWorld": {},
//! "bevy_render::view::Msaa": "Sample4",
//! "bevy_camera::visibility::InheritedVisibility": true,
//! "bevy_camera::visibility::ViewVisibility": false,
//! "bevy_camera::visibility::Visibility": "Inherited",
//! "bevy_camera::visibility::VisibleEntities": {},
//! "bevy_transform::components::global_transform::GlobalTransform": [
//! 0.9635179042816162,
//! -3.725290298461914e-9,
//! 0.26764383912086487,
//! 0.11616238951683044,
//! 0.9009039402008056,
//! -0.4181846082210541,
//! -0.24112138152122495,
//! 0.4340185225009918,
//! 0.8680371046066284,
//! -2.5,
//! 4.5,
//! 9.0
//! ],
//! "bevy_transform::components::transform::Transform": {
//! "rotation": [
//! -0.22055435180664065,
//! -0.13167093694210052,
//! -0.03006339818239212,
//! 0.9659786224365234
//! ],
//! "scale": [
//! 1.0,
//! 1.0,
//! 1.0
//! ],
//! "translation": [
//! -2.5,
//! 4.5,
//! 9.0
//! ]
//! },
//! "bevy_transform::components::transform::TransformTreeChanged": null
//! },
//! "entity": 4294967261
//!},
//! ```
//!
//! ### `world.spawn_entity`
//!
//! Create a new entity with the provided components and return the resulting entity ID.
//!
//! `params`:
//! - `components`: A map associating each component's [fully-qualified type name] with its value.
//!
//! `result`:
//! - `entity`: The ID of the newly spawned entity.
//!
//! ### `world.despawn_entity`
//!
//! Despawn the entity with the given ID.
//!
//! `params`:
//! - `entity`: The ID of the entity to be despawned.
//!
//! `result`: null.
//!
//! ### `world.remove_components`
//!
//! Delete one or more components from an entity.
//!
//! `params`:
//! - `entity`: The ID of the entity whose components should be removed.
//! - `components`: An array of [fully-qualified type names] of components to be removed.
//!
//! `result`: null.
//!
//! ### `world.insert_components`
//!
//! Insert one or more components into an entity.
//!
//! `params`:
//! - `entity`: The ID of the entity to insert components into.
//! - `components`: A map associating each component's fully-qualified type name with its value.
//!
//! `result`: null.
//!
//! ### `world.mutate_components`
//!
//! Mutate a field in a component.
//!
//! `params`:
//! - `entity`: The ID of the entity with the component to mutate.
//! - `component`: The component's [fully-qualified type name].
//! - `path`: The path of the field within the component. See
//! [`GetPath`](bevy_reflect::GetPath#syntax) for more information on formatting this string.
//! - `value`: The value to insert at `path`.
//!
//! `result`: null.
//!
//! ### `world.reparent_entities`
//!
//! Assign a new parent to one or more entities.
//!
//! `params`:
//! - `entities`: An array of entity IDs of entities that will be made children of the `parent`.
//! - `parent` (optional): The entity ID of the parent to which the child entities will be assigned.
//! If excluded, the given entities will be removed from their parents.
//!
//! `result`: null.
//!
//! ### `world.list_components`
//!
//! List all registered components or all components present on an entity.
//!
//! When `params` is not provided, this lists all registered components. If `params` is provided,
//! this lists only those components present on the provided entity.
//!
//! `params` (optional):
//! - `entity`: The ID of the entity whose components will be listed.
//!
//! `result`: An array of fully-qualified type names of components.
//!
//! ### `world.get_components+watch`
//!
//! Watch the values of one or more components from an entity.
//!
//! `params`:
//! - `entity`: The ID of the entity whose components will be fetched.
//! - `components`: An array of [fully-qualified type names] of components to fetch.
//! - `strict` (optional): A flag to enable strict mode which will fail if any one of the
//! components is not present or can not be reflected. Defaults to false.
//!
//! If `strict` is false:
//!
//! `result`:
//! - `components`: A map of components added or changed in the last tick associating each type
//! name to its value on the requested entity.
//! - `removed`: An array of fully-qualified type names of components removed from the entity
//! in the last tick.
//! - `errors`: A map associating each type name with an error if it was not on the entity
//! or could not be reflected.
//!
//! If `strict` is true:
//!
//! `result`:
//! - `components`: A map of components added or changed in the last tick associating each type
//! name to its value on the requested entity.
//! - `removed`: An array of fully-qualified type names of components removed from the entity
//! in the last tick.
//!
//! ### `world.list_components+watch`
//!
//! Watch all components present on an entity.
//!
//! When `params` is not provided, this lists all registered components. If `params` is provided,
//! this lists only those components present on the provided entity.
//!
//! `params`:
//! - `entity`: The ID of the entity whose components will be listed.
//!
//! `result`:
//! - `added`: An array of fully-qualified type names of components added to the entity in the
//! last tick.
//! - `removed`: An array of fully-qualified type names of components removed from the entity
//! in the last tick.
//!
//! ### `world.get_resources`
//!
//! Extract the value of a given resource from the world.
//!
//! `params`:
//! - `resource`: The [fully-qualified type name] of the resource to get.
//!
//! `result`:
//! - `value`: The value of the resource in the world.
//!
//! ### `world.insert_resources`
//!
//! Insert the given resource into the world with the given value.
//!
//! `params`:
//! - `resource`: The [fully-qualified type name] of the resource to insert.
//! - `value`: The value of the resource to be inserted.
//!
//! `result`: null.
//!
//! ### `world.remove_resources`
//!
//! Remove the given resource from the world.
//!
//! `params`
//! - `resource`: The [fully-qualified type name] of the resource to remove.
//!
//! `result`: null.
//!
//! ### `world.mutate_resources`
//!
//! Mutate a field in a resource.
//!
//! `params`:
//! - `resource`: The [fully-qualified type name] of the resource to mutate.
//! - `path`: The path of the field within the resource. See
//! [`GetPath`](bevy_reflect::GetPath#syntax) for more information on formatting this string.
//! - `value`: The value to be inserted at `path`.
//!
//! `result`: null.
//!
//! ### `world.list_resources`
//!
//! List all reflectable registered resource types. This method has no parameters.
//!
//! `result`: An array of [fully-qualified type names] of registered resource types.
//!
//! ### `world.trigger_event`
//!
//! Triggers an event.
//!
//! `params`:
//! - `event`: The [fully-qualified type name] of the event to trigger.
//! - `value`: The value of the event to trigger.
//!
//! `result`: null.
//!
//! ### `registry.schema`
//!
//! Retrieve schema information about registered types in the Bevy app's type registry.
//!
//! `params` (optional):
//! - `with_crates`: An array of crate names to include in the results. When empty or omitted, types from all crates will be included.
//! - `without_crates`: An array of crate names to exclude from the results. When empty or omitted, no crates will be excluded.
//! - `type_limit`: Additional type constraints:
//! - `with`: An array of [fully-qualified type names] that must be present for a type to be included
//! - `without`: An array of [fully-qualified type names] that must not be present for a type to be excluded
//!
//! `result`: A map associating each type's [fully-qualified type name] to a [`JsonSchemaBevyType`](crate::schemas::json_schema::JsonSchemaBevyType).
//! This contains schema information about that type, including field definitions, type information, reflect type information, and other metadata
//! helpful for understanding the structure of the type.
//!
//! ### `rpc.discover`
//!
//! Discover available remote methods and server information. This follows the [`OpenRPC` specification for service discovery](https://spec.open-rpc.org/#service-discovery-method).
//!
//! This method takes no parameters.
//!
//! `result`: An `OpenRPC` document containing:
//! - Information about all available remote methods
//! - Server connection information (when using HTTP transport)
//! - `OpenRPC` specification version
//!
//! ## Custom methods
//!
//! In addition to the provided methods, the Bevy Remote Protocol can be extended to include custom
//! methods. This is primarily done during the initialization of [`RemotePlugin`], although the
//! methods may also be extended at runtime using the [`RemoteMethods`] resource.
//!
//! ### Example
//! ```ignore
//! fn main() {
//! App::new()
//! .add_plugins(DefaultPlugins)
//! .add_plugins(
//! // `default` adds all of the built-in methods, while `with_method` extends them
//! RemotePlugin::default()
//! .with_method("super_user/cool_method", path::to::my::cool::handler)
//! // ... more methods can be added by chaining `with_method`
//! )
//! .add_systems(
//! // ... standard application setup
//! )
//! .run();
//! }
//! ```
//!
//! The handler is expected to be a system-convertible function which takes optional JSON parameters
//! as input and returns a [`BrpResult`]. This means that it should have a type signature which looks
//! something like this:
//! ```
//! # use serde_json::Value;
//! # use bevy_ecs::prelude::{In, World};
//! # use bevy_remote::BrpResult;
//! fn handler(In(params): In<Option<Value>>, world: &mut World) -> BrpResult {
//! todo!()
//! }
//! ```
//!
//! Arbitrary system parameters can be used in conjunction with the optional `Value` input. The
//! handler system will always run with exclusive `World` access.
//!
//! [the `serde` documentation]: https://serde.rs/
//! [fully-qualified type names]: bevy_reflect::TypePath::type_path
//! [fully-qualified type name]: bevy_reflect::TypePath::type_path
extern crate alloc;
use async_channel::{Receiver, Sender};
use bevy_app::{prelude::*, MainScheduleOrder};
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{
entity::Entity,
resource::Resource,
schedule::{IntoScheduleConfigs, ScheduleLabel, SystemSet},
system::{Commands, In, IntoSystem, ResMut, System, SystemId},
world::World,
};
use bevy_platform::collections::HashMap;
use bevy_utils::prelude::default;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::RwLock;
pub mod builtin_methods;
#[cfg(feature = "http")]
pub mod http;
pub mod schemas;
const CHANNEL_SIZE: usize = 16;
/// Add this plugin to your [`App`] to allow remote connections to inspect and modify entities.
///
/// This the main plugin for `bevy_remote`. See the [crate-level documentation] for details on
/// the available protocols and its default methods.
///
/// [crate-level documentation]: crate
pub struct RemotePlugin {
/// The verbs that the server will recognize and respond to.
methods: RwLock<Vec<(String, RemoteMethodHandler)>>,
}
impl RemotePlugin {
/// Create a [`RemotePlugin`] with the default address and port but without
/// any associated methods.
fn empty() -> Self {
Self {
methods: RwLock::new(vec![]),
}
}
/// Add a remote method to the plugin using the given `name` and `handler`.
#[must_use]
pub fn with_method<M>(
mut self,
name: impl Into<String>,
handler: impl IntoSystem<In<Option<Value>>, BrpResult, M>,
) -> Self {
self.methods.get_mut().unwrap().push((
name.into(),
RemoteMethodHandler::Instant(Box::new(IntoSystem::into_system(handler))),
));
self
}
/// Add a remote method with a watching handler to the plugin using the given `name`.
#[must_use]
pub fn with_watching_method<M>(
mut self,
name: impl Into<String>,
handler: impl IntoSystem<In<Option<Value>>, BrpResult<Option<Value>>, M>,
) -> Self {
self.methods.get_mut().unwrap().push((
name.into(),
RemoteMethodHandler::Watching(Box::new(IntoSystem::into_system(handler))),
));
self
}
}
impl Default for RemotePlugin {
fn default() -> Self {
Self::empty()
.with_method(
builtin_methods::BRP_GET_COMPONENTS_METHOD,
builtin_methods::process_remote_get_components_request,
)
.with_method(
builtin_methods::BRP_QUERY_METHOD,
builtin_methods::process_remote_query_request,
)
.with_method(
builtin_methods::BRP_SPAWN_ENTITY_METHOD,
builtin_methods::process_remote_spawn_entity_request,
)
.with_method(
builtin_methods::BRP_INSERT_COMPONENTS_METHOD,
builtin_methods::process_remote_insert_components_request,
)
.with_method(
builtin_methods::BRP_REMOVE_COMPONENTS_METHOD,
builtin_methods::process_remote_remove_components_request,
)
.with_method(
builtin_methods::BRP_DESPAWN_COMPONENTS_METHOD,
builtin_methods::process_remote_despawn_entity_request,
)
.with_method(
builtin_methods::BRP_REPARENT_ENTITIES_METHOD,
builtin_methods::process_remote_reparent_entities_request,
)
.with_method(
builtin_methods::BRP_LIST_COMPONENTS_METHOD,
builtin_methods::process_remote_list_components_request,
)
.with_method(
builtin_methods::BRP_MUTATE_COMPONENTS_METHOD,
builtin_methods::process_remote_mutate_components_request,
)
.with_method(
builtin_methods::RPC_DISCOVER_METHOD,
builtin_methods::process_remote_list_methods_request,
)
.with_watching_method(
builtin_methods::BRP_GET_COMPONENTS_AND_WATCH_METHOD,
builtin_methods::process_remote_get_components_watching_request,
)
.with_watching_method(
builtin_methods::BRP_LIST_COMPONENTS_AND_WATCH_METHOD,
builtin_methods::process_remote_list_components_watching_request,
)
.with_method(
builtin_methods::BRP_GET_RESOURCE_METHOD,
builtin_methods::process_remote_get_resources_request,
)
.with_method(
builtin_methods::BRP_INSERT_RESOURCE_METHOD,
builtin_methods::process_remote_insert_resources_request,
)
.with_method(
builtin_methods::BRP_REMOVE_RESOURCE_METHOD,
builtin_methods::process_remote_remove_resources_request,
)
.with_method(
builtin_methods::BRP_MUTATE_RESOURCE_METHOD,
builtin_methods::process_remote_mutate_resources_request,
)
.with_method(
builtin_methods::BRP_LIST_RESOURCES_METHOD,
builtin_methods::process_remote_list_resources_request,
)
.with_method(
builtin_methods::BRP_TRIGGER_EVENT_METHOD,
builtin_methods::process_remote_trigger_event_request,
)
.with_method(
builtin_methods::BRP_REGISTRY_SCHEMA_METHOD,
builtin_methods::export_registry_types,
)
}
}
impl Plugin for RemotePlugin {
fn build(&self, app: &mut App) {
let mut remote_methods = RemoteMethods::new();
let plugin_methods = &mut *self.methods.write().unwrap();
for (name, handler) in plugin_methods.drain(..) {
remote_methods.insert(
name,
match handler {
RemoteMethodHandler::Instant(system) => RemoteMethodSystemId::Instant(
app.main_mut().world_mut().register_boxed_system(system),
),
RemoteMethodHandler::Watching(system) => RemoteMethodSystemId::Watching(
app.main_mut().world_mut().register_boxed_system(system),
),
},
);
}
app.init_schedule(RemoteLast)
.world_mut()
.resource_mut::<MainScheduleOrder>()
.insert_after(Last, RemoteLast);
app.insert_resource(remote_methods)
.init_resource::<schemas::SchemaTypesMetadata>()
.init_resource::<RemoteWatchingRequests>()
.add_systems(PreStartup, setup_mailbox_channel)
.configure_sets(
RemoteLast,
(RemoteSystems::ProcessRequests, RemoteSystems::Cleanup).chain(),
)
.add_systems(
RemoteLast,
(
(process_remote_requests, process_ongoing_watching_requests)
.chain()
.in_set(RemoteSystems::ProcessRequests),
remove_closed_watching_requests.in_set(RemoteSystems::Cleanup),
),
);
}
}
/// Schedule that contains all systems to process Bevy Remote Protocol requests
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct RemoteLast;
/// The systems sets of the [`RemoteLast`] schedule.
///
/// These can be useful for ordering.
#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
pub enum RemoteSystems {
/// Processing of remote requests.
ProcessRequests,
/// Cleanup (remove closed watchers etc)
Cleanup,
}
/// A type to hold the allowed types of systems to be used as method handlers.
#[derive(Debug)]
pub enum RemoteMethodHandler {
/// A handler that only runs once and returns one response.
Instant(Box<dyn System<In = In<Option<Value>>, Out = BrpResult>>),
/// A handler that watches for changes and response when a change is detected.
Watching(Box<dyn System<In = In<Option<Value>>, Out = BrpResult<Option<Value>>>>),
}
/// The [`SystemId`] of a function that implements a remote instant method (`world.get_components`, `world.query`, etc.)
///
/// The first parameter is the JSON value of the `params`. Typically, an
/// implementation will deserialize these as the first thing they do.
///
/// The returned JSON value will be returned as the response. Bevy will
/// automatically populate the `id` field before sending.
pub type RemoteInstantMethodSystemId = SystemId<In<Option<Value>>, BrpResult>;
/// The [`SystemId`] of a function that implements a remote watching method (`world.get_components+watch`, `world.list_components+watch`, etc.)
///
/// The first parameter is the JSON value of the `params`. Typically, an
/// implementation will deserialize these as the first thing they do.
///
/// The optional returned JSON value will be sent as a response. If no
/// changes were detected this should be [`None`]. Re-running of this
/// handler is done in the [`RemotePlugin`].
pub type RemoteWatchingMethodSystemId = SystemId<In<Option<Value>>, BrpResult<Option<Value>>>;
/// The [`SystemId`] of a function that can be used as a remote method.
#[derive(Debug, Clone, Copy)]
pub enum RemoteMethodSystemId {
/// A handler that only runs once and returns one response.
Instant(RemoteInstantMethodSystemId),
/// A handler that watches for changes and response when a change is detected.
Watching(RemoteWatchingMethodSystemId),
}
/// Holds all implementations of methods known to the server.
///
/// Custom methods can be added to this list using [`RemoteMethods::insert`].
#[derive(Debug, Resource, Default)]
pub struct RemoteMethods(HashMap<String, RemoteMethodSystemId>);
impl RemoteMethods {
/// Creates a new [`RemoteMethods`] resource with no methods registered in it.
pub fn new() -> Self {
default()
}
/// Adds a new method, replacing any existing method with that name.
///
/// If there was an existing method with that name, returns its handler.
pub fn insert(
&mut self,
method_name: impl Into<String>,
handler: RemoteMethodSystemId,
) -> Option<RemoteMethodSystemId> {
self.0.insert(method_name.into(), handler)
}
/// Get a [`RemoteMethodSystemId`] with its method name.
pub fn get(&self, method: &str) -> Option<&RemoteMethodSystemId> {
self.0.get(method)
}
/// Get a [`Vec<String>`] with method names.
pub fn methods(&self) -> Vec<String> {
self.0.keys().cloned().collect()
}
}
/// Holds the [`BrpMessage`]'s of all ongoing watching requests along with their handlers.
#[derive(Debug, Resource, Default)]
pub struct RemoteWatchingRequests(Vec<(BrpMessage, RemoteWatchingMethodSystemId)>);
/// A single request from a Bevy Remote Protocol client to the server,
/// serialized in JSON.
///
/// The JSON payload is expected to look like this:
///
/// ```json
/// {
/// "jsonrpc": "2.0",
/// "method": "world.get_components",
/// "id": 0,
/// "params": {
/// "entity": 4294967298,
/// "components": [
/// "bevy_transform::components::transform::Transform"
/// ]
/// }
/// }
/// ```
/// Or, to list all the fully-qualified type paths in **your** project, pass Null to the
/// `params`.
/// ```json
/// {
/// "jsonrpc": "2.0",
/// "method": "world.list_components",
/// "id": 0,
/// "params": null
///}
///```
///
/// In Rust:
/// ```ignore
/// let req = BrpRequest {
/// jsonrpc: "2.0".to_string(),
/// method: BRP_LIST_METHOD.to_string(), // All the methods have consts
/// id: Some(ureq::json!(0)),
/// params: None,
/// };
/// ```
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BrpRequest {
/// This field is mandatory and must be set to `"2.0"` for the request to be accepted.
pub jsonrpc: String,
/// The action to be performed.
pub method: String,
/// Arbitrary data that will be returned verbatim to the client as part of
/// the response.
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<Value>,
/// The parameters, specific to each method.
///
/// These are passed as the first argument to the method handler.
/// Sometimes params can be omitted.
#[serde(skip_serializing_if = "Option::is_none")]
pub params: Option<Value>,
}
/// A response according to BRP.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BrpResponse {
/// This field is mandatory and must be set to `"2.0"`.
pub jsonrpc: &'static str,
/// The id of the original request.
pub id: Option<Value>,
/// The actual response payload.
#[serde(flatten)]
pub payload: BrpPayload,
}
impl BrpResponse {
/// Generates a [`BrpResponse`] from an id and a `Result`.
#[must_use]
pub fn new(id: Option<Value>, result: BrpResult) -> Self {
Self {
jsonrpc: "2.0",
id,
payload: BrpPayload::from(result),
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_remote/src/http.rs | crates/bevy_remote/src/http.rs | //! The BRP transport using JSON-RPC over HTTP.
//!
//! Adding the [`RemoteHttpPlugin`] to your [`App`] causes Bevy to accept
//! connections over HTTP (by default, on port 15702) while your app is running.
//!
//! Clients are expected to `POST` JSON requests to the root URL; see the `client`
//! example for a trivial example of use.
#![cfg(not(target_family = "wasm"))]
use crate::{
error_codes, BrpBatch, BrpError, BrpMessage, BrpRequest, BrpResponse, BrpResult, BrpSender,
};
use anyhow::Result as AnyhowResult;
use async_channel::{Receiver, Sender};
use async_io::Async;
use bevy_app::{App, Plugin, Startup};
use bevy_ecs::resource::Resource;
use bevy_ecs::system::Res;
use bevy_tasks::{futures_lite::StreamExt, IoTaskPool};
use core::{
convert::Infallible,
net::{IpAddr, Ipv4Addr},
pin::Pin,
task::{Context, Poll},
};
use http_body_util::{BodyExt as _, Full};
use hyper::{
body::{Body, Bytes, Frame, Incoming},
header::{HeaderName, HeaderValue},
server::conn::http1,
service, Request, Response,
};
use serde_json::Value;
use smol_hyper::rt::{FuturesIo, SmolTimer};
use std::{
collections::HashMap,
net::{TcpListener, TcpStream},
};
/// The default port that Bevy will listen on.
///
/// This value was chosen randomly.
pub const DEFAULT_PORT: u16 = 15702;
/// The default host address that Bevy will use for its server.
pub const DEFAULT_ADDR: IpAddr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
/// A struct that holds a collection of HTTP headers.
///
/// This struct is used to store a set of HTTP headers as key-value pairs, where the keys are
/// of type [`HeaderName`] and the values are of type [`HeaderValue`].
///
#[derive(Debug, Resource, Clone)]
pub struct Headers {
headers: HashMap<HeaderName, HeaderValue>,
}
impl Headers {
/// Create a new instance of `Headers`.
pub fn new() -> Self {
Self {
headers: HashMap::default(),
}
}
/// Insert a key value pair to the `Headers` instance.
pub fn insert(
mut self,
name: impl TryInto<HeaderName>,
value: impl TryInto<HeaderValue>,
) -> Self {
let Ok(header_name) = name.try_into() else {
panic!("Invalid header name")
};
let Ok(header_value) = value.try_into() else {
panic!("Invalid header value")
};
self.headers.insert(header_name, header_value);
self
}
}
impl Default for Headers {
fn default() -> Self {
Self::new()
}
}
/// Add this plugin to your [`App`] to allow remote connections over HTTP to inspect and modify entities.
/// It requires the [`RemotePlugin`](super::RemotePlugin).
///
/// This BRP transport cannot be used when targeting WASM.
///
/// The defaults are:
/// - [`DEFAULT_ADDR`] : 127.0.0.1.
/// - [`DEFAULT_PORT`] : 15702.
///
pub struct RemoteHttpPlugin {
/// The address that Bevy will bind to.
address: IpAddr,
/// The port that Bevy will listen on.
port: u16,
/// The headers that Bevy will include in its HTTP responses
headers: Headers,
}
impl Default for RemoteHttpPlugin {
fn default() -> Self {
Self {
address: DEFAULT_ADDR,
port: DEFAULT_PORT,
headers: Headers::new(),
}
}
}
impl Plugin for RemoteHttpPlugin {
fn build(&self, app: &mut App) {
app.insert_resource(HostAddress(self.address))
.insert_resource(HostPort(self.port))
.insert_resource(HostHeaders(self.headers.clone()))
.add_systems(Startup, start_http_server);
}
}
impl RemoteHttpPlugin {
/// Set the IP address that the server will use.
#[must_use]
pub fn with_address(mut self, address: impl Into<IpAddr>) -> Self {
self.address = address.into();
self
}
/// Set the remote port that the server will listen on.
#[must_use]
pub fn with_port(mut self, port: u16) -> Self {
self.port = port;
self
}
/// Set the extra headers that the response will include.
///
/// ////// /// # Example
///
/// ```ignore
///
/// // Create CORS headers
/// let cors_headers = Headers::new()
/// .insert("Access-Control-Allow-Origin", "*")
/// .insert("Access-Control-Allow-Headers", "Content-Type");
///
/// // Create the Bevy app and add the RemoteHttpPlugin with CORS headers
/// fn main() {
/// App::new()
/// .add_plugins(DefaultPlugins)
/// .add_plugins(RemotePlugin::default())
/// .add_plugins(RemoteHttpPlugin::default()
/// .with_headers(cors_headers))
/// .run();
/// }
/// ```
#[must_use]
pub fn with_headers(mut self, headers: Headers) -> Self {
self.headers = headers;
self
}
/// Add a single header to the response headers.
#[must_use]
pub fn with_header(
mut self,
name: impl TryInto<HeaderName>,
value: impl TryInto<HeaderValue>,
) -> Self {
self.headers = self.headers.insert(name, value);
self
}
}
/// A resource containing the IP address that Bevy will host on.
///
/// Currently, changing this while the application is running has no effect; this merely
/// reflects the IP address that is set during the setup of the [`RemoteHttpPlugin`].
#[derive(Debug, Resource)]
pub struct HostAddress(pub IpAddr);
/// A resource containing the port number that Bevy will listen on.
///
/// Currently, changing this while the application is running has no effect; this merely
/// reflects the host that is set during the setup of the [`RemoteHttpPlugin`].
#[derive(Debug, Resource)]
pub struct HostPort(pub u16);
/// A resource containing the headers that Bevy will include in its HTTP responses.
///
#[derive(Debug, Resource)]
struct HostHeaders(pub Headers);
/// A system that starts up the Bevy Remote Protocol HTTP server.
fn start_http_server(
request_sender: Res<BrpSender>,
address: Res<HostAddress>,
remote_port: Res<HostPort>,
headers: Res<HostHeaders>,
) {
IoTaskPool::get()
.spawn(server_main(
address.0,
remote_port.0,
request_sender.clone(),
headers.0.clone(),
))
.detach();
}
/// The Bevy Remote Protocol server main loop.
async fn server_main(
address: IpAddr,
port: u16,
request_sender: Sender<BrpMessage>,
headers: Headers,
) -> AnyhowResult<()> {
listen(
Async::<TcpListener>::bind((address, port))?,
&request_sender,
&headers,
)
.await
}
async fn listen(
listener: Async<TcpListener>,
request_sender: &Sender<BrpMessage>,
headers: &Headers,
) -> AnyhowResult<()> {
loop {
let (client, _) = listener.accept().await?;
let request_sender = request_sender.clone();
let headers = headers.clone();
IoTaskPool::get()
.spawn(async move {
let _ = handle_client(client, request_sender, headers).await;
})
.detach();
}
}
async fn handle_client(
client: Async<TcpStream>,
request_sender: Sender<BrpMessage>,
headers: Headers,
) -> AnyhowResult<()> {
http1::Builder::new()
.timer(SmolTimer::new())
.serve_connection(
FuturesIo::new(client),
service::service_fn(|request| {
process_request_batch(request, &request_sender, &headers)
}),
)
.await?;
Ok(())
}
/// A helper function for the Bevy Remote Protocol server that handles a batch
/// of requests coming from a client.
async fn process_request_batch(
request: Request<Incoming>,
request_sender: &Sender<BrpMessage>,
headers: &Headers,
) -> AnyhowResult<Response<BrpHttpBody>> {
let batch_bytes = request.into_body().collect().await?.to_bytes();
let batch: Result<BrpBatch, _> = serde_json::from_slice(&batch_bytes);
let result = match batch {
Ok(BrpBatch::Single(request)) => {
let response = process_single_request(request, request_sender).await?;
match response {
BrpHttpResponse::Complete(res) => {
BrpHttpResponse::Complete(serde_json::to_string(&res)?)
}
BrpHttpResponse::Stream(stream) => BrpHttpResponse::Stream(stream),
}
}
Ok(BrpBatch::Batch(requests)) => {
let mut responses = Vec::new();
for request in requests {
let response = process_single_request(request, request_sender).await?;
match response {
BrpHttpResponse::Complete(res) => responses.push(res),
BrpHttpResponse::Stream(BrpStream { id, .. }) => {
responses.push(BrpResponse::new(
id,
Err(BrpError {
code: error_codes::INVALID_REQUEST,
message: "Streaming can not be used in batch requests".to_string(),
data: None,
}),
));
}
}
}
BrpHttpResponse::Complete(serde_json::to_string(&responses)?)
}
Err(err) => {
let err = BrpResponse::new(
None,
Err(BrpError {
code: error_codes::INVALID_REQUEST,
message: err.to_string(),
data: None,
}),
);
BrpHttpResponse::Complete(serde_json::to_string(&err)?)
}
};
let mut response = match result {
BrpHttpResponse::Complete(serialized) => {
let mut response = Response::new(BrpHttpBody::Complete(Full::new(Bytes::from(
serialized.as_bytes().to_owned(),
))));
response.headers_mut().insert(
hyper::header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
response
}
BrpHttpResponse::Stream(stream) => {
let mut response = Response::new(BrpHttpBody::Stream(stream));
response.headers_mut().insert(
hyper::header::CONTENT_TYPE,
HeaderValue::from_static("text/event-stream"),
);
response
}
};
for (key, value) in &headers.headers {
response.headers_mut().insert(key, value.clone());
}
Ok(response)
}
/// A helper function for the Bevy Remote Protocol server that processes a single
/// request coming from a client.
async fn process_single_request(
request: Value,
request_sender: &Sender<BrpMessage>,
) -> AnyhowResult<BrpHttpResponse<BrpResponse, BrpStream>> {
// Reach in and get the request ID early so that we can report it even when parsing fails.
let id = request.as_object().and_then(|map| map.get("id")).cloned();
let request: BrpRequest = match serde_json::from_value(request) {
Ok(v) => v,
Err(err) => {
return Ok(BrpHttpResponse::Complete(BrpResponse::new(
id,
Err(BrpError {
code: error_codes::INVALID_REQUEST,
message: err.to_string(),
data: None,
}),
)));
}
};
if request.jsonrpc != "2.0" {
return Ok(BrpHttpResponse::Complete(BrpResponse::new(
id,
Err(BrpError {
code: error_codes::INVALID_REQUEST,
message: String::from("JSON-RPC request requires `\"jsonrpc\": \"2.0\"`"),
data: None,
}),
)));
}
let watch = request.method.contains("+watch");
let size = if watch { 8 } else { 1 };
let (result_sender, result_receiver) = async_channel::bounded(size);
let _ = request_sender
.send(BrpMessage {
method: request.method,
params: request.params,
sender: result_sender,
})
.await;
if watch {
Ok(BrpHttpResponse::Stream(BrpStream {
id: request.id,
rx: Box::pin(result_receiver),
}))
} else {
let result = result_receiver.recv().await?;
Ok(BrpHttpResponse::Complete(BrpResponse::new(
request.id, result,
)))
}
}
struct BrpStream {
id: Option<Value>,
rx: Pin<Box<Receiver<BrpResult>>>,
}
impl Body for BrpStream {
type Data = Bytes;
type Error = Infallible;
fn poll_frame(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
match self.as_mut().rx.poll_next(cx) {
Poll::Ready(result) => match result {
Some(result) => {
let response = BrpResponse::new(self.id.clone(), result);
let serialized = serde_json::to_string(&response).unwrap();
let bytes =
Bytes::from(format!("data: {serialized}\n\n").as_bytes().to_owned());
let frame = Frame::data(bytes);
Poll::Ready(Some(Ok(frame)))
}
None => Poll::Ready(None),
},
Poll::Pending => Poll::Pending,
}
}
fn is_end_stream(&self) -> bool {
self.rx.is_closed()
}
}
enum BrpHttpResponse<C, S> {
Complete(C),
Stream(S),
}
enum BrpHttpBody {
Complete(Full<Bytes>),
Stream(BrpStream),
}
impl Body for BrpHttpBody {
type Data = Bytes;
type Error = Infallible;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
match &mut *self.get_mut() {
BrpHttpBody::Complete(body) => Body::poll_frame(Pin::new(body), cx),
BrpHttpBody::Stream(body) => Body::poll_frame(Pin::new(body), cx),
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_remote/src/schemas/open_rpc.rs | crates/bevy_remote/src/schemas/open_rpc.rs | //! Module with trimmed down `OpenRPC` document structs.
//! It tries to follow this standard: <https://spec.open-rpc.org>
use bevy_platform::collections::HashMap;
use bevy_utils::default;
use serde::{Deserialize, Serialize};
use crate::RemoteMethods;
use super::json_schema::JsonSchemaBevyType;
/// Represents an `OpenRPC` document as defined by the `OpenRPC` specification.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenRpcDocument {
/// The version of the `OpenRPC` specification being used.
pub openrpc: String,
/// Informational metadata about the document.
pub info: InfoObject,
/// List of RPC methods defined in the document.
pub methods: Vec<MethodObject>,
/// Optional list of server objects that provide the API endpoint details.
pub servers: Option<Vec<ServerObject>>,
}
/// Contains metadata information about the `OpenRPC` document.
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct InfoObject {
/// The title of the API or document.
pub title: String,
/// The version of the API.
pub version: String,
/// An optional description providing additional details about the API.
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// A collection of custom extension fields.
#[serde(flatten)]
pub extensions: HashMap<String, serde_json::Value>,
}
impl Default for InfoObject {
fn default() -> Self {
Self {
title: "Bevy Remote Protocol".to_owned(),
version: env!("CARGO_PKG_VERSION").to_owned(),
description: None,
extensions: Default::default(),
}
}
}
/// Describes a server hosting the API as specified in the `OpenRPC` document.
#[derive(Serialize, Deserialize, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct ServerObject {
/// The name of the server.
pub name: String,
/// The URL endpoint of the server.
pub url: String,
/// An optional description of the server.
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// Additional custom extension fields.
#[serde(flatten)]
pub extensions: HashMap<String, serde_json::Value>,
}
/// Represents an RPC method in the `OpenRPC` document.
#[derive(Serialize, Deserialize, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct MethodObject {
#[expect(
clippy::doc_markdown,
reason = "In this case, we are referring to a string, so using quotes instead of backticks makes sense."
)]
/// The method name (e.g., "world.get_components")
pub name: String,
/// An optional short summary of the method.
#[serde(skip_serializing_if = "Option::is_none")]
pub summary: Option<String>,
/// An optional detailed description of the method.
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// Parameters for the RPC method
#[serde(default)]
pub params: Vec<Parameter>,
// /// The expected result of the method
// #[serde(skip_serializing_if = "Option::is_none")]
// pub result: Option<Parameter>,
/// Additional custom extension fields.
#[serde(flatten)]
pub extensions: HashMap<String, serde_json::Value>,
}
/// Represents an RPC method parameter in the `OpenRPC` document.
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Parameter {
/// Parameter name
pub name: String,
/// Parameter description
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// JSON schema describing the parameter
pub schema: JsonSchemaBevyType,
/// Additional custom extension fields.
#[serde(flatten)]
pub extensions: HashMap<String, serde_json::Value>,
}
impl From<&RemoteMethods> for Vec<MethodObject> {
fn from(value: &RemoteMethods) -> Self {
value
.methods()
.iter()
.map(|e| MethodObject {
name: e.to_owned(),
..default()
})
.collect()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_remote/src/schemas/json_schema.rs | crates/bevy_remote/src/schemas/json_schema.rs | //! Module with JSON Schema type for Bevy Registry Types.
//! It tries to follow this standard: <https://json-schema.org/specification>
use alloc::borrow::Cow;
use bevy_platform::collections::HashMap;
use bevy_reflect::{
GetTypeRegistration, NamedField, OpaqueInfo, TypeInfo, TypeRegistration, TypeRegistry,
VariantInfo,
};
use core::any::TypeId;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use crate::schemas::SchemaTypesMetadata;
/// Helper trait for converting `TypeRegistration` to `JsonSchemaBevyType`
pub trait TypeRegistrySchemaReader {
/// Export type JSON Schema.
fn export_type_json_schema<T: GetTypeRegistration + 'static>(
&self,
extra_info: &SchemaTypesMetadata,
) -> Option<JsonSchemaBevyType> {
self.export_type_json_schema_for_id(extra_info, TypeId::of::<T>())
}
/// Export type JSON Schema.
fn export_type_json_schema_for_id(
&self,
extra_info: &SchemaTypesMetadata,
type_id: TypeId,
) -> Option<JsonSchemaBevyType>;
}
impl TypeRegistrySchemaReader for TypeRegistry {
fn export_type_json_schema_for_id(
&self,
extra_info: &SchemaTypesMetadata,
type_id: TypeId,
) -> Option<JsonSchemaBevyType> {
let type_reg = self.get(type_id)?;
Some((type_reg, extra_info).into())
}
}
/// Exports schema info for a given type
pub fn export_type(
reg: &TypeRegistration,
metadata: &SchemaTypesMetadata,
) -> (Cow<'static, str>, JsonSchemaBevyType) {
(reg.type_info().type_path().into(), (reg, metadata).into())
}
impl From<(&TypeRegistration, &SchemaTypesMetadata)> for JsonSchemaBevyType {
fn from(value: (&TypeRegistration, &SchemaTypesMetadata)) -> Self {
let (reg, metadata) = value;
let t = reg.type_info();
let binding = t.type_path_table();
let short_path = binding.short_path();
let type_path = binding.path();
let mut typed_schema = JsonSchemaBevyType {
reflect_types: metadata.get_registered_reflect_types(reg),
short_path: short_path.to_owned(),
type_path: type_path.to_owned(),
crate_name: binding.crate_name().map(str::to_owned),
module_path: binding.module_path().map(str::to_owned),
..Default::default()
};
match t {
TypeInfo::Struct(info) => {
typed_schema.properties = info
.iter()
.map(|field| (field.name().to_owned(), field.ty().ref_type()))
.collect::<HashMap<_, _>>();
typed_schema.required = info
.iter()
.filter(|field| !field.type_path().starts_with("core::option::Option"))
.map(|f| f.name().to_owned())
.collect::<Vec<_>>();
typed_schema.additional_properties = Some(false);
typed_schema.schema_type = SchemaType::Object;
typed_schema.kind = SchemaKind::Struct;
}
TypeInfo::Enum(info) => {
typed_schema.kind = SchemaKind::Enum;
let simple = info
.iter()
.all(|variant| matches!(variant, VariantInfo::Unit(_)));
if simple {
typed_schema.schema_type = SchemaType::String;
typed_schema.one_of = info
.iter()
.map(|variant| match variant {
VariantInfo::Unit(v) => v.name().into(),
_ => unreachable!(),
})
.collect::<Vec<_>>();
} else {
typed_schema.schema_type = SchemaType::Object;
typed_schema.one_of = info
.iter()
.map(|variant| match variant {
VariantInfo::Struct(v) => json!({
"type": "object",
"kind": "Struct",
"typePath": format!("{}::{}", type_path, v.name()),
"shortPath": v.name(),
"properties": v
.iter()
.map(|field| (field.name().to_owned(), field.ref_type()))
.collect::<Map<_, _>>(),
"additionalProperties": false,
"required": v
.iter()
.filter(|field| !field.type_path().starts_with("core::option::Option"))
.map(NamedField::name)
.collect::<Vec<_>>(),
}),
VariantInfo::Tuple(v) => json!({
"type": "array",
"kind": "Tuple",
"typePath": format!("{}::{}", type_path, v.name()),
"shortPath": v.name(),
"prefixItems": v
.iter()
.map(SchemaJsonReference::ref_type)
.collect::<Vec<_>>(),
"items": false,
}),
VariantInfo::Unit(v) => json!({
"typePath": format!("{}::{}", type_path, v.name()),
"shortPath": v.name(),
}),
})
.collect::<Vec<_>>();
}
}
TypeInfo::TupleStruct(info) => {
typed_schema.schema_type = SchemaType::Array;
typed_schema.kind = SchemaKind::TupleStruct;
typed_schema.prefix_items = info
.iter()
.map(SchemaJsonReference::ref_type)
.collect::<Vec<_>>();
typed_schema.items = Some(false.into());
}
TypeInfo::List(info) => {
typed_schema.schema_type = SchemaType::Array;
typed_schema.kind = SchemaKind::List;
typed_schema.items = info.item_ty().ref_type().into();
}
TypeInfo::Array(info) => {
typed_schema.schema_type = SchemaType::Array;
typed_schema.kind = SchemaKind::Array;
typed_schema.items = info.item_ty().ref_type().into();
}
TypeInfo::Map(info) => {
typed_schema.schema_type = SchemaType::Object;
typed_schema.kind = SchemaKind::Map;
typed_schema.key_type = info.key_ty().ref_type().into();
typed_schema.value_type = info.value_ty().ref_type().into();
}
TypeInfo::Tuple(info) => {
typed_schema.schema_type = SchemaType::Array;
typed_schema.kind = SchemaKind::Tuple;
typed_schema.prefix_items = info
.iter()
.map(SchemaJsonReference::ref_type)
.collect::<Vec<_>>();
typed_schema.items = Some(false.into());
}
TypeInfo::Set(info) => {
typed_schema.schema_type = SchemaType::Set;
typed_schema.kind = SchemaKind::Set;
typed_schema.items = info.value_ty().ref_type().into();
}
TypeInfo::Opaque(info) => {
typed_schema.schema_type = info.map_json_type();
typed_schema.kind = SchemaKind::Value;
}
};
typed_schema
}
}
/// JSON Schema type for Bevy Registry Types
/// It tries to follow this standard: <https://json-schema.org/specification>
///
/// To take the full advantage from info provided by Bevy registry it provides extra fields
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct JsonSchemaBevyType {
/// Bevy specific field, short path of the type.
pub short_path: String,
/// Bevy specific field, full path of the type.
pub type_path: String,
/// Bevy specific field, path of the module that type is part of.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub module_path: Option<String>,
/// Bevy specific field, name of the crate that type is part of.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub crate_name: Option<String>,
/// Bevy specific field, names of the types that type reflects.
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub reflect_types: Vec<String>,
/// Bevy specific field, [`TypeInfo`] type mapping.
pub kind: SchemaKind,
/// Bevy specific field, provided when [`SchemaKind`] `kind` field is equal to [`SchemaKind::Map`].
///
/// It contains type info of key of the Map.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub key_type: Option<Value>,
/// Bevy specific field, provided when [`SchemaKind`] `kind` field is equal to [`SchemaKind::Map`].
///
/// It contains type info of value of the Map.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub value_type: Option<Value>,
/// The type keyword is fundamental to JSON Schema. It specifies the data type for a schema.
#[serde(rename = "type")]
pub schema_type: SchemaType,
/// The behavior of this keyword depends on the presence and annotation results of "properties"
/// and "patternProperties" within the same schema object.
/// Validation with "additionalProperties" applies only to the child
/// values of instance names that do not appear in the annotation results of either "properties" or "patternProperties".
#[serde(skip_serializing_if = "Option::is_none", default)]
pub additional_properties: Option<bool>,
/// Validation succeeds if, for each name that appears in both the instance and as a name
/// within this keyword's value, the child instance for that name successfully validates
/// against the corresponding schema.
#[serde(skip_serializing_if = "HashMap::is_empty", default)]
pub properties: HashMap<String, Value>,
/// An object instance is valid against this keyword if every item in the array is the name of a property in the instance.
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub required: Vec<String>,
/// An instance validates successfully against this keyword if it validates successfully against exactly one schema defined by this keyword's value.
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub one_of: Vec<Value>,
/// Validation succeeds if each element of the instance validates against the schema at the same position, if any. This keyword does not constrain the length of the array. If the array is longer than this keyword's value, this keyword validates only the prefix of matching length.
///
/// This keyword produces an annotation value which is the largest index to which this keyword
/// applied a subschema. The value MAY be a boolean true if a subschema was applied to every
/// index of the instance, such as is produced by the "items" keyword.
/// This annotation affects the behavior of "items" and "unevaluatedItems".
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub prefix_items: Vec<Value>,
/// This keyword applies its subschema to all instance elements at indexes greater
/// than the length of the "prefixItems" array in the same schema object,
/// as reported by the annotation result of that "prefixItems" keyword.
/// If no such annotation result exists, "items" applies its subschema to all
/// instance array elements.
///
/// If the "items" subschema is applied to any positions within the instance array,
/// it produces an annotation result of boolean true, indicating that all remaining
/// array elements have been evaluated against this keyword's subschema.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub items: Option<Value>,
}
/// Kind of json schema, maps [`TypeInfo`] type
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
pub enum SchemaKind {
/// Struct
#[default]
Struct,
/// Enum type
Enum,
/// A key-value map
Map,
/// Array
Array,
/// List
List,
/// Fixed size collection of items
Tuple,
/// Fixed size collection of items with named fields
TupleStruct,
/// Set of unique values
Set,
/// Single value, eg. primitive types
Value,
}
/// Type of json schema
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum SchemaType {
/// Represents a string value.
String,
/// Represents a floating-point number.
Float,
/// Represents an unsigned integer.
Uint,
/// Represents a signed integer.
Int,
/// Represents an object with key-value pairs.
Object,
/// Represents an array of values.
Array,
/// Represents a boolean value (true or false).
Boolean,
/// Represents a set of unique values.
Set,
/// Represents a null value.
#[default]
Null,
}
/// Helper trait for generating json schema reference
trait SchemaJsonReference {
/// Reference to another type in schema.
/// The value `$ref` is a URI-reference that is resolved against the schema.
fn ref_type(self) -> Value;
}
/// Helper trait for mapping bevy type path into json schema type
pub trait SchemaJsonType {
/// Bevy Reflect type path
fn get_type_path(&self) -> &'static str;
/// JSON Schema type keyword from Bevy reflect type path into
fn map_json_type(&self) -> SchemaType {
match self.get_type_path() {
"bool" => SchemaType::Boolean,
"u8" | "u16" | "u32" | "u64" | "u128" | "usize" => SchemaType::Uint,
"i8" | "i16" | "i32" | "i64" | "i128" | "isize" => SchemaType::Int,
"f32" | "f64" => SchemaType::Float,
"char" | "str" | "alloc::string::String" => SchemaType::String,
_ => SchemaType::Object,
}
}
}
impl SchemaJsonType for OpaqueInfo {
fn get_type_path(&self) -> &'static str {
self.type_path()
}
}
impl SchemaJsonReference for &bevy_reflect::Type {
fn ref_type(self) -> Value {
let path = self.path();
json!({"type": json!({ "$ref": format!("#/$defs/{path}") })})
}
}
impl SchemaJsonReference for &bevy_reflect::UnnamedField {
fn ref_type(self) -> Value {
let path = self.type_path();
json!({"type": json!({ "$ref": format!("#/$defs/{path}") })})
}
}
impl SchemaJsonReference for &NamedField {
fn ref_type(self) -> Value {
let type_path = self.type_path();
json!({"type": json!({ "$ref": format!("#/$defs/{type_path}") }), "typePath": self.name()})
}
}
#[cfg(test)]
mod tests {
use super::*;
use bevy_ecs::prelude::ReflectComponent;
use bevy_ecs::prelude::ReflectResource;
use bevy_ecs::{component::Component, reflect::AppTypeRegistry, resource::Resource};
use bevy_reflect::prelude::ReflectDefault;
use bevy_reflect::{Reflect, ReflectDeserialize, ReflectSerialize};
#[test]
fn reflect_export_struct() {
#[derive(Reflect, Resource, Default, Deserialize, Serialize)]
#[reflect(Resource, Default, Serialize, Deserialize)]
struct Foo {
a: f32,
b: Option<f32>,
}
let atr = AppTypeRegistry::default();
{
let mut register = atr.write();
register.register::<Foo>();
}
let type_registry = atr.read();
let foo_registration = type_registry
.get(TypeId::of::<Foo>())
.expect("SHOULD BE REGISTERED")
.clone();
let (_, schema) = export_type(&foo_registration, &SchemaTypesMetadata::default());
assert!(
!schema.reflect_types.contains(&"Component".to_owned()),
"Should not be a component"
);
assert!(
schema.reflect_types.contains(&"Resource".to_owned()),
"Should be a resource"
);
let _ = schema.properties.get("a").expect("Missing `a` field");
let _ = schema.properties.get("b").expect("Missing `b` field");
assert!(
schema.required.contains(&"a".to_owned()),
"Field a should be required"
);
assert!(
!schema.required.contains(&"b".to_owned()),
"Field b should not be required"
);
}
#[test]
fn reflect_export_enum() {
#[derive(Reflect, Component, Default, Deserialize, Serialize)]
#[reflect(Component, Default, Serialize, Deserialize)]
enum EnumComponent {
ValueOne(i32),
ValueTwo {
test: i32,
},
#[default]
NoValue,
}
let atr = AppTypeRegistry::default();
{
let mut register = atr.write();
register.register::<EnumComponent>();
}
let type_registry = atr.read();
let foo_registration = type_registry
.get(TypeId::of::<EnumComponent>())
.expect("SHOULD BE REGISTERED")
.clone();
let (_, schema) = export_type(&foo_registration, &SchemaTypesMetadata::default());
assert!(
schema.reflect_types.contains(&"Component".to_owned()),
"Should be a component"
);
assert!(
!schema.reflect_types.contains(&"Resource".to_owned()),
"Should not be a resource"
);
assert!(schema.properties.is_empty(), "Should not have any field");
assert!(schema.one_of.len() == 3, "Should have 3 possible schemas");
}
#[test]
fn reflect_export_struct_without_reflect_types() {
#[derive(Reflect, Component, Default, Deserialize, Serialize)]
enum EnumComponent {
ValueOne(i32),
ValueTwo {
test: i32,
},
#[default]
NoValue,
}
let atr = AppTypeRegistry::default();
{
let mut register = atr.write();
register.register::<EnumComponent>();
}
let type_registry = atr.read();
let foo_registration = type_registry
.get(TypeId::of::<EnumComponent>())
.expect("SHOULD BE REGISTERED")
.clone();
let (_, schema) = export_type(&foo_registration, &SchemaTypesMetadata::default());
assert!(
!schema.reflect_types.contains(&"Component".to_owned()),
"Should not be a component"
);
assert!(
!schema.reflect_types.contains(&"Resource".to_owned()),
"Should not be a resource"
);
assert!(schema.properties.is_empty(), "Should not have any field");
assert!(schema.one_of.len() == 3, "Should have 3 possible schemas");
}
#[test]
fn reflect_struct_with_custom_type_data() {
#[derive(Reflect, Default, Deserialize, Serialize)]
#[reflect(Default)]
enum EnumComponent {
ValueOne(i32),
ValueTwo {
test: i32,
},
#[default]
NoValue,
}
#[derive(Clone)]
pub struct ReflectCustomData;
impl<T: Reflect> bevy_reflect::FromType<T> for ReflectCustomData {
fn from_type() -> Self {
ReflectCustomData
}
}
let atr = AppTypeRegistry::default();
{
let mut register = atr.write();
register.register::<EnumComponent>();
register.register_type_data::<EnumComponent, ReflectCustomData>();
}
let mut metadata = SchemaTypesMetadata::default();
metadata.map_type_data::<ReflectCustomData>("CustomData");
let type_registry = atr.read();
let foo_registration = type_registry
.get(TypeId::of::<EnumComponent>())
.expect("SHOULD BE REGISTERED")
.clone();
let (_, schema) = export_type(&foo_registration, &metadata);
assert!(
!metadata.has_type_data::<ReflectComponent>(&schema.reflect_types),
"Should not be a component"
);
assert!(
!metadata.has_type_data::<ReflectResource>(&schema.reflect_types),
"Should not be a resource"
);
assert!(
metadata.has_type_data::<ReflectDefault>(&schema.reflect_types),
"Should have default"
);
assert!(
metadata.has_type_data::<ReflectCustomData>(&schema.reflect_types),
"Should have CustomData"
);
assert!(schema.properties.is_empty(), "Should not have any field");
assert!(schema.one_of.len() == 3, "Should have 3 possible schemas");
}
#[test]
fn reflect_export_tuple_struct() {
#[derive(Reflect, Component, Default, Deserialize, Serialize)]
#[reflect(Component, Default, Serialize, Deserialize)]
struct TupleStructType(usize, i32);
let atr = AppTypeRegistry::default();
{
let mut register = atr.write();
register.register::<TupleStructType>();
}
let type_registry = atr.read();
let foo_registration = type_registry
.get(TypeId::of::<TupleStructType>())
.expect("SHOULD BE REGISTERED")
.clone();
let (_, schema) = export_type(&foo_registration, &SchemaTypesMetadata::default());
assert!(
schema.reflect_types.contains(&"Component".to_owned()),
"Should be a component"
);
assert!(
!schema.reflect_types.contains(&"Resource".to_owned()),
"Should not be a resource"
);
assert!(schema.properties.is_empty(), "Should not have any field");
assert!(schema.prefix_items.len() == 2, "Should have 2 prefix items");
}
#[test]
fn reflect_export_serialization_check() {
#[derive(Reflect, Resource, Default, Deserialize, Serialize)]
#[reflect(Resource, Default)]
struct Foo {
a: f32,
}
let atr = AppTypeRegistry::default();
{
let mut register = atr.write();
register.register::<Foo>();
}
let type_registry = atr.read();
let foo_registration = type_registry
.get(TypeId::of::<Foo>())
.expect("SHOULD BE REGISTERED")
.clone();
let (_, schema) = export_type(&foo_registration, &SchemaTypesMetadata::default());
let schema_as_value = serde_json::to_value(&schema).expect("Should serialize");
let value = json!({
"shortPath": "Foo",
"typePath": "bevy_remote::schemas::json_schema::tests::Foo",
"modulePath": "bevy_remote::schemas::json_schema::tests",
"crateName": "bevy_remote",
"reflectTypes": [
"Resource",
"Default",
],
"kind": "Struct",
"type": "object",
"additionalProperties": false,
"properties": {
"a": {
"type": {
"$ref": "#/$defs/f32"
}
},
},
"required": [
"a"
]
});
assert_normalized_values(schema_as_value, value);
}
/// This function exist to avoid false failures due to ordering differences between `serde_json` values.
fn assert_normalized_values(mut one: Value, mut two: Value) {
normalize_json(&mut one);
normalize_json(&mut two);
assert_eq!(one, two);
/// Recursively sorts arrays in a `serde_json::Value`
fn normalize_json(value: &mut Value) {
match value {
Value::Array(arr) => {
for v in arr.iter_mut() {
normalize_json(v);
}
arr.sort_by_key(ToString::to_string); // Sort by stringified version
}
Value::Object(map) => {
for (_k, v) in map.iter_mut() {
normalize_json(v);
}
}
_ => {}
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_remote/src/schemas/mod.rs | crates/bevy_remote/src/schemas/mod.rs | //! Module with schemas used for various BRP endpoints
use bevy_ecs::{
reflect::{ReflectComponent, ReflectEvent, ReflectResource},
resource::Resource,
};
use bevy_platform::collections::HashMap;
use bevy_reflect::{
prelude::ReflectDefault, Reflect, ReflectDeserialize, ReflectSerialize, TypeData,
TypeRegistration,
};
use core::any::TypeId;
pub mod json_schema;
pub mod open_rpc;
/// Holds mapping of reflect [type data](TypeData) to strings,
/// later on used in Bevy Json Schema.
#[derive(Debug, Resource, Reflect)]
#[reflect(Resource)]
pub struct SchemaTypesMetadata {
/// Type Data id mapping to strings.
pub type_data_map: HashMap<TypeId, String>,
}
impl Default for SchemaTypesMetadata {
fn default() -> Self {
let mut data_types = Self {
type_data_map: Default::default(),
};
data_types.map_type_data::<ReflectComponent>("Component");
data_types.map_type_data::<ReflectResource>("Resource");
data_types.map_type_data::<ReflectEvent>("Event");
data_types.map_type_data::<ReflectDefault>("Default");
#[cfg(feature = "bevy_asset")]
data_types.map_type_data::<bevy_asset::ReflectAsset>("Asset");
#[cfg(feature = "bevy_asset")]
data_types.map_type_data::<bevy_asset::ReflectHandle>("AssetHandle");
data_types.map_type_data::<ReflectSerialize>("Serialize");
data_types.map_type_data::<ReflectDeserialize>("Deserialize");
data_types
}
}
impl SchemaTypesMetadata {
/// Map `TypeId` of `TypeData` to string
pub fn map_type_data<T: TypeData>(&mut self, name: impl Into<String>) {
self.type_data_map.insert(TypeId::of::<T>(), name.into());
}
/// Build reflect types list for a given type registration
pub fn get_registered_reflect_types(&self, reg: &TypeRegistration) -> Vec<String> {
self.type_data_map
.iter()
.filter_map(|(id, name)| reg.data_by_id(*id).and(Some(name.clone())))
.collect()
}
/// Checks if slice contains string value that matches checked `TypeData`
pub fn has_type_data<T: TypeData>(&self, types_string_slice: &[String]) -> bool {
self.has_type_data_by_id(TypeId::of::<T>(), types_string_slice)
}
/// Checks if slice contains string value that matches checked `TypeData` by id.
pub fn has_type_data_by_id(&self, id: TypeId, types_string_slice: &[String]) -> bool {
self.type_data_map
.get(&id)
.is_some_and(|data_s| types_string_slice.iter().any(|e| e.eq(data_s)))
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_winit/src/lib.rs | crates/bevy_winit/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"
)]
//! `bevy_winit` provides utilities to handle window creation and the eventloop through [`winit`]
//!
//! Most commonly, the [`WinitPlugin`] is used as part of
//! [`DefaultPlugins`](https://docs.rs/bevy/latest/bevy/struct.DefaultPlugins.html).
//! The app's [runner](bevy_app::App::runner) is set by `WinitPlugin` and handles the `winit` [`EventLoop`].
//! See `winit_runner` for details.
extern crate alloc;
use bevy_derive::Deref;
use bevy_reflect::Reflect;
use bevy_window::{RawHandleWrapperHolder, WindowEvent};
use core::cell::RefCell;
use winit::{event_loop::EventLoop, window::WindowId};
use bevy_a11y::AccessibilityRequested;
use bevy_app::{App, Last, Plugin};
use bevy_ecs::prelude::*;
use bevy_window::{exit_on_all_closed, CursorOptions, Window, WindowCreated};
use system::{changed_cursor_options, changed_windows, check_keyboard_focus_lost, despawn_windows};
pub use system::{create_monitors, create_windows};
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
pub use winit::platform::web::CustomCursorExtWebSys;
pub use winit::{
event_loop::EventLoopProxy,
window::{CustomCursor as WinitCustomCursor, CustomCursorSource},
};
pub use winit_config::*;
pub use winit_monitors::*;
pub use winit_windows::*;
use crate::{
accessibility::{AccessKitPlugin, WinitActionRequestHandlers},
state::winit_runner,
};
pub mod accessibility;
pub mod converters;
mod cursor;
mod state;
mod system;
mod winit_config;
mod winit_monitors;
mod winit_windows;
thread_local! {
/// Temporary storage of WinitWindows data to replace usage of `!Send` resources. This will be replaced with proper
/// storage of `!Send` data after issue #17667 is complete.
pub static WINIT_WINDOWS: RefCell<WinitWindows> = const { RefCell::new(WinitWindows::new()) };
}
/// A [`Plugin`] that uses `winit` to create and manage windows, and receive window and input
/// events.
///
/// This plugin will add systems and resources that sync with the `winit` backend and also
/// replace the existing [`App`] runner with one that constructs an [event loop](EventLoop) to
/// receive window and input events from the OS.
///
/// The `M` message type can be used to pass custom messages to the `winit`'s loop, and handled as messages
/// in systems.
///
/// When using eg. `MinimalPlugins` you can add this using `WinitPlugin::<WakeUp>::default()`, where
/// `WakeUp` is the default event that bevy uses.
#[derive(Default)]
pub struct WinitPlugin {
/// Allows the window (and the event loop) to be created on any thread
/// instead of only the main thread.
///
/// See [`EventLoopBuilder::build`](winit::event_loop::EventLoopBuilder::build) for more information on this.
///
/// # Supported platforms
///
/// Only works on Linux (X11/Wayland) and Windows.
/// This field is ignored on other platforms.
pub run_on_any_thread: bool,
}
impl Plugin for WinitPlugin {
fn name(&self) -> &str {
"bevy_winit::WinitPlugin"
}
fn build(&self, app: &mut App) {
let mut event_loop_builder = EventLoop::<WinitUserEvent>::with_user_event();
// linux check is needed because x11 might be enabled on other platforms.
#[cfg(all(target_os = "linux", feature = "x11"))]
{
use winit::platform::x11::EventLoopBuilderExtX11;
// This allows a Bevy app to be started and ran outside the main thread.
// A use case for this is to allow external applications to spawn a thread
// which runs a Bevy app without requiring the Bevy app to need to reside on
// the main thread, which can be problematic.
event_loop_builder.with_any_thread(self.run_on_any_thread);
}
// linux check is needed because wayland might be enabled on other platforms.
#[cfg(all(target_os = "linux", feature = "wayland"))]
{
use winit::platform::wayland::EventLoopBuilderExtWayland;
event_loop_builder.with_any_thread(self.run_on_any_thread);
}
#[cfg(target_os = "windows")]
{
use winit::platform::windows::EventLoopBuilderExtWindows;
event_loop_builder.with_any_thread(self.run_on_any_thread);
}
#[cfg(target_os = "android")]
{
use winit::platform::android::EventLoopBuilderExtAndroid;
let msg = "Bevy must be setup with the #[bevy_main] macro on Android";
event_loop_builder
.with_android_app(bevy_android::ANDROID_APP.get().expect(msg).clone());
}
let event_loop = event_loop_builder
.build()
.expect("Failed to build event loop");
app.init_resource::<WinitMonitors>()
.init_resource::<WinitSettings>()
.insert_resource(DisplayHandleWrapper(event_loop.owned_display_handle()))
.insert_resource(EventLoopProxyWrapper(event_loop.create_proxy()))
.add_message::<RawWinitWindowEvent>()
.set_runner(|app| winit_runner(app, event_loop))
.add_systems(
Last,
(
// `exit_on_all_closed` only checks if windows exist but doesn't access data,
// so we don't need to care about its ordering relative to `changed_windows`
changed_windows.ambiguous_with(exit_on_all_closed),
changed_cursor_options,
despawn_windows,
check_keyboard_focus_lost,
)
.chain(),
);
app.add_plugins(AccessKitPlugin);
app.add_plugins(cursor::WinitCursorPlugin);
app.add_observer(
|_window: On<Add, Window>, event_loop_proxy: Res<EventLoopProxyWrapper>| -> Result {
event_loop_proxy.send_event(WinitUserEvent::WindowAdded)?;
Ok(())
},
);
}
}
/// Events that can be sent to perform actions inside the winit event loop.
///
/// Sent via the [`EventLoopProxyWrapper`] resource.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # use bevy_winit::{EventLoopProxyWrapper, WinitUserEvent};
/// fn wakeup_system(event_loop_proxy: Res<EventLoopProxyWrapper>) -> Result {
/// event_loop_proxy.send_event(WinitUserEvent::WakeUp)?;
///
/// Ok(())
/// }
/// ```
#[derive(Debug, Clone, Copy, Reflect)]
#[reflect(Debug, Clone)]
pub enum WinitUserEvent {
/// Dummy event that just wakes up the winit event loop
WakeUp,
/// Tell winit that a window needs to be created
WindowAdded,
}
/// The original window event as produced by Winit. This is meant as an escape
/// hatch for power users that wish to add custom Winit integrations.
/// If you want to process events for your app or game, you should instead use
/// `bevy::window::WindowEvent`, or one of its sub-events.
///
/// When you receive this event it has already been handled by Bevy's main loop.
/// Sending these events will NOT cause them to be processed by Bevy.
#[derive(Debug, Clone, Message)]
pub struct RawWinitWindowEvent {
/// The window for which the event was fired.
pub window_id: WindowId,
/// The raw winit window event.
pub event: winit::event::WindowEvent,
}
/// A wrapper type around [`winit::event_loop::EventLoopProxy`] with the specific
/// [`winit::event::Event::UserEvent`] used in the [`WinitPlugin`].
///
/// The `EventLoopProxy` can be used to request a redraw from outside bevy.
///
/// Use `Res<EventLoopProxyWrapper>` to retrieve this resource.
#[derive(Resource, Deref)]
pub struct EventLoopProxyWrapper(EventLoopProxy<WinitUserEvent>);
/// A wrapper around [`winit::event_loop::OwnedDisplayHandle`]
///
/// The `DisplayHandleWrapper` can be used to build integrations that rely on direct
/// access to the display handle
///
/// Use `Res<DisplayHandleWrapper>` to receive this resource.
#[derive(Resource, Deref)]
pub struct DisplayHandleWrapper(pub winit::event_loop::OwnedDisplayHandle);
trait AppSendEvent {
fn send(&mut self, event: impl Into<WindowEvent>);
}
impl AppSendEvent for Vec<WindowEvent> {
fn send(&mut self, event: impl Into<WindowEvent>) {
self.push(Into::<WindowEvent>::into(event));
}
}
/// The parameters of the [`create_windows`] system.
pub type CreateWindowParams<'w, 's> = (
Commands<'w, 's>,
Query<
'w,
's,
(
Entity,
&'static mut Window,
&'static CursorOptions,
Option<&'static RawHandleWrapperHolder>,
),
Added<Window>,
>,
MessageWriter<'w, WindowCreated>,
ResMut<'w, WinitActionRequestHandlers>,
Res<'w, AccessibilityRequested>,
Res<'w, WinitMonitors>,
);
/// The parameters of the [`create_monitors`] system.
pub type CreateMonitorParams<'w, 's> = (Commands<'w, 's>, ResMut<'w, WinitMonitors>);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_winit/src/winit_config.rs | crates/bevy_winit/src/winit_config.rs | use bevy_ecs::resource::Resource;
use core::time::Duration;
/// Settings for the [`WinitPlugin`](super::WinitPlugin).
#[derive(Debug, Resource, Clone)]
pub struct WinitSettings {
/// Determines how frequently the application can update when it has focus.
pub focused_mode: UpdateMode,
/// Determines how frequently the application can update when it's out of focus.
pub unfocused_mode: UpdateMode,
}
impl WinitSettings {
/// Default settings for games.
///
/// [`Continuous`](UpdateMode::Continuous) if windows have focus,
/// [`reactive_low_power`](UpdateMode::reactive_low_power) otherwise.
pub fn game() -> Self {
WinitSettings {
focused_mode: UpdateMode::Continuous,
unfocused_mode: UpdateMode::reactive_low_power(Duration::from_secs_f64(1.0 / 60.0)), /* 60Hz, */
}
}
/// Default settings for desktop applications.
///
/// [`Reactive`](UpdateMode::Reactive) if windows have focus,
/// [`reactive_low_power`](UpdateMode::reactive_low_power) otherwise.
///
/// Use the [`EventLoopProxy`](crate::EventLoopProxy) to request a redraw from outside bevy.
pub fn desktop_app() -> Self {
WinitSettings {
focused_mode: UpdateMode::reactive(Duration::from_secs(5)),
unfocused_mode: UpdateMode::reactive_low_power(Duration::from_secs(60)),
}
}
/// Default settings for mobile.
///
/// [`Reactive`](UpdateMode::Reactive) if windows have focus,
/// [`reactive_low_power`](UpdateMode::reactive_low_power) otherwise.
///
/// Use the [`EventLoopProxy`](crate::EventLoopProxy) to request a redraw from outside bevy.
pub fn mobile() -> Self {
WinitSettings {
focused_mode: UpdateMode::reactive(Duration::from_secs_f32(1.0 / 60.0)),
unfocused_mode: UpdateMode::reactive_low_power(Duration::from_secs(1)),
}
}
/// The application will update as fast possible.
///
/// Uses [`Continuous`](UpdateMode::Continuous) regardless of whether windows have focus.
pub fn continuous() -> Self {
WinitSettings {
focused_mode: UpdateMode::Continuous,
unfocused_mode: UpdateMode::Continuous,
}
}
/// Returns the current [`UpdateMode`].
///
/// **Note:** The output depends on whether the window has focus or not.
pub fn update_mode(&self, focused: bool) -> UpdateMode {
match focused {
true => self.focused_mode,
false => self.unfocused_mode,
}
}
}
impl Default for WinitSettings {
fn default() -> Self {
WinitSettings::game()
}
}
/// Determines how frequently an [`App`](bevy_app::App) should update.
///
/// **Note:** This setting is independent of VSync. VSync is controlled by a window's
/// [`PresentMode`](bevy_window::PresentMode) setting. If an app can update faster than the refresh
/// rate, but VSync is enabled, the update rate will be indirectly limited by the renderer.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum UpdateMode {
/// The [`App`](bevy_app::App) will update over and over, as fast as it possibly can, until an
/// [`AppExit`](bevy_app::AppExit) event appears.
Continuous,
/// The [`App`](bevy_app::App) will update in response to the following, until an
/// [`AppExit`](bevy_app::AppExit) event appears:
/// - `wait` time has elapsed since the previous update
/// - a redraw has been requested by [`RequestRedraw`](bevy_window::RequestRedraw)
/// - new [window](`winit::event::WindowEvent`), [raw input](`winit::event::DeviceEvent`), or custom
/// events have appeared
/// - a redraw has been requested with the [`EventLoopProxy`](crate::EventLoopProxy)
Reactive {
/// The approximate time from the start of one update to the next.
///
/// **Note:** This has no upper limit.
/// The [`App`](bevy_app::App) will wait indefinitely if you set this to [`Duration::MAX`].
wait: Duration,
/// Reacts to device events, that will wake up the loop if it's in a wait state
react_to_device_events: bool,
/// Reacts to user events, that will wake up the loop if it's in a wait state
react_to_user_events: bool,
/// Reacts to window events, that will wake up the loop if it's in a wait state
react_to_window_events: bool,
},
}
impl UpdateMode {
/// Reactive mode, will update the app for any kind of event
pub fn reactive(wait: Duration) -> Self {
Self::Reactive {
wait,
react_to_device_events: true,
react_to_user_events: true,
react_to_window_events: true,
}
}
/// Low power mode
///
/// Unlike [`Reactive`](`UpdateMode::reactive()`), this will ignore events that
/// don't come from interacting with a window, like [`MouseMotion`](winit::event::DeviceEvent::MouseMotion).
/// Use this if, for example, you only want your app to update when the mouse cursor is
/// moving over a window, not just moving in general. This can greatly reduce power consumption.
pub fn reactive_low_power(wait: Duration) -> Self {
Self::Reactive {
wait,
react_to_device_events: false,
react_to_user_events: true,
react_to_window_events: true,
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_winit/src/winit_monitors.rs | crates/bevy_winit/src/winit_monitors.rs | use winit::monitor::MonitorHandle;
use bevy_ecs::{entity::Entity, resource::Resource};
/// Stores [`winit`] monitors and their corresponding entities
///
/// # Known Issues
///
/// On some platforms, physically disconnecting a monitor might result in a
/// panic in [`winit`]'s loop. This will lead to a crash in the bevy app. See
/// [13669] for investigations and discussions.
///
/// [13669]: https://github.com/bevyengine/bevy/pull/13669
#[derive(Resource, Debug, Default)]
pub struct WinitMonitors {
/// Stores [`winit`] monitors and their corresponding entities
// We can't use a `BtreeMap` here because clippy complains about using `MonitorHandle` as a key
// on some platforms. Using a `Vec` is fine because we don't expect to have a large number of
// monitors and avoids having to audit the code for `MonitorHandle` equality.
pub(crate) monitors: Vec<(MonitorHandle, Entity)>,
}
impl WinitMonitors {
/// Gets the [`MonitorHandle`] at index `n`.
pub fn nth(&self, n: usize) -> Option<MonitorHandle> {
self.monitors.get(n).map(|(monitor, _)| monitor.clone())
}
/// Gets the [`MonitorHandle`] associated with a `Monitor` entity.
pub fn find_entity(&self, entity: Entity) -> Option<MonitorHandle> {
self.monitors
.iter()
.find(|(_, e)| *e == entity)
.map(|(monitor, _)| monitor.clone())
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_winit/src/state.rs | crates/bevy_winit/src/state.rs | use approx::relative_eq;
use bevy_app::{App, AppExit, PluginsState};
use bevy_ecs::{
change_detection::{DetectChanges, Res},
entity::Entity,
message::{MessageCursor, MessageWriter},
prelude::*,
system::SystemState,
world::FromWorld,
};
use bevy_input::{
gestures::*,
mouse::{MouseButtonInput, MouseMotion, MouseScrollUnit, MouseWheel},
};
use bevy_log::{trace, warn};
use bevy_math::{ivec2, DVec2, Vec2};
use bevy_platform::time::Instant;
#[cfg(not(target_arch = "wasm32"))]
use bevy_tasks::tick_global_task_pools_on_main_thread;
#[cfg(target_arch = "wasm32")]
use winit::platform::web::EventLoopExtWebSys;
use winit::{
application::ApplicationHandler,
dpi::PhysicalSize,
event,
event::{DeviceEvent, DeviceId, StartCause, WindowEvent},
event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
window::WindowId,
};
use bevy_window::{
AppLifecycle, CursorEntered, CursorLeft, CursorMoved, FileDragAndDrop, Ime, RequestRedraw,
Window, WindowBackendScaleFactorChanged, WindowCloseRequested, WindowDestroyed,
WindowEvent as BevyWindowEvent, WindowFocused, WindowMoved, WindowOccluded, WindowResized,
WindowScaleFactorChanged, WindowThemeChanged,
};
#[cfg(target_os = "android")]
use bevy_window::{CursorOptions, PrimaryWindow, RawHandleWrapper};
use crate::{
accessibility::ACCESS_KIT_ADAPTERS,
converters, create_windows,
system::{create_monitors, CachedWindow, WinitWindowPressedKeys},
AppSendEvent, CreateMonitorParams, CreateWindowParams, RawWinitWindowEvent, UpdateMode,
WinitSettings, WinitUserEvent, WINIT_WINDOWS,
};
/// Persistent state that is used to run the [`App`] according to the current
/// [`UpdateMode`].
pub(crate) struct WinitAppRunnerState {
/// The running app.
app: App,
/// Exit value once the loop is finished.
app_exit: Option<AppExit>,
/// Current update mode of the app.
update_mode: UpdateMode,
/// Is `true` if a new [`WindowEvent`] event has been received since the last update.
window_event_received: bool,
/// Is `true` if a new [`DeviceEvent`] event has been received since the last update.
device_event_received: bool,
/// Is `true` if a new `T` event has been received since the last update.
user_event_received: bool,
/// Is `true` if the app has requested a redraw since the last update.
redraw_requested: bool,
/// Is `true` if the app has already updated since the last redraw.
ran_update_since_last_redraw: bool,
/// Is `true` if enough time has elapsed since `last_update` to run another update.
wait_elapsed: bool,
/// Number of "forced" updates to trigger on application start
startup_forced_updates: u32,
/// Current app lifecycle state.
lifecycle: AppLifecycle,
/// The previous app lifecycle state.
previous_lifecycle: AppLifecycle,
/// Bevy window events to send
bevy_window_events: Vec<bevy_window::WindowEvent>,
/// Raw Winit window events to send
raw_winit_events: Vec<RawWinitWindowEvent>,
message_writer_system_state: SystemState<(
MessageWriter<'static, WindowResized>,
MessageWriter<'static, WindowBackendScaleFactorChanged>,
MessageWriter<'static, WindowScaleFactorChanged>,
Query<
'static,
'static,
(
&'static mut Window,
&'static mut CachedWindow,
&'static mut WinitWindowPressedKeys,
),
>,
)>,
/// time at which next tick is scheduled to run when `update_mode` is [`UpdateMode::Reactive`]
scheduled_tick_start: Option<Instant>,
}
impl WinitAppRunnerState {
fn new(mut app: App) -> Self {
let message_writer_system_state: SystemState<(
MessageWriter<WindowResized>,
MessageWriter<WindowBackendScaleFactorChanged>,
MessageWriter<WindowScaleFactorChanged>,
Query<(&mut Window, &mut CachedWindow, &mut WinitWindowPressedKeys)>,
)> = SystemState::new(app.world_mut());
Self {
app,
lifecycle: AppLifecycle::Idle,
previous_lifecycle: AppLifecycle::Idle,
app_exit: None,
update_mode: UpdateMode::Continuous,
window_event_received: false,
device_event_received: false,
user_event_received: false,
redraw_requested: false,
ran_update_since_last_redraw: false,
wait_elapsed: false,
// 3 seems to be enough, 5 is a safe margin
startup_forced_updates: 5,
bevy_window_events: Vec::new(),
raw_winit_events: Vec::new(),
message_writer_system_state,
scheduled_tick_start: None,
}
}
fn reset_on_update(&mut self) {
self.window_event_received = false;
self.device_event_received = false;
self.user_event_received = false;
}
fn world(&self) -> &World {
self.app.world()
}
pub(crate) fn world_mut(&mut self) -> &mut World {
self.app.world_mut()
}
}
impl ApplicationHandler<WinitUserEvent> for WinitAppRunnerState {
fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
if event_loop.exiting() {
return;
}
#[cfg(feature = "trace")]
let _span = tracing::info_span!("winit event_handler").entered();
if self.app.plugins_state() != PluginsState::Cleaned {
if self.app.plugins_state() != PluginsState::Ready {
#[cfg(not(target_arch = "wasm32"))]
tick_global_task_pools_on_main_thread();
} else {
self.app.finish();
self.app.cleanup();
}
self.redraw_requested = true;
}
self.wait_elapsed = match cause {
StartCause::WaitCancelled {
requested_resume: Some(resume),
..
} => {
// If the resume time is not after now, it means that at least the wait timeout
// has elapsed.
resume <= Instant::now()
}
_ => true,
};
}
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
// Mark the state as `WillResume`. This will let the schedule run one extra time
// when actually resuming the app
self.lifecycle = AppLifecycle::WillResume;
// Create the initial window if needed
let mut create_window = SystemState::<CreateWindowParams>::from_world(self.world_mut());
create_windows(event_loop, create_window.get_mut(self.world_mut()));
create_window.apply(self.world_mut());
}
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: WinitUserEvent) {
self.user_event_received = true;
match event {
WinitUserEvent::WakeUp => {
self.redraw_requested = true;
}
WinitUserEvent::WindowAdded => {
let mut create_window =
SystemState::<CreateWindowParams>::from_world(self.world_mut());
create_windows(event_loop, create_window.get_mut(self.world_mut()));
create_window.apply(self.world_mut());
}
}
}
fn window_event(
&mut self,
_event_loop: &ActiveEventLoop,
window_id: WindowId,
event: WindowEvent,
) {
self.window_event_received = true;
#[cfg_attr(
not(target_os = "windows"),
expect(unused_mut, reason = "only needs to be mut on windows for now")
)]
let mut manual_run_redraw_requested = false;
WINIT_WINDOWS.with_borrow(|winit_windows| {
ACCESS_KIT_ADAPTERS.with_borrow_mut(|access_kit_adapters| {
let (
mut window_resized,
mut window_backend_scale_factor_changed,
mut window_scale_factor_changed,
mut windows,
) = self
.message_writer_system_state
.get_mut(self.app.world_mut());
let Some(window) = winit_windows.get_window_entity(window_id) else {
warn!("Skipped event {event:?} for unknown winit Window Id {window_id:?}");
return;
};
let Ok((mut win, _, mut pressed_keys)) = windows.get_mut(window) else {
warn!(
"Window {window:?} is missing `Window` component, skipping event {event:?}"
);
return;
};
// Store a copy of the event to send to a MessageWriter later.
self.raw_winit_events.push(RawWinitWindowEvent {
window_id,
event: event.clone(),
});
// Allow AccessKit to respond to `WindowEvent`s before they reach
// the engine.
if let Some(adapter) = access_kit_adapters.get_mut(&window)
&& let Some(winit_window) = winit_windows.get_window(window)
{
adapter.process_event(winit_window, &event);
}
match event {
WindowEvent::Resized(size) => {
react_to_resize(window, &mut win, size, &mut window_resized);
}
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
react_to_scale_factor_change(
window,
&mut win,
scale_factor,
&mut window_backend_scale_factor_changed,
&mut window_scale_factor_changed,
);
}
WindowEvent::CloseRequested => self
.bevy_window_events
.send(WindowCloseRequested { window }),
WindowEvent::KeyboardInput {
ref event,
// On some platforms, winit sends "synthetic" key press events when the window
// gains or loses focus. These are not implemented on every platform, so we ignore
// winit's synthetic key pressed and implement the same mechanism ourselves.
// (See the `WinitWindowPressedKeys` component)
is_synthetic: false,
..
} => {
let keyboard_input = converters::convert_keyboard_input(event, window);
if event.state.is_pressed() {
pressed_keys.0.insert(
keyboard_input.key_code,
keyboard_input.logical_key.clone(),
);
} else {
pressed_keys.0.remove(&keyboard_input.key_code);
}
self.bevy_window_events.send(keyboard_input);
}
WindowEvent::CursorMoved { position, .. } => {
let physical_position = DVec2::new(position.x, position.y);
let last_position = win.physical_cursor_position();
let delta = last_position.map(|last_pos| {
(physical_position.as_vec2() - last_pos) / win.resolution.scale_factor()
});
win.set_physical_cursor_position(Some(physical_position));
let position =
(physical_position / win.resolution.scale_factor() as f64).as_vec2();
self.bevy_window_events.send(CursorMoved {
window,
position,
delta,
});
}
WindowEvent::CursorEntered { .. } => {
self.bevy_window_events.send(CursorEntered { window });
}
WindowEvent::CursorLeft { .. } => {
win.set_physical_cursor_position(None);
self.bevy_window_events.send(CursorLeft { window });
}
WindowEvent::MouseInput { state, button, .. } => {
self.bevy_window_events.send(MouseButtonInput {
button: converters::convert_mouse_button(button),
state: converters::convert_element_state(state),
window,
});
}
WindowEvent::PinchGesture { delta, .. } => {
self.bevy_window_events.send(PinchGesture(delta as f32));
}
WindowEvent::RotationGesture { delta, .. } => {
self.bevy_window_events.send(RotationGesture(delta));
}
WindowEvent::DoubleTapGesture { .. } => {
self.bevy_window_events.send(DoubleTapGesture);
}
WindowEvent::PanGesture { delta, .. } => {
self.bevy_window_events.send(PanGesture(Vec2 {
x: delta.x,
y: delta.y,
}));
}
WindowEvent::MouseWheel { delta, .. } => match delta {
event::MouseScrollDelta::LineDelta(x, y) => {
self.bevy_window_events.send(MouseWheel {
unit: MouseScrollUnit::Line,
x,
y,
window,
});
}
event::MouseScrollDelta::PixelDelta(p) => {
self.bevy_window_events.send(MouseWheel {
unit: MouseScrollUnit::Pixel,
x: p.x as f32,
y: p.y as f32,
window,
});
}
},
WindowEvent::Touch(touch) => {
let location = touch
.location
.to_logical(win.resolution.scale_factor() as f64);
self.bevy_window_events
.send(converters::convert_touch_input(touch, location, window));
}
WindowEvent::Focused(focused) => {
win.focused = focused;
self.bevy_window_events
.send(WindowFocused { window, focused });
}
WindowEvent::Occluded(occluded) => {
self.bevy_window_events
.send(WindowOccluded { window, occluded });
}
WindowEvent::DroppedFile(path_buf) => {
self.bevy_window_events
.send(FileDragAndDrop::DroppedFile { window, path_buf });
}
WindowEvent::HoveredFile(path_buf) => {
self.bevy_window_events
.send(FileDragAndDrop::HoveredFile { window, path_buf });
}
WindowEvent::HoveredFileCancelled => {
self.bevy_window_events
.send(FileDragAndDrop::HoveredFileCanceled { window });
}
WindowEvent::Moved(position) => {
let position = ivec2(position.x, position.y);
win.position.set(position);
self.bevy_window_events
.send(WindowMoved { window, position });
}
WindowEvent::Ime(event) => match event {
event::Ime::Preedit(value, cursor) => {
self.bevy_window_events.send(Ime::Preedit {
window,
value,
cursor,
});
}
event::Ime::Commit(value) => {
self.bevy_window_events.send(Ime::Commit { window, value });
}
event::Ime::Enabled => {
self.bevy_window_events.send(Ime::Enabled { window });
}
event::Ime::Disabled => {
self.bevy_window_events.send(Ime::Disabled { window });
}
},
WindowEvent::ThemeChanged(theme) => {
self.bevy_window_events.send(WindowThemeChanged {
window,
theme: converters::convert_winit_theme(theme),
});
}
WindowEvent::Destroyed => {
self.bevy_window_events.send(WindowDestroyed { window });
}
WindowEvent::RedrawRequested => {
self.ran_update_since_last_redraw = false;
// https://github.com/bevyengine/bevy/issues/17488
#[cfg(target_os = "windows")]
{
// Have the startup behavior run in about_to_wait, which prevents issues with
// invisible window creation. https://github.com/bevyengine/bevy/issues/18027
if self.startup_forced_updates == 0 {
manual_run_redraw_requested = true;
}
}
}
_ => {}
}
let mut windows = self.world_mut().query::<(&mut Window, &mut CachedWindow)>();
if let Ok((window_component, mut cache)) = windows.get_mut(self.world_mut(), window)
&& window_component.is_changed()
{
**cache = window_component.clone();
}
});
});
if manual_run_redraw_requested {
self.redraw_requested(_event_loop);
}
}
fn device_event(
&mut self,
_event_loop: &ActiveEventLoop,
_device_id: DeviceId,
event: DeviceEvent,
) {
self.device_event_received = true;
if let DeviceEvent::MouseMotion { delta: (x, y) } = event {
let delta = Vec2::new(x as f32, y as f32);
self.bevy_window_events.send(MouseMotion { delta });
}
}
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
let mut create_monitor = SystemState::<CreateMonitorParams>::from_world(self.world_mut());
create_monitors(event_loop, create_monitor.get_mut(self.world_mut()));
create_monitor.apply(self.world_mut());
// TODO: This is a workaround for https://github.com/bevyengine/bevy/issues/17488
// while preserving the iOS fix in https://github.com/bevyengine/bevy/pull/11245
// The monitor sync logic likely belongs in monitor event handlers and not here.
#[cfg(not(target_os = "windows"))]
self.redraw_requested(event_loop);
// Have the startup behavior run in about_to_wait, which prevents issues with
// invisible window creation. https://github.com/bevyengine/bevy/issues/18027
#[cfg(target_os = "windows")]
{
fn headless_or_all_invisible() -> bool {
WINIT_WINDOWS.with_borrow(|winit_windows| {
winit_windows
.windows
.iter()
.all(|(_, w)| !w.is_visible().unwrap_or(false))
})
}
if self.app_exit.is_none()
&& (self.startup_forced_updates > 0
|| matches!(self.update_mode, UpdateMode::Reactive { .. })
|| self.window_event_received
|| headless_or_all_invisible())
{
self.redraw_requested(event_loop);
}
}
}
fn suspended(&mut self, _event_loop: &ActiveEventLoop) {
// Mark the state as `WillSuspend`. This will let the schedule run one last time
// before actually suspending to let the application react
self.lifecycle = AppLifecycle::WillSuspend;
}
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
// Drop windows while event loop is still active, before TLS destruction.
// Prevents panic on macOS when exiting from exclusive fullscreen.
WINIT_WINDOWS.with(|ww| ww.borrow_mut().windows.clear());
let world = self.world_mut();
world.clear_all();
}
}
impl WinitAppRunnerState {
fn redraw_requested(&mut self, event_loop: &ActiveEventLoop) {
let mut redraw_message_cursor = MessageCursor::<RequestRedraw>::default();
let mut close_message_cursor = MessageCursor::<WindowCloseRequested>::default();
let mut focused_windows_state: SystemState<(Res<WinitSettings>, Query<(Entity, &Window)>)> =
SystemState::new(self.world_mut());
let (config, windows) = focused_windows_state.get(self.world());
let focused = windows.iter().any(|(_, window)| window.focused);
let mut update_mode = config.update_mode(focused);
let mut should_update = self.should_update(update_mode);
if self.startup_forced_updates > 0 {
self.startup_forced_updates -= 1;
// Ensure that an update is triggered on the first iterations for app initialization
should_update = true;
}
if self.lifecycle == AppLifecycle::WillSuspend {
self.lifecycle = AppLifecycle::Suspended;
// Trigger one last update to enter the suspended state
should_update = true;
self.ran_update_since_last_redraw = false;
#[cfg(target_os = "android")]
{
// Remove the `RawHandleWrapper` from the primary window.
// This will trigger the surface destruction.
let mut query = self
.world_mut()
.query_filtered::<Entity, With<PrimaryWindow>>();
let entity = query.single(&self.world()).unwrap();
self.world_mut()
.entity_mut(entity)
.remove::<RawHandleWrapper>();
}
}
if self.lifecycle == AppLifecycle::WillResume {
self.lifecycle = AppLifecycle::Running;
// Trigger the update to enter the running state
should_update = true;
// Trigger the next redraw to refresh the screen immediately
self.redraw_requested = true;
#[cfg(target_os = "android")]
{
// Get windows that are cached but without raw handles. Those window were already created, but got their
// handle wrapper removed when the app was suspended.
let mut query = self.world_mut()
.query_filtered::<(Entity, &Window, &CursorOptions), (With<CachedWindow>, Without<RawHandleWrapper>)>();
if let Ok((entity, window, cursor_options)) = query.single(&self.world()) {
let window = window.clone();
let cursor_options = cursor_options.clone();
WINIT_WINDOWS.with_borrow_mut(|winit_windows| {
ACCESS_KIT_ADAPTERS.with_borrow_mut(|adapters| {
let mut create_window =
SystemState::<CreateWindowParams>::from_world(self.world_mut());
let (.., mut handlers, accessibility_requested, monitors) =
create_window.get_mut(self.world_mut());
let winit_window = winit_windows.create_window(
event_loop,
entity,
&window,
&cursor_options,
adapters,
&mut handlers,
&accessibility_requested,
&monitors,
);
let wrapper = RawHandleWrapper::new(winit_window).unwrap();
self.world_mut().entity_mut(entity).insert(wrapper);
});
});
}
}
}
// Notifies a lifecycle change
if self.lifecycle != self.previous_lifecycle {
self.previous_lifecycle = self.lifecycle;
self.bevy_window_events.send(self.lifecycle);
}
// This is recorded before running app.update(), to run the next cycle after a correct timeout.
// If the cycle takes more than the wait timeout, it will be re-executed immediately.
let begin_frame_time = Instant::now();
if should_update {
let (_, windows) = focused_windows_state.get(self.world());
// If no windows exist, this will evaluate to `true`.
let all_invisible = windows.iter().all(|w| !w.1.visible);
// Not redrawing, but the timeout elapsed.
//
// Additional condition for Windows OS.
// If no windows are visible, redraw calls will never succeed, which results in no app update calls being performed.
// This is a temporary solution, full solution is mentioned here: https://github.com/bevyengine/bevy/issues/1343#issuecomment-770091684
if !self.ran_update_since_last_redraw || all_invisible {
self.run_app_update();
#[cfg(feature = "custom_cursor")]
self.update_cursors(event_loop);
#[cfg(not(feature = "custom_cursor"))]
self.update_cursors();
self.ran_update_since_last_redraw = true;
} else {
self.redraw_requested = true;
}
// Read RequestRedraw events that may have been sent during the update
if let Some(app_redraw_events) = self.world().get_resource::<Messages<RequestRedraw>>()
&& redraw_message_cursor
.read(app_redraw_events)
.last()
.is_some()
{
self.redraw_requested = true;
}
// Running the app may have produced WindowCloseRequested events that should be processed
if let Some(close_request_messages) = self
.world()
.get_resource::<Messages<WindowCloseRequested>>()
&& close_message_cursor
.read(close_request_messages)
.last()
.is_some()
{
self.redraw_requested = true;
}
// Running the app may have changed the WinitSettings resource, so we have to re-extract it.
let (config, windows) = focused_windows_state.get(self.world());
let focused = windows.iter().any(|(_, window)| window.focused);
update_mode = config.update_mode(focused);
}
// The update mode could have been changed, so we need to redraw and force an update
if update_mode != self.update_mode {
// Trigger the next redraw since we're changing the update mode
self.redraw_requested = true;
// Consider the wait as elapsed since it could have been cancelled by a user event
self.wait_elapsed = true;
// reset the scheduled start time
self.scheduled_tick_start = None;
self.update_mode = update_mode;
}
match update_mode {
UpdateMode::Continuous => {
// per winit's docs on [Window::is_visible](https://docs.rs/winit/latest/winit/window/struct.Window.html#method.is_visible),
// we cannot use the visibility to drive rendering on these platforms
// so we cannot discern whether to beneficially use `Poll` or not?
cfg_if::cfg_if! {
if #[cfg(not(any(
target_arch = "wasm32",
target_os = "android",
target_os = "ios",
all(target_os = "linux", any(feature = "x11", feature = "wayland"))
)))]
{
let visible = WINIT_WINDOWS.with_borrow(|winit_windows| {
winit_windows.windows.iter().any(|(_, w)| {
w.is_visible().unwrap_or(false)
})
});
event_loop.set_control_flow(if visible {
ControlFlow::Wait
} else {
ControlFlow::Poll
});
}
else {
event_loop.set_control_flow(ControlFlow::Wait);
}
}
// Trigger the next redraw to refresh the screen immediately if waiting
if let ControlFlow::Wait = event_loop.control_flow() {
self.redraw_requested = true;
}
}
UpdateMode::Reactive { wait, .. } => {
// Set the next timeout, starting from the instant we were scheduled to begin
if self.wait_elapsed {
self.redraw_requested = true;
let begin_instant = self.scheduled_tick_start.unwrap_or(begin_frame_time);
if let Some(next) = begin_instant.checked_add(wait) {
let now = Instant::now();
if next < now {
// request next redraw as soon as possible if we are already past the next scheduled frame start time
event_loop.set_control_flow(ControlFlow::Poll);
self.scheduled_tick_start = Some(now);
} else {
event_loop.set_control_flow(ControlFlow::WaitUntil(next));
self.scheduled_tick_start = Some(next);
}
}
}
}
}
if self.redraw_requested && self.lifecycle != AppLifecycle::Suspended {
WINIT_WINDOWS.with_borrow(|winit_windows| {
for window in winit_windows.windows.values() {
window.request_redraw();
}
});
self.redraw_requested = false;
}
if let Some(app_exit) = self.app.should_exit() {
self.app_exit = Some(app_exit);
event_loop.exit();
}
}
fn should_update(&self, update_mode: UpdateMode) -> bool {
let handle_event = match update_mode {
UpdateMode::Continuous => {
self.wait_elapsed
|| self.user_event_received
|| self.window_event_received
|| self.device_event_received
}
UpdateMode::Reactive {
react_to_device_events,
react_to_user_events,
react_to_window_events,
..
} => {
self.wait_elapsed
|| (react_to_device_events && self.device_event_received)
|| (react_to_user_events && self.user_event_received)
|| (react_to_window_events && self.window_event_received)
}
};
handle_event && self.lifecycle.is_active()
}
fn run_app_update(&mut self) {
self.reset_on_update();
self.forward_bevy_events();
if self.app.plugins_state() == PluginsState::Cleaned {
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_winit/src/converters.rs | crates/bevy_winit/src/converters.rs | //! Helpers for mapping between winit and bevy types
use bevy_ecs::entity::Entity;
use bevy_input::{
keyboard::{KeyCode, KeyboardInput, NativeKeyCode},
mouse::MouseButton,
touch::{ForceTouch, TouchInput, TouchPhase},
ButtonState,
};
use bevy_math::{CompassOctant, Vec2};
use bevy_window::SystemCursorIcon;
use bevy_window::{EnabledButtons, WindowLevel, WindowTheme};
use winit::keyboard::{Key, NamedKey, NativeKey};
#[cfg(target_os = "ios")]
use bevy_window::ScreenEdge;
/// Converts a [`winit::event::KeyEvent`] and a window [`Entity`] to a Bevy [`KeyboardInput`]
pub fn convert_keyboard_input(
keyboard_input: &winit::event::KeyEvent,
window: Entity,
) -> KeyboardInput {
KeyboardInput {
state: convert_element_state(keyboard_input.state),
key_code: convert_physical_key_code(keyboard_input.physical_key),
logical_key: convert_logical_key(&keyboard_input.logical_key),
text: keyboard_input.text.clone(),
repeat: keyboard_input.repeat,
window,
}
}
/// Converts a [`winit::event::ElementState`] to a Bevy [`ButtonState`]
pub fn convert_element_state(element_state: winit::event::ElementState) -> ButtonState {
match element_state {
winit::event::ElementState::Pressed => ButtonState::Pressed,
winit::event::ElementState::Released => ButtonState::Released,
}
}
/// Converts a [`winit::event::MouseButton`] to a Bevy [`MouseButton`]
pub fn convert_mouse_button(mouse_button: winit::event::MouseButton) -> MouseButton {
match mouse_button {
winit::event::MouseButton::Left => MouseButton::Left,
winit::event::MouseButton::Right => MouseButton::Right,
winit::event::MouseButton::Middle => MouseButton::Middle,
winit::event::MouseButton::Back => MouseButton::Back,
winit::event::MouseButton::Forward => MouseButton::Forward,
winit::event::MouseButton::Other(val) => MouseButton::Other(val),
}
}
/// Converts a [`winit::event::Touch`], [`winit::dpi::LogicalPosition<f64>`] and window [`Entity`] to a Bevy [`TouchInput`]
pub fn convert_touch_input(
touch_input: winit::event::Touch,
location: winit::dpi::LogicalPosition<f64>,
window_entity: Entity,
) -> TouchInput {
TouchInput {
phase: match touch_input.phase {
winit::event::TouchPhase::Started => TouchPhase::Started,
winit::event::TouchPhase::Moved => TouchPhase::Moved,
winit::event::TouchPhase::Ended => TouchPhase::Ended,
winit::event::TouchPhase::Cancelled => TouchPhase::Canceled,
},
position: Vec2::new(location.x as f32, location.y as f32),
window: window_entity,
force: touch_input.force.map(|f| match f {
winit::event::Force::Calibrated {
force,
max_possible_force,
altitude_angle,
} => ForceTouch::Calibrated {
force,
max_possible_force,
altitude_angle,
},
winit::event::Force::Normalized(x) => ForceTouch::Normalized(x),
}),
id: touch_input.id,
}
}
/// Converts a [`winit::keyboard::NativeKeyCode`] to a Bevy [`NativeKeyCode`]
pub fn convert_physical_native_key_code(
native_key_code: winit::keyboard::NativeKeyCode,
) -> NativeKeyCode {
match native_key_code {
winit::keyboard::NativeKeyCode::Unidentified => NativeKeyCode::Unidentified,
winit::keyboard::NativeKeyCode::Android(scan_code) => NativeKeyCode::Android(scan_code),
winit::keyboard::NativeKeyCode::MacOS(scan_code) => NativeKeyCode::MacOS(scan_code),
winit::keyboard::NativeKeyCode::Windows(scan_code) => NativeKeyCode::Windows(scan_code),
winit::keyboard::NativeKeyCode::Xkb(key_code) => NativeKeyCode::Xkb(key_code),
}
}
/// Converts a [`winit::keyboard::PhysicalKey`] to a Bevy [`KeyCode`]
pub fn convert_physical_key_code(virtual_key_code: winit::keyboard::PhysicalKey) -> KeyCode {
match virtual_key_code {
winit::keyboard::PhysicalKey::Unidentified(native_key_code) => {
KeyCode::Unidentified(convert_physical_native_key_code(native_key_code))
}
winit::keyboard::PhysicalKey::Code(code) => match code {
winit::keyboard::KeyCode::Backquote => KeyCode::Backquote,
winit::keyboard::KeyCode::Backslash => KeyCode::Backslash,
winit::keyboard::KeyCode::BracketLeft => KeyCode::BracketLeft,
winit::keyboard::KeyCode::BracketRight => KeyCode::BracketRight,
winit::keyboard::KeyCode::Comma => KeyCode::Comma,
winit::keyboard::KeyCode::Digit0 => KeyCode::Digit0,
winit::keyboard::KeyCode::Digit1 => KeyCode::Digit1,
winit::keyboard::KeyCode::Digit2 => KeyCode::Digit2,
winit::keyboard::KeyCode::Digit3 => KeyCode::Digit3,
winit::keyboard::KeyCode::Digit4 => KeyCode::Digit4,
winit::keyboard::KeyCode::Digit5 => KeyCode::Digit5,
winit::keyboard::KeyCode::Digit6 => KeyCode::Digit6,
winit::keyboard::KeyCode::Digit7 => KeyCode::Digit7,
winit::keyboard::KeyCode::Digit8 => KeyCode::Digit8,
winit::keyboard::KeyCode::Digit9 => KeyCode::Digit9,
winit::keyboard::KeyCode::Equal => KeyCode::Equal,
winit::keyboard::KeyCode::IntlBackslash => KeyCode::IntlBackslash,
winit::keyboard::KeyCode::IntlRo => KeyCode::IntlRo,
winit::keyboard::KeyCode::IntlYen => KeyCode::IntlYen,
winit::keyboard::KeyCode::KeyA => KeyCode::KeyA,
winit::keyboard::KeyCode::KeyB => KeyCode::KeyB,
winit::keyboard::KeyCode::KeyC => KeyCode::KeyC,
winit::keyboard::KeyCode::KeyD => KeyCode::KeyD,
winit::keyboard::KeyCode::KeyE => KeyCode::KeyE,
winit::keyboard::KeyCode::KeyF => KeyCode::KeyF,
winit::keyboard::KeyCode::KeyG => KeyCode::KeyG,
winit::keyboard::KeyCode::KeyH => KeyCode::KeyH,
winit::keyboard::KeyCode::KeyI => KeyCode::KeyI,
winit::keyboard::KeyCode::KeyJ => KeyCode::KeyJ,
winit::keyboard::KeyCode::KeyK => KeyCode::KeyK,
winit::keyboard::KeyCode::KeyL => KeyCode::KeyL,
winit::keyboard::KeyCode::KeyM => KeyCode::KeyM,
winit::keyboard::KeyCode::KeyN => KeyCode::KeyN,
winit::keyboard::KeyCode::KeyO => KeyCode::KeyO,
winit::keyboard::KeyCode::KeyP => KeyCode::KeyP,
winit::keyboard::KeyCode::KeyQ => KeyCode::KeyQ,
winit::keyboard::KeyCode::KeyR => KeyCode::KeyR,
winit::keyboard::KeyCode::KeyS => KeyCode::KeyS,
winit::keyboard::KeyCode::KeyT => KeyCode::KeyT,
winit::keyboard::KeyCode::KeyU => KeyCode::KeyU,
winit::keyboard::KeyCode::KeyV => KeyCode::KeyV,
winit::keyboard::KeyCode::KeyW => KeyCode::KeyW,
winit::keyboard::KeyCode::KeyX => KeyCode::KeyX,
winit::keyboard::KeyCode::KeyY => KeyCode::KeyY,
winit::keyboard::KeyCode::KeyZ => KeyCode::KeyZ,
winit::keyboard::KeyCode::Minus => KeyCode::Minus,
winit::keyboard::KeyCode::Period => KeyCode::Period,
winit::keyboard::KeyCode::Quote => KeyCode::Quote,
winit::keyboard::KeyCode::Semicolon => KeyCode::Semicolon,
winit::keyboard::KeyCode::Slash => KeyCode::Slash,
winit::keyboard::KeyCode::AltLeft => KeyCode::AltLeft,
winit::keyboard::KeyCode::AltRight => KeyCode::AltRight,
winit::keyboard::KeyCode::Backspace => KeyCode::Backspace,
winit::keyboard::KeyCode::CapsLock => KeyCode::CapsLock,
winit::keyboard::KeyCode::ContextMenu => KeyCode::ContextMenu,
winit::keyboard::KeyCode::ControlLeft => KeyCode::ControlLeft,
winit::keyboard::KeyCode::ControlRight => KeyCode::ControlRight,
winit::keyboard::KeyCode::Enter => KeyCode::Enter,
winit::keyboard::KeyCode::SuperLeft => KeyCode::SuperLeft,
winit::keyboard::KeyCode::SuperRight => KeyCode::SuperRight,
winit::keyboard::KeyCode::ShiftLeft => KeyCode::ShiftLeft,
winit::keyboard::KeyCode::ShiftRight => KeyCode::ShiftRight,
winit::keyboard::KeyCode::Space => KeyCode::Space,
winit::keyboard::KeyCode::Tab => KeyCode::Tab,
winit::keyboard::KeyCode::Convert => KeyCode::Convert,
winit::keyboard::KeyCode::KanaMode => KeyCode::KanaMode,
winit::keyboard::KeyCode::Lang1 => KeyCode::Lang1,
winit::keyboard::KeyCode::Lang2 => KeyCode::Lang2,
winit::keyboard::KeyCode::Lang3 => KeyCode::Lang3,
winit::keyboard::KeyCode::Lang4 => KeyCode::Lang4,
winit::keyboard::KeyCode::Lang5 => KeyCode::Lang5,
winit::keyboard::KeyCode::NonConvert => KeyCode::NonConvert,
winit::keyboard::KeyCode::Delete => KeyCode::Delete,
winit::keyboard::KeyCode::End => KeyCode::End,
winit::keyboard::KeyCode::Help => KeyCode::Help,
winit::keyboard::KeyCode::Home => KeyCode::Home,
winit::keyboard::KeyCode::Insert => KeyCode::Insert,
winit::keyboard::KeyCode::PageDown => KeyCode::PageDown,
winit::keyboard::KeyCode::PageUp => KeyCode::PageUp,
winit::keyboard::KeyCode::ArrowDown => KeyCode::ArrowDown,
winit::keyboard::KeyCode::ArrowLeft => KeyCode::ArrowLeft,
winit::keyboard::KeyCode::ArrowRight => KeyCode::ArrowRight,
winit::keyboard::KeyCode::ArrowUp => KeyCode::ArrowUp,
winit::keyboard::KeyCode::NumLock => KeyCode::NumLock,
winit::keyboard::KeyCode::Numpad0 => KeyCode::Numpad0,
winit::keyboard::KeyCode::Numpad1 => KeyCode::Numpad1,
winit::keyboard::KeyCode::Numpad2 => KeyCode::Numpad2,
winit::keyboard::KeyCode::Numpad3 => KeyCode::Numpad3,
winit::keyboard::KeyCode::Numpad4 => KeyCode::Numpad4,
winit::keyboard::KeyCode::Numpad5 => KeyCode::Numpad5,
winit::keyboard::KeyCode::Numpad6 => KeyCode::Numpad6,
winit::keyboard::KeyCode::Numpad7 => KeyCode::Numpad7,
winit::keyboard::KeyCode::Numpad8 => KeyCode::Numpad8,
winit::keyboard::KeyCode::Numpad9 => KeyCode::Numpad9,
winit::keyboard::KeyCode::NumpadAdd => KeyCode::NumpadAdd,
winit::keyboard::KeyCode::NumpadBackspace => KeyCode::NumpadBackspace,
winit::keyboard::KeyCode::NumpadClear => KeyCode::NumpadClear,
winit::keyboard::KeyCode::NumpadClearEntry => KeyCode::NumpadClearEntry,
winit::keyboard::KeyCode::NumpadComma => KeyCode::NumpadComma,
winit::keyboard::KeyCode::NumpadDecimal => KeyCode::NumpadDecimal,
winit::keyboard::KeyCode::NumpadDivide => KeyCode::NumpadDivide,
winit::keyboard::KeyCode::NumpadEnter => KeyCode::NumpadEnter,
winit::keyboard::KeyCode::NumpadEqual => KeyCode::NumpadEqual,
winit::keyboard::KeyCode::NumpadHash => KeyCode::NumpadHash,
winit::keyboard::KeyCode::NumpadMemoryAdd => KeyCode::NumpadMemoryAdd,
winit::keyboard::KeyCode::NumpadMemoryClear => KeyCode::NumpadMemoryClear,
winit::keyboard::KeyCode::NumpadMemoryRecall => KeyCode::NumpadMemoryRecall,
winit::keyboard::KeyCode::NumpadMemoryStore => KeyCode::NumpadMemoryStore,
winit::keyboard::KeyCode::NumpadMemorySubtract => KeyCode::NumpadMemorySubtract,
winit::keyboard::KeyCode::NumpadMultiply => KeyCode::NumpadMultiply,
winit::keyboard::KeyCode::NumpadParenLeft => KeyCode::NumpadParenLeft,
winit::keyboard::KeyCode::NumpadParenRight => KeyCode::NumpadParenRight,
winit::keyboard::KeyCode::NumpadStar => KeyCode::NumpadStar,
winit::keyboard::KeyCode::NumpadSubtract => KeyCode::NumpadSubtract,
winit::keyboard::KeyCode::Escape => KeyCode::Escape,
winit::keyboard::KeyCode::Fn => KeyCode::Fn,
winit::keyboard::KeyCode::FnLock => KeyCode::FnLock,
winit::keyboard::KeyCode::PrintScreen => KeyCode::PrintScreen,
winit::keyboard::KeyCode::ScrollLock => KeyCode::ScrollLock,
winit::keyboard::KeyCode::Pause => KeyCode::Pause,
winit::keyboard::KeyCode::BrowserBack => KeyCode::BrowserBack,
winit::keyboard::KeyCode::BrowserFavorites => KeyCode::BrowserFavorites,
winit::keyboard::KeyCode::BrowserForward => KeyCode::BrowserForward,
winit::keyboard::KeyCode::BrowserHome => KeyCode::BrowserHome,
winit::keyboard::KeyCode::BrowserRefresh => KeyCode::BrowserRefresh,
winit::keyboard::KeyCode::BrowserSearch => KeyCode::BrowserSearch,
winit::keyboard::KeyCode::BrowserStop => KeyCode::BrowserStop,
winit::keyboard::KeyCode::Eject => KeyCode::Eject,
winit::keyboard::KeyCode::LaunchApp1 => KeyCode::LaunchApp1,
winit::keyboard::KeyCode::LaunchApp2 => KeyCode::LaunchApp2,
winit::keyboard::KeyCode::LaunchMail => KeyCode::LaunchMail,
winit::keyboard::KeyCode::MediaPlayPause => KeyCode::MediaPlayPause,
winit::keyboard::KeyCode::MediaSelect => KeyCode::MediaSelect,
winit::keyboard::KeyCode::MediaStop => KeyCode::MediaStop,
winit::keyboard::KeyCode::MediaTrackNext => KeyCode::MediaTrackNext,
winit::keyboard::KeyCode::MediaTrackPrevious => KeyCode::MediaTrackPrevious,
winit::keyboard::KeyCode::Power => KeyCode::Power,
winit::keyboard::KeyCode::Sleep => KeyCode::Sleep,
winit::keyboard::KeyCode::AudioVolumeDown => KeyCode::AudioVolumeDown,
winit::keyboard::KeyCode::AudioVolumeMute => KeyCode::AudioVolumeMute,
winit::keyboard::KeyCode::AudioVolumeUp => KeyCode::AudioVolumeUp,
winit::keyboard::KeyCode::WakeUp => KeyCode::WakeUp,
winit::keyboard::KeyCode::Meta => KeyCode::Meta,
winit::keyboard::KeyCode::Hyper => KeyCode::Hyper,
winit::keyboard::KeyCode::Turbo => KeyCode::Turbo,
winit::keyboard::KeyCode::Abort => KeyCode::Abort,
winit::keyboard::KeyCode::Resume => KeyCode::Resume,
winit::keyboard::KeyCode::Suspend => KeyCode::Suspend,
winit::keyboard::KeyCode::Again => KeyCode::Again,
winit::keyboard::KeyCode::Copy => KeyCode::Copy,
winit::keyboard::KeyCode::Cut => KeyCode::Cut,
winit::keyboard::KeyCode::Find => KeyCode::Find,
winit::keyboard::KeyCode::Open => KeyCode::Open,
winit::keyboard::KeyCode::Paste => KeyCode::Paste,
winit::keyboard::KeyCode::Props => KeyCode::Props,
winit::keyboard::KeyCode::Select => KeyCode::Select,
winit::keyboard::KeyCode::Undo => KeyCode::Undo,
winit::keyboard::KeyCode::Hiragana => KeyCode::Hiragana,
winit::keyboard::KeyCode::Katakana => KeyCode::Katakana,
winit::keyboard::KeyCode::F1 => KeyCode::F1,
winit::keyboard::KeyCode::F2 => KeyCode::F2,
winit::keyboard::KeyCode::F3 => KeyCode::F3,
winit::keyboard::KeyCode::F4 => KeyCode::F4,
winit::keyboard::KeyCode::F5 => KeyCode::F5,
winit::keyboard::KeyCode::F6 => KeyCode::F6,
winit::keyboard::KeyCode::F7 => KeyCode::F7,
winit::keyboard::KeyCode::F8 => KeyCode::F8,
winit::keyboard::KeyCode::F9 => KeyCode::F9,
winit::keyboard::KeyCode::F10 => KeyCode::F10,
winit::keyboard::KeyCode::F11 => KeyCode::F11,
winit::keyboard::KeyCode::F12 => KeyCode::F12,
winit::keyboard::KeyCode::F13 => KeyCode::F13,
winit::keyboard::KeyCode::F14 => KeyCode::F14,
winit::keyboard::KeyCode::F15 => KeyCode::F15,
winit::keyboard::KeyCode::F16 => KeyCode::F16,
winit::keyboard::KeyCode::F17 => KeyCode::F17,
winit::keyboard::KeyCode::F18 => KeyCode::F18,
winit::keyboard::KeyCode::F19 => KeyCode::F19,
winit::keyboard::KeyCode::F20 => KeyCode::F20,
winit::keyboard::KeyCode::F21 => KeyCode::F21,
winit::keyboard::KeyCode::F22 => KeyCode::F22,
winit::keyboard::KeyCode::F23 => KeyCode::F23,
winit::keyboard::KeyCode::F24 => KeyCode::F24,
winit::keyboard::KeyCode::F25 => KeyCode::F25,
winit::keyboard::KeyCode::F26 => KeyCode::F26,
winit::keyboard::KeyCode::F27 => KeyCode::F27,
winit::keyboard::KeyCode::F28 => KeyCode::F28,
winit::keyboard::KeyCode::F29 => KeyCode::F29,
winit::keyboard::KeyCode::F30 => KeyCode::F30,
winit::keyboard::KeyCode::F31 => KeyCode::F31,
winit::keyboard::KeyCode::F32 => KeyCode::F32,
winit::keyboard::KeyCode::F33 => KeyCode::F33,
winit::keyboard::KeyCode::F34 => KeyCode::F34,
winit::keyboard::KeyCode::F35 => KeyCode::F35,
_ => KeyCode::Unidentified(NativeKeyCode::Unidentified),
},
}
}
///Converts a [`winit::keyboard::Key`] to a Bevy [`bevy_input::keyboard::Key`]
pub fn convert_logical_key(logical_key_code: &Key) -> bevy_input::keyboard::Key {
match logical_key_code {
Key::Character(s) => bevy_input::keyboard::Key::Character(s.clone()),
Key::Unidentified(nk) => bevy_input::keyboard::Key::Unidentified(convert_native_key(nk)),
Key::Dead(c) => bevy_input::keyboard::Key::Dead(c.to_owned()),
Key::Named(NamedKey::Alt) => bevy_input::keyboard::Key::Alt,
Key::Named(NamedKey::AltGraph) => bevy_input::keyboard::Key::AltGraph,
Key::Named(NamedKey::CapsLock) => bevy_input::keyboard::Key::CapsLock,
Key::Named(NamedKey::Control) => bevy_input::keyboard::Key::Control,
Key::Named(NamedKey::Fn) => bevy_input::keyboard::Key::Fn,
Key::Named(NamedKey::FnLock) => bevy_input::keyboard::Key::FnLock,
Key::Named(NamedKey::NumLock) => bevy_input::keyboard::Key::NumLock,
Key::Named(NamedKey::ScrollLock) => bevy_input::keyboard::Key::ScrollLock,
Key::Named(NamedKey::Shift) => bevy_input::keyboard::Key::Shift,
Key::Named(NamedKey::Symbol) => bevy_input::keyboard::Key::Symbol,
Key::Named(NamedKey::SymbolLock) => bevy_input::keyboard::Key::SymbolLock,
Key::Named(NamedKey::Meta) => bevy_input::keyboard::Key::Meta,
Key::Named(NamedKey::Hyper) => bevy_input::keyboard::Key::Hyper,
Key::Named(NamedKey::Super) => bevy_input::keyboard::Key::Super,
Key::Named(NamedKey::Enter) => bevy_input::keyboard::Key::Enter,
Key::Named(NamedKey::Tab) => bevy_input::keyboard::Key::Tab,
Key::Named(NamedKey::Space) => bevy_input::keyboard::Key::Space,
Key::Named(NamedKey::ArrowDown) => bevy_input::keyboard::Key::ArrowDown,
Key::Named(NamedKey::ArrowLeft) => bevy_input::keyboard::Key::ArrowLeft,
Key::Named(NamedKey::ArrowRight) => bevy_input::keyboard::Key::ArrowRight,
Key::Named(NamedKey::ArrowUp) => bevy_input::keyboard::Key::ArrowUp,
Key::Named(NamedKey::End) => bevy_input::keyboard::Key::End,
Key::Named(NamedKey::Home) => bevy_input::keyboard::Key::Home,
Key::Named(NamedKey::PageDown) => bevy_input::keyboard::Key::PageDown,
Key::Named(NamedKey::PageUp) => bevy_input::keyboard::Key::PageUp,
Key::Named(NamedKey::Backspace) => bevy_input::keyboard::Key::Backspace,
Key::Named(NamedKey::Clear) => bevy_input::keyboard::Key::Clear,
Key::Named(NamedKey::Copy) => bevy_input::keyboard::Key::Copy,
Key::Named(NamedKey::CrSel) => bevy_input::keyboard::Key::CrSel,
Key::Named(NamedKey::Cut) => bevy_input::keyboard::Key::Cut,
Key::Named(NamedKey::Delete) => bevy_input::keyboard::Key::Delete,
Key::Named(NamedKey::EraseEof) => bevy_input::keyboard::Key::EraseEof,
Key::Named(NamedKey::ExSel) => bevy_input::keyboard::Key::ExSel,
Key::Named(NamedKey::Insert) => bevy_input::keyboard::Key::Insert,
Key::Named(NamedKey::Paste) => bevy_input::keyboard::Key::Paste,
Key::Named(NamedKey::Redo) => bevy_input::keyboard::Key::Redo,
Key::Named(NamedKey::Undo) => bevy_input::keyboard::Key::Undo,
Key::Named(NamedKey::Accept) => bevy_input::keyboard::Key::Accept,
Key::Named(NamedKey::Again) => bevy_input::keyboard::Key::Again,
Key::Named(NamedKey::Attn) => bevy_input::keyboard::Key::Attn,
Key::Named(NamedKey::Cancel) => bevy_input::keyboard::Key::Cancel,
Key::Named(NamedKey::ContextMenu) => bevy_input::keyboard::Key::ContextMenu,
Key::Named(NamedKey::Escape) => bevy_input::keyboard::Key::Escape,
Key::Named(NamedKey::Execute) => bevy_input::keyboard::Key::Execute,
Key::Named(NamedKey::Find) => bevy_input::keyboard::Key::Find,
Key::Named(NamedKey::Help) => bevy_input::keyboard::Key::Help,
Key::Named(NamedKey::Pause) => bevy_input::keyboard::Key::Pause,
Key::Named(NamedKey::Play) => bevy_input::keyboard::Key::Play,
Key::Named(NamedKey::Props) => bevy_input::keyboard::Key::Props,
Key::Named(NamedKey::Select) => bevy_input::keyboard::Key::Select,
Key::Named(NamedKey::ZoomIn) => bevy_input::keyboard::Key::ZoomIn,
Key::Named(NamedKey::ZoomOut) => bevy_input::keyboard::Key::ZoomOut,
Key::Named(NamedKey::BrightnessDown) => bevy_input::keyboard::Key::BrightnessDown,
Key::Named(NamedKey::BrightnessUp) => bevy_input::keyboard::Key::BrightnessUp,
Key::Named(NamedKey::Eject) => bevy_input::keyboard::Key::Eject,
Key::Named(NamedKey::LogOff) => bevy_input::keyboard::Key::LogOff,
Key::Named(NamedKey::Power) => bevy_input::keyboard::Key::Power,
Key::Named(NamedKey::PowerOff) => bevy_input::keyboard::Key::PowerOff,
Key::Named(NamedKey::PrintScreen) => bevy_input::keyboard::Key::PrintScreen,
Key::Named(NamedKey::Hibernate) => bevy_input::keyboard::Key::Hibernate,
Key::Named(NamedKey::Standby) => bevy_input::keyboard::Key::Standby,
Key::Named(NamedKey::WakeUp) => bevy_input::keyboard::Key::WakeUp,
Key::Named(NamedKey::AllCandidates) => bevy_input::keyboard::Key::AllCandidates,
Key::Named(NamedKey::Alphanumeric) => bevy_input::keyboard::Key::Alphanumeric,
Key::Named(NamedKey::CodeInput) => bevy_input::keyboard::Key::CodeInput,
Key::Named(NamedKey::Compose) => bevy_input::keyboard::Key::Compose,
Key::Named(NamedKey::Convert) => bevy_input::keyboard::Key::Convert,
Key::Named(NamedKey::FinalMode) => bevy_input::keyboard::Key::FinalMode,
Key::Named(NamedKey::GroupFirst) => bevy_input::keyboard::Key::GroupFirst,
Key::Named(NamedKey::GroupLast) => bevy_input::keyboard::Key::GroupLast,
Key::Named(NamedKey::GroupNext) => bevy_input::keyboard::Key::GroupNext,
Key::Named(NamedKey::GroupPrevious) => bevy_input::keyboard::Key::GroupPrevious,
Key::Named(NamedKey::ModeChange) => bevy_input::keyboard::Key::ModeChange,
Key::Named(NamedKey::NextCandidate) => bevy_input::keyboard::Key::NextCandidate,
Key::Named(NamedKey::NonConvert) => bevy_input::keyboard::Key::NonConvert,
Key::Named(NamedKey::PreviousCandidate) => bevy_input::keyboard::Key::PreviousCandidate,
Key::Named(NamedKey::Process) => bevy_input::keyboard::Key::Process,
Key::Named(NamedKey::SingleCandidate) => bevy_input::keyboard::Key::SingleCandidate,
Key::Named(NamedKey::HangulMode) => bevy_input::keyboard::Key::HangulMode,
Key::Named(NamedKey::HanjaMode) => bevy_input::keyboard::Key::HanjaMode,
Key::Named(NamedKey::JunjaMode) => bevy_input::keyboard::Key::JunjaMode,
Key::Named(NamedKey::Eisu) => bevy_input::keyboard::Key::Eisu,
Key::Named(NamedKey::Hankaku) => bevy_input::keyboard::Key::Hankaku,
Key::Named(NamedKey::Hiragana) => bevy_input::keyboard::Key::Hiragana,
Key::Named(NamedKey::HiraganaKatakana) => bevy_input::keyboard::Key::HiraganaKatakana,
Key::Named(NamedKey::KanaMode) => bevy_input::keyboard::Key::KanaMode,
Key::Named(NamedKey::KanjiMode) => bevy_input::keyboard::Key::KanjiMode,
Key::Named(NamedKey::Katakana) => bevy_input::keyboard::Key::Katakana,
Key::Named(NamedKey::Romaji) => bevy_input::keyboard::Key::Romaji,
Key::Named(NamedKey::Zenkaku) => bevy_input::keyboard::Key::Zenkaku,
Key::Named(NamedKey::ZenkakuHankaku) => bevy_input::keyboard::Key::ZenkakuHankaku,
Key::Named(NamedKey::Soft1) => bevy_input::keyboard::Key::Soft1,
Key::Named(NamedKey::Soft2) => bevy_input::keyboard::Key::Soft2,
Key::Named(NamedKey::Soft3) => bevy_input::keyboard::Key::Soft3,
Key::Named(NamedKey::Soft4) => bevy_input::keyboard::Key::Soft4,
Key::Named(NamedKey::ChannelDown) => bevy_input::keyboard::Key::ChannelDown,
Key::Named(NamedKey::ChannelUp) => bevy_input::keyboard::Key::ChannelUp,
Key::Named(NamedKey::Close) => bevy_input::keyboard::Key::Close,
Key::Named(NamedKey::MailForward) => bevy_input::keyboard::Key::MailForward,
Key::Named(NamedKey::MailReply) => bevy_input::keyboard::Key::MailReply,
Key::Named(NamedKey::MailSend) => bevy_input::keyboard::Key::MailSend,
Key::Named(NamedKey::MediaClose) => bevy_input::keyboard::Key::MediaClose,
Key::Named(NamedKey::MediaFastForward) => bevy_input::keyboard::Key::MediaFastForward,
Key::Named(NamedKey::MediaPause) => bevy_input::keyboard::Key::MediaPause,
Key::Named(NamedKey::MediaPlay) => bevy_input::keyboard::Key::MediaPlay,
Key::Named(NamedKey::MediaPlayPause) => bevy_input::keyboard::Key::MediaPlayPause,
Key::Named(NamedKey::MediaRecord) => bevy_input::keyboard::Key::MediaRecord,
Key::Named(NamedKey::MediaRewind) => bevy_input::keyboard::Key::MediaRewind,
Key::Named(NamedKey::MediaStop) => bevy_input::keyboard::Key::MediaStop,
Key::Named(NamedKey::MediaTrackNext) => bevy_input::keyboard::Key::MediaTrackNext,
Key::Named(NamedKey::MediaTrackPrevious) => bevy_input::keyboard::Key::MediaTrackPrevious,
Key::Named(NamedKey::New) => bevy_input::keyboard::Key::New,
Key::Named(NamedKey::Open) => bevy_input::keyboard::Key::Open,
Key::Named(NamedKey::Print) => bevy_input::keyboard::Key::Print,
Key::Named(NamedKey::Save) => bevy_input::keyboard::Key::Save,
Key::Named(NamedKey::SpellCheck) => bevy_input::keyboard::Key::SpellCheck,
Key::Named(NamedKey::Key11) => bevy_input::keyboard::Key::Key11,
Key::Named(NamedKey::Key12) => bevy_input::keyboard::Key::Key12,
Key::Named(NamedKey::AudioBalanceLeft) => bevy_input::keyboard::Key::AudioBalanceLeft,
Key::Named(NamedKey::AudioBalanceRight) => bevy_input::keyboard::Key::AudioBalanceRight,
Key::Named(NamedKey::AudioBassBoostDown) => bevy_input::keyboard::Key::AudioBassBoostDown,
Key::Named(NamedKey::AudioBassBoostToggle) => {
bevy_input::keyboard::Key::AudioBassBoostToggle
}
Key::Named(NamedKey::AudioBassBoostUp) => bevy_input::keyboard::Key::AudioBassBoostUp,
Key::Named(NamedKey::AudioFaderFront) => bevy_input::keyboard::Key::AudioFaderFront,
Key::Named(NamedKey::AudioFaderRear) => bevy_input::keyboard::Key::AudioFaderRear,
Key::Named(NamedKey::AudioSurroundModeNext) => {
bevy_input::keyboard::Key::AudioSurroundModeNext
}
Key::Named(NamedKey::AudioTrebleDown) => bevy_input::keyboard::Key::AudioTrebleDown,
Key::Named(NamedKey::AudioTrebleUp) => bevy_input::keyboard::Key::AudioTrebleUp,
Key::Named(NamedKey::AudioVolumeDown) => bevy_input::keyboard::Key::AudioVolumeDown,
Key::Named(NamedKey::AudioVolumeUp) => bevy_input::keyboard::Key::AudioVolumeUp,
Key::Named(NamedKey::AudioVolumeMute) => bevy_input::keyboard::Key::AudioVolumeMute,
Key::Named(NamedKey::MicrophoneToggle) => bevy_input::keyboard::Key::MicrophoneToggle,
Key::Named(NamedKey::MicrophoneVolumeDown) => {
bevy_input::keyboard::Key::MicrophoneVolumeDown
}
Key::Named(NamedKey::MicrophoneVolumeUp) => bevy_input::keyboard::Key::MicrophoneVolumeUp,
Key::Named(NamedKey::MicrophoneVolumeMute) => {
bevy_input::keyboard::Key::MicrophoneVolumeMute
}
Key::Named(NamedKey::SpeechCorrectionList) => {
bevy_input::keyboard::Key::SpeechCorrectionList
}
Key::Named(NamedKey::SpeechInputToggle) => bevy_input::keyboard::Key::SpeechInputToggle,
Key::Named(NamedKey::LaunchApplication1) => bevy_input::keyboard::Key::LaunchApplication1,
Key::Named(NamedKey::LaunchApplication2) => bevy_input::keyboard::Key::LaunchApplication2,
Key::Named(NamedKey::LaunchCalendar) => bevy_input::keyboard::Key::LaunchCalendar,
Key::Named(NamedKey::LaunchContacts) => bevy_input::keyboard::Key::LaunchContacts,
Key::Named(NamedKey::LaunchMail) => bevy_input::keyboard::Key::LaunchMail,
Key::Named(NamedKey::LaunchMediaPlayer) => bevy_input::keyboard::Key::LaunchMediaPlayer,
Key::Named(NamedKey::LaunchMusicPlayer) => bevy_input::keyboard::Key::LaunchMusicPlayer,
Key::Named(NamedKey::LaunchPhone) => bevy_input::keyboard::Key::LaunchPhone,
Key::Named(NamedKey::LaunchScreenSaver) => bevy_input::keyboard::Key::LaunchScreenSaver,
Key::Named(NamedKey::LaunchSpreadsheet) => bevy_input::keyboard::Key::LaunchSpreadsheet,
Key::Named(NamedKey::LaunchWebBrowser) => bevy_input::keyboard::Key::LaunchWebBrowser,
Key::Named(NamedKey::LaunchWebCam) => bevy_input::keyboard::Key::LaunchWebCam,
Key::Named(NamedKey::LaunchWordProcessor) => bevy_input::keyboard::Key::LaunchWordProcessor,
Key::Named(NamedKey::BrowserBack) => bevy_input::keyboard::Key::BrowserBack,
Key::Named(NamedKey::BrowserFavorites) => bevy_input::keyboard::Key::BrowserFavorites,
Key::Named(NamedKey::BrowserForward) => bevy_input::keyboard::Key::BrowserForward,
Key::Named(NamedKey::BrowserHome) => bevy_input::keyboard::Key::BrowserHome,
Key::Named(NamedKey::BrowserRefresh) => bevy_input::keyboard::Key::BrowserRefresh,
Key::Named(NamedKey::BrowserSearch) => bevy_input::keyboard::Key::BrowserSearch,
Key::Named(NamedKey::BrowserStop) => bevy_input::keyboard::Key::BrowserStop,
Key::Named(NamedKey::AppSwitch) => bevy_input::keyboard::Key::AppSwitch,
Key::Named(NamedKey::Call) => bevy_input::keyboard::Key::Call,
Key::Named(NamedKey::Camera) => bevy_input::keyboard::Key::Camera,
Key::Named(NamedKey::CameraFocus) => bevy_input::keyboard::Key::CameraFocus,
Key::Named(NamedKey::EndCall) => bevy_input::keyboard::Key::EndCall,
Key::Named(NamedKey::GoBack) => bevy_input::keyboard::Key::GoBack,
Key::Named(NamedKey::GoHome) => bevy_input::keyboard::Key::GoHome,
Key::Named(NamedKey::HeadsetHook) => bevy_input::keyboard::Key::HeadsetHook,
Key::Named(NamedKey::LastNumberRedial) => bevy_input::keyboard::Key::LastNumberRedial,
Key::Named(NamedKey::Notification) => bevy_input::keyboard::Key::Notification,
Key::Named(NamedKey::MannerMode) => bevy_input::keyboard::Key::MannerMode,
Key::Named(NamedKey::VoiceDial) => bevy_input::keyboard::Key::VoiceDial,
Key::Named(NamedKey::TV) => bevy_input::keyboard::Key::TV,
Key::Named(NamedKey::TV3DMode) => bevy_input::keyboard::Key::TV3DMode,
Key::Named(NamedKey::TVAntennaCable) => bevy_input::keyboard::Key::TVAntennaCable,
Key::Named(NamedKey::TVAudioDescription) => bevy_input::keyboard::Key::TVAudioDescription,
Key::Named(NamedKey::TVAudioDescriptionMixDown) => {
bevy_input::keyboard::Key::TVAudioDescriptionMixDown
}
Key::Named(NamedKey::TVAudioDescriptionMixUp) => {
bevy_input::keyboard::Key::TVAudioDescriptionMixUp
}
Key::Named(NamedKey::TVContentsMenu) => bevy_input::keyboard::Key::TVContentsMenu,
Key::Named(NamedKey::TVDataService) => bevy_input::keyboard::Key::TVDataService,
Key::Named(NamedKey::TVInput) => bevy_input::keyboard::Key::TVInput,
Key::Named(NamedKey::TVInputComponent1) => bevy_input::keyboard::Key::TVInputComponent1,
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.