2020-11-28 00:39:59 +00:00
|
|
|
# Bevy Reflect
|
|
|
|
|
2023-10-15 00:52:31 +00:00
|
|
|
[![License](https://img.shields.io/badge/license-MIT%2FApache-blue.svg)](https://github.com/bevyengine/bevy#license)
|
|
|
|
[![Crates.io](https://img.shields.io/crates/v/bevy.svg)](https://crates.io/crates/bevy_reflect)
|
|
|
|
[![Downloads](https://img.shields.io/crates/d/bevy_reflect.svg)](https://crates.io/crates/bevy_reflect)
|
|
|
|
[![Docs](https://docs.rs/bevy_reflect/badge.svg)](https://docs.rs/bevy_reflect/latest/bevy_reflect/)
|
|
|
|
[![Discord](https://img.shields.io/discord/691052431525675048.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/bevy)
|
|
|
|
|
2020-11-28 00:39:59 +00:00
|
|
|
This crate enables you to dynamically interact with Rust types:
|
|
|
|
|
|
|
|
* Derive the Reflect traits
|
|
|
|
* Interact with fields using their names (for named structs) or indices (for tuple structs)
|
|
|
|
* "Patch" your types with new values
|
|
|
|
* Look up nested fields using "path strings"
|
|
|
|
* Iterate over struct fields
|
|
|
|
* Automatically serialize and deserialize via Serde (without explicit serde impls)
|
2021-02-22 04:50:05 +00:00
|
|
|
* Trait "reflection"
|
2020-11-28 00:39:59 +00:00
|
|
|
|
|
|
|
## Features
|
|
|
|
|
|
|
|
### Derive the Reflect traits
|
|
|
|
|
2021-12-18 22:59:55 +00:00
|
|
|
```rust ignore
|
2020-11-28 00:39:59 +00:00
|
|
|
// this will automatically implement the Reflect trait and the Struct trait (because the type is a struct)
|
|
|
|
#[derive(Reflect)]
|
|
|
|
struct Foo {
|
|
|
|
a: u32,
|
2020-12-01 02:12:09 +00:00
|
|
|
b: Bar,
|
2020-11-28 00:39:59 +00:00
|
|
|
c: Vec<i32>,
|
2022-06-29 02:48:47 +00:00
|
|
|
d: Vec<Baz>,
|
2020-11-28 00:39:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// this will automatically implement the Reflect trait and the TupleStruct trait (because the type is a tuple struct)
|
|
|
|
#[derive(Reflect)]
|
|
|
|
struct Bar(String);
|
|
|
|
|
bevy_reflect: `FromReflect` Ergonomics Implementation (#6056)
# Objective
**This implementation is based on
https://github.com/bevyengine/rfcs/pull/59.**
---
Resolves #4597
Full details and motivation can be found in the RFC, but here's a brief
summary.
`FromReflect` is a very powerful and important trait within the
reflection API. It allows Dynamic types (e.g., `DynamicList`, etc.) to
be formed into Real ones (e.g., `Vec<i32>`, etc.).
This mainly comes into play concerning deserialization, where the
reflection deserializers both return a `Box<dyn Reflect>` that almost
always contain one of these Dynamic representations of a Real type. To
convert this to our Real type, we need to use `FromReflect`.
It also sneaks up in other ways. For example, it's a required bound for
`T` in `Vec<T>` so that `Vec<T>` as a whole can be made `FromReflect`.
It's also required by all fields of an enum as it's used as part of the
`Reflect::apply` implementation.
So in other words, much like `GetTypeRegistration` and `Typed`, it is
very much a core reflection trait.
The problem is that it is not currently treated like a core trait and is
not automatically derived alongside `Reflect`. This makes using it a bit
cumbersome and easy to forget.
## Solution
Automatically derive `FromReflect` when deriving `Reflect`.
Users can then choose to opt-out if needed using the
`#[reflect(from_reflect = false)]` attribute.
```rust
#[derive(Reflect)]
struct Foo;
#[derive(Reflect)]
#[reflect(from_reflect = false)]
struct Bar;
fn test<T: FromReflect>(value: T) {}
test(Foo); // <-- OK
test(Bar); // <-- Panic! Bar does not implement trait `FromReflect`
```
#### `ReflectFromReflect`
This PR also automatically adds the `ReflectFromReflect` (introduced in
#6245) registration to the derived `GetTypeRegistration` impl— if the
type hasn't opted out of `FromReflect` of course.
<details>
<summary><h4>Improved Deserialization</h4></summary>
> **Warning**
> This section includes changes that have since been descoped from this
PR. They will likely be implemented again in a followup PR. I am mainly
leaving these details in for archival purposes, as well as for reference
when implementing this logic again.
And since we can do all the above, we might as well improve
deserialization. We can now choose to deserialize into a Dynamic type or
automatically convert it using `FromReflect` under the hood.
`[Un]TypedReflectDeserializer::new` will now perform the conversion and
return the `Box`'d Real type.
`[Un]TypedReflectDeserializer::new_dynamic` will work like what we have
now and simply return the `Box`'d Dynamic type.
```rust
// Returns the Real type
let reflect_deserializer = UntypedReflectDeserializer::new(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input)?;
let output: SomeStruct = reflect_deserializer.deserialize(&mut deserializer)?.take()?;
// Returns the Dynamic type
let reflect_deserializer = UntypedReflectDeserializer::new_dynamic(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input)?;
let output: DynamicStruct = reflect_deserializer.deserialize(&mut deserializer)?.take()?;
```
</details>
---
## Changelog
* `FromReflect` is now automatically derived within the `Reflect` derive
macro
* This includes auto-registering `ReflectFromReflect` in the derived
`GetTypeRegistration` impl
* ~~Renamed `TypedReflectDeserializer::new` and
`UntypedReflectDeserializer::new` to
`TypedReflectDeserializer::new_dynamic` and
`UntypedReflectDeserializer::new_dynamic`, respectively~~ **Descoped**
* ~~Changed `TypedReflectDeserializer::new` and
`UntypedReflectDeserializer::new` to automatically convert the
deserialized output using `FromReflect`~~ **Descoped**
## Migration Guide
* `FromReflect` is now automatically derived within the `Reflect` derive
macro. Items with both derives will need to remove the `FromReflect`
one.
```rust
// OLD
#[derive(Reflect, FromReflect)]
struct Foo;
// NEW
#[derive(Reflect)]
struct Foo;
```
If using a manual implementation of `FromReflect` and the `Reflect`
derive, users will need to opt-out of the automatic implementation.
```rust
// OLD
#[derive(Reflect)]
struct Foo;
impl FromReflect for Foo {/* ... */}
// NEW
#[derive(Reflect)]
#[reflect(from_reflect = false)]
struct Foo;
impl FromReflect for Foo {/* ... */}
```
<details>
<summary><h4>Removed Migrations</h4></summary>
> **Warning**
> This section includes changes that have since been descoped from this
PR. They will likely be implemented again in a followup PR. I am mainly
leaving these details in for archival purposes, as well as for reference
when implementing this logic again.
* The reflect deserializers now perform a `FromReflect` conversion
internally. The expected output of `TypedReflectDeserializer::new` and
`UntypedReflectDeserializer::new` is no longer a Dynamic (e.g.,
`DynamicList`), but its Real counterpart (e.g., `Vec<i32>`).
```rust
let reflect_deserializer =
UntypedReflectDeserializer::new_dynamic(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input)?;
// OLD
let output: DynamicStruct = reflect_deserializer.deserialize(&mut
deserializer)?.take()?;
// NEW
let output: SomeStruct = reflect_deserializer.deserialize(&mut
deserializer)?.take()?;
```
Alternatively, if this behavior isn't desired, use the
`TypedReflectDeserializer::new_dynamic` and
`UntypedReflectDeserializer::new_dynamic` methods instead:
```rust
// OLD
let reflect_deserializer = UntypedReflectDeserializer::new(®istry);
// NEW
let reflect_deserializer =
UntypedReflectDeserializer::new_dynamic(®istry);
```
</details>
---------
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-06-29 01:31:34 +00:00
|
|
|
#[derive(Reflect)]
|
2020-11-28 00:39:59 +00:00
|
|
|
struct Baz {
|
|
|
|
value: f32,
|
2020-12-01 02:12:09 +00:00
|
|
|
}
|
2020-11-28 00:39:59 +00:00
|
|
|
|
|
|
|
// We will use this value to illustrate `bevy_reflect` features
|
|
|
|
let mut foo = Foo {
|
|
|
|
a: 1,
|
|
|
|
b: Bar("hello".to_string()),
|
2020-12-01 02:12:09 +00:00
|
|
|
c: vec![1, 2],
|
|
|
|
d: vec![Baz { value: 3.14 }],
|
2020-11-28 00:39:59 +00:00
|
|
|
};
|
|
|
|
```
|
|
|
|
|
|
|
|
### Interact with fields using their names
|
|
|
|
|
2021-12-18 22:59:55 +00:00
|
|
|
```rust ignore
|
2020-11-28 00:39:59 +00:00
|
|
|
assert_eq!(*foo.get_field::<u32>("a").unwrap(), 1);
|
|
|
|
|
|
|
|
*foo.get_field_mut::<u32>("a").unwrap() = 2;
|
|
|
|
|
|
|
|
assert_eq!(foo.a, 2);
|
|
|
|
```
|
|
|
|
|
|
|
|
### "Patch" your types with new values
|
|
|
|
|
2021-12-18 22:59:55 +00:00
|
|
|
```rust ignore
|
2020-11-28 00:39:59 +00:00
|
|
|
let mut dynamic_struct = DynamicStruct::default();
|
|
|
|
dynamic_struct.insert("a", 42u32);
|
|
|
|
dynamic_struct.insert("c", vec![3, 4, 5]);
|
|
|
|
|
|
|
|
foo.apply(&dynamic_struct);
|
|
|
|
|
|
|
|
assert_eq!(foo.a, 42);
|
|
|
|
assert_eq!(foo.c, vec![3, 4, 5]);
|
|
|
|
```
|
|
|
|
|
|
|
|
### Look up nested fields using "path strings"
|
|
|
|
|
2021-12-18 22:59:55 +00:00
|
|
|
```rust ignore
|
2020-11-28 00:39:59 +00:00
|
|
|
let value = *foo.get_path::<f32>("d[0].value").unwrap();
|
|
|
|
assert_eq!(value, 3.14);
|
|
|
|
```
|
|
|
|
|
|
|
|
### Iterate over struct fields
|
|
|
|
|
2021-12-18 22:59:55 +00:00
|
|
|
```rust ignore
|
2020-11-28 00:39:59 +00:00
|
|
|
for (i, value: &Reflect) in foo.iter_fields().enumerate() {
|
|
|
|
let field_name = foo.name_at(i).unwrap();
|
2022-07-29 20:01:51 +00:00
|
|
|
if let Some(value) = value.downcast_ref::<u32>() {
|
2020-11-28 00:39:59 +00:00
|
|
|
println!("{} is a u32 with the value: {}", field_name, *value);
|
2021-02-22 04:50:05 +00:00
|
|
|
}
|
2020-11-28 00:39:59 +00:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
### Automatically serialize and deserialize via Serde (without explicit serde impls)
|
|
|
|
|
2021-12-18 22:59:55 +00:00
|
|
|
```rust ignore
|
2020-11-28 00:39:59 +00:00
|
|
|
let mut registry = TypeRegistry::default();
|
|
|
|
registry.register::<u32>();
|
|
|
|
registry.register::<i32>();
|
|
|
|
registry.register::<f32>();
|
|
|
|
registry.register::<String>();
|
|
|
|
registry.register::<Bar>();
|
|
|
|
registry.register::<Baz>();
|
|
|
|
|
|
|
|
let serializer = ReflectSerializer::new(&foo, ®istry);
|
|
|
|
let serialized = ron::ser::to_string_pretty(&serializer, ron::ser::PrettyConfig::default()).unwrap();
|
|
|
|
|
|
|
|
let mut deserializer = ron::de::Deserializer::from_str(&serialized).unwrap();
|
|
|
|
let reflect_deserializer = ReflectDeserializer::new(®istry);
|
|
|
|
let value = reflect_deserializer.deserialize(&mut deserializer).unwrap();
|
|
|
|
let dynamic_struct = value.take::<DynamicStruct>().unwrap();
|
|
|
|
|
2020-12-01 19:15:07 +00:00
|
|
|
assert!(foo.reflect_partial_eq(&dynamic_struct).unwrap());
|
2020-11-28 00:39:59 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
### Trait "reflection"
|
|
|
|
|
2022-06-29 02:48:47 +00:00
|
|
|
Call a trait on a given `&dyn Reflect` reference without knowing the underlying type!
|
2020-11-28 00:39:59 +00:00
|
|
|
|
2021-12-18 22:59:55 +00:00
|
|
|
```rust ignore
|
2020-11-28 00:39:59 +00:00
|
|
|
#[derive(Reflect)]
|
|
|
|
#[reflect(DoThing)]
|
|
|
|
struct MyType {
|
|
|
|
value: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl DoThing for MyType {
|
|
|
|
fn do_thing(&self) -> String {
|
|
|
|
format!("{} World!", self.value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[reflect_trait]
|
|
|
|
pub trait DoThing {
|
|
|
|
fn do_thing(&self) -> String;
|
|
|
|
}
|
|
|
|
|
|
|
|
// First, lets box our type as a Box<dyn Reflect>
|
|
|
|
let reflect_value: Box<dyn Reflect> = Box::new(MyType {
|
|
|
|
value: "Hello".to_string(),
|
|
|
|
});
|
|
|
|
|
|
|
|
// This means we no longer have direct access to MyType or its methods. We can only call Reflect methods on reflect_value.
|
|
|
|
// What if we want to call `do_thing` on our type? We could downcast using reflect_value.downcast_ref::<MyType>(), but what if we
|
|
|
|
// don't know the type at compile time?
|
|
|
|
|
|
|
|
// Normally in rust we would be out of luck at this point. Lets use our new reflection powers to do something cool!
|
2022-07-29 20:01:51 +00:00
|
|
|
let mut type_registry = TypeRegistry::default();
|
2020-11-28 00:39:59 +00:00
|
|
|
type_registry.register::<MyType>();
|
|
|
|
|
|
|
|
// The #[reflect] attribute we put on our DoThing trait generated a new `ReflectDoThing` struct, which implements TypeData.
|
|
|
|
// This was added to MyType's TypeRegistration.
|
|
|
|
let reflect_do_thing = type_registry
|
|
|
|
.get_type_data::<ReflectDoThing>(reflect_value.type_id())
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
// We can use this generated type to convert our `&dyn Reflect` reference to a `&dyn DoThing` reference
|
|
|
|
let my_trait: &dyn DoThing = reflect_do_thing.get(&*reflect_value).unwrap();
|
|
|
|
|
|
|
|
// Which means we can now call do_thing(). Magic!
|
|
|
|
println!("{}", my_trait.do_thing());
|
|
|
|
|
|
|
|
// This works because the #[reflect(MyTrait)] we put on MyType informed the Reflect derive to insert a new instance
|
2023-04-01 03:01:44 +00:00
|
|
|
// of ReflectDoThing into MyType's registration. The instance knows how to cast &dyn Reflect to &dyn DoThing, because it
|
|
|
|
// knows that &dyn Reflect should first be downcasted to &MyType, which can then be safely casted to &dyn DoThing
|
2020-11-28 00:39:59 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
## Why make this?
|
|
|
|
|
|
|
|
The whole point of Rust is static safety! Why build something that makes it easy to throw it all away?
|
|
|
|
|
|
|
|
* Some problems are inherently dynamic (scripting, some types of serialization / deserialization)
|
|
|
|
* Sometimes the dynamic way is easier
|
2020-12-01 02:12:09 +00:00
|
|
|
* Sometimes the dynamic way puts less burden on your users to derive a bunch of traits (this was a big motivator for the Bevy project)
|