type_data/type_data.rs
1//! The example demonstrates what type data is, how to create it, and how to use it.
2
3use bevy::{
4 prelude::*,
5 reflect::{FromType, TypeRegistry},
6};
7
8// It's recommended to read this example from top to bottom.
9// Comments are provided to explain the code and its purpose as you go along.
10fn main() {
11 trait Damageable {
12 type Health;
13 fn damage(&mut self, damage: Self::Health);
14 }
15
16 #[derive(Reflect, PartialEq, Debug)]
17 struct Zombie {
18 health: u32,
19 }
20
21 impl Damageable for Zombie {
22 type Health = u32;
23 fn damage(&mut self, damage: Self::Health) {
24 self.health -= damage;
25 }
26 }
27
28 // Let's say we have a reflected value.
29 // Here we know it's a `Zombie`, but for demonstration purposes let's pretend we don't.
30 // Pretend it's just some `Box<dyn Reflect>` value.
31 let mut value: Box<dyn Reflect> = Box::new(Zombie { health: 100 });
32
33 // We think `value` might contain a type that implements `Damageable`
34 // and now we want to call `Damageable::damage` on it.
35 // How can we do this without knowing in advance the concrete type is `Zombie`?
36
37 // This is where type data comes in.
38 // Type data is a way of associating type-specific data with a type for use in dynamic contexts.
39 // This type data can then be used at runtime to perform type-specific operations.
40
41 // Let's create a type data struct for `Damageable` that we can associate with `Zombie`!
42
43 // Firstly, type data must be cloneable.
44 #[derive(Clone)]
45 // Next, they are usually named with the `Reflect` prefix (we'll see why in a bit).
46 struct ReflectDamageable {
47 // Type data can contain whatever you want, but it's common to include function pointers
48 // to the type-specific operations you want to perform (such as trait methods).
49 // Just remember that we're working with `Reflect` data,
50 // so we can't use `Self`, generics, or associated types.
51 // In those cases, we'll have to use `dyn Reflect` trait objects.
52 damage: fn(&mut dyn Reflect, damage: Box<dyn Reflect>),
53 }
54
55 // Now, we can create a blanket implementation of the `FromType` trait to construct our type data
56 // for any type that implements `Reflect` and `Damageable`.
57 impl<T: Reflect + Damageable<Health: Reflect>> FromType<T> for ReflectDamageable {
58 fn from_type() -> Self {
59 Self {
60 damage: |reflect, damage| {
61 // This requires that `reflect` is `T` and not a dynamic representation like `DynamicStruct`.
62 // We could have the function pointer return a `Result`, but we'll just `unwrap` for simplicity.
63 let damageable = reflect.downcast_mut::<T>().unwrap();
64 let damage = damage.take::<T::Health>().unwrap();
65 damageable.damage(damage);
66 },
67 }
68 }
69 }
70
71 // It's also common to provide convenience methods for calling the type-specific operations.
72 impl ReflectDamageable {
73 pub fn damage(&self, reflect: &mut dyn Reflect, damage: Box<dyn Reflect>) {
74 (self.damage)(reflect, damage);
75 }
76 }
77
78 // With all this done, we're ready to make use of `ReflectDamageable`!
79 // It starts with registering our type along with its type data:
80 let mut registry = TypeRegistry::default();
81 registry.register::<Zombie>();
82 registry.register_type_data::<Zombie, ReflectDamageable>();
83
84 // Then at any point we can retrieve the type data from the registry:
85 let type_id = value.reflect_type_info().type_id();
86 let reflect_damageable = registry
87 .get_type_data::<ReflectDamageable>(type_id)
88 .unwrap();
89
90 // And call our method:
91 reflect_damageable.damage(value.as_reflect_mut(), Box::new(25u32));
92 assert_eq!(value.take::<Zombie>().unwrap(), Zombie { health: 75 });
93
94 // This is a simple example, but type data can be used for much more complex operations.
95 // Bevy also provides some useful shorthand for working with type data.
96
97 // For example, we can have the type data be automatically registered when we register the type
98 // by using the `#[reflect(MyTrait)]` attribute when defining our type.
99 #[derive(Reflect)]
100 // Notice that we don't need to type out `ReflectDamageable`.
101 // This is why we named it with the `Reflect` prefix:
102 // the derive macro will automatically look for a type named `ReflectDamageable` in the current scope.
103 #[reflect(Damageable)]
104 struct Skeleton {
105 health: u32,
106 }
107
108 impl Damageable for Skeleton {
109 type Health = u32;
110 fn damage(&mut self, damage: Self::Health) {
111 self.health -= damage;
112 }
113 }
114
115 // This will now register `Skeleton` along with its `ReflectDamageable` type data.
116 registry.register::<Skeleton>();
117
118 // And for object-safe traits (see https://doc.rust-lang.org/reference/items/traits.html#object-safety),
119 // Bevy provides a convenience macro for generating type data that converts `dyn Reflect` into `dyn MyTrait`.
120 #[reflect_trait]
121 trait Health {
122 fn health(&self) -> u32;
123 }
124
125 impl Health for Skeleton {
126 fn health(&self) -> u32 {
127 self.health
128 }
129 }
130
131 // Using the `#[reflect_trait]` macro we're able to automatically generate a `ReflectHealth` type data struct,
132 // which can then be registered like any other type data:
133 registry.register_type_data::<Skeleton, ReflectHealth>();
134
135 // Now we can use `ReflectHealth` to convert `dyn Reflect` into `dyn Health`:
136 let value: Box<dyn Reflect> = Box::new(Skeleton { health: 50 });
137
138 let type_id = value.reflect_type_info().type_id();
139 let reflect_health = registry.get_type_data::<ReflectHealth>(type_id).unwrap();
140
141 // Type data generated by `#[reflect_trait]` comes with a `get`, `get_mut`, and `get_boxed` method,
142 // which convert `&dyn Reflect` into `&dyn MyTrait`, `&mut dyn Reflect` into `&mut dyn MyTrait`,
143 // and `Box<dyn Reflect>` into `Box<dyn MyTrait>`, respectively.
144 let value: &dyn Health = reflect_health.get(value.as_reflect()).unwrap();
145 assert_eq!(value.health(), 50);
146
147 // Lastly, here's a list of some useful type data provided by Bevy that you might want to register for your types:
148 // - `ReflectDefault` for types that implement `Default`
149 // - `ReflectFromWorld` for types that implement `FromWorld`
150 // - `ReflectComponent` for types that implement `Component`
151 // - `ReflectResource` for types that implement `Resource`
152 // - `ReflectSerialize` for types that implement `Serialize`
153 // - `ReflectDeserialize` for types that implement `Deserialize`
154 //
155 // And here are some that are automatically registered by the `Reflect` derive macro:
156 // - `ReflectFromPtr`
157 // - `ReflectFromReflect` (if not `#[reflect(from_reflect = false)]`)
158}