1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
/// Prelude module to import all necessary traits and types for [`Kind`] semantics.
pub mod prelude {
pub use crate::{CastInto, Kind};
pub use crate::{
ComponentInstance, InsertInstance, InsertInstanceWorld, SpawnInstance, SpawnInstanceWorld,
};
pub use crate::{ContainsInstance, Instance, InstanceMut, InstanceRef};
pub use crate::{GetInstanceCommands, InstanceCommands};
pub use crate::{GetTriggerTargetInstance, TriggerInstance};
}
mod instance;
use bevy_ecs::world::DeferredWorld;
use bevy_reflect::TypePath;
pub use instance::*;
use bevy_ecs::component::Mutable;
use bevy_ecs::{prelude::*, query::QueryFilter};
/// A type which represents the kind of an [`Entity`].
///
/// An entity is of kind `T` if it matches [`Query<Entity, <T as Kind>::Filter>`][`Query`].
///
/// By default, an entity with a [`Component`] of type `T` is also of kind `T`.
///
/// # Examples
/// ```
/// # use bevy::prelude::*;
/// # use moonshine_kind::prelude::*;
///
/// #[derive(Component)]
/// struct Apple;
///
/// #[derive(Component)]
/// struct Orange;
///
/// struct Fruit;
///
/// impl Kind for Fruit {
/// type Filter = Or<(With<Apple>, With<Orange>)>;
/// }
///
/// fn fruits(query: Query<Instance<Fruit>>) {
/// for fruit in query.iter() {
/// println!("{fruit:?} is a fruit!");
/// }
/// }
///
/// # bevy_ecs::system::assert_is_system(fruits);
/// ```
pub trait Kind: 'static + Send + Sized + Sync {
/// The [`QueryFilter`] which defines this kind.
type Filter: QueryFilter;
/// Returns the debug name of this kind.
///
/// By default, this is the short type name (without path) of this kind.
/// This is mainly used for [`Debug`](std::fmt::Debug) and [`Display`](std::fmt::Display) implementations.
fn debug_name() -> String {
disqualified::ShortName::of::<Self>().to_string()
}
}
impl<T: Component> Kind for T {
type Filter = With<T>;
}
/// Represents the kind of any [`Entity`].
///
/// See [`Instance<Any>`] for more information on usage.
#[derive(TypePath)]
pub struct Any;
impl Kind for Any {
type Filter = ();
}
/// A trait which allows safe casting from one [`Kind`] to another.
pub trait CastInto<T: Kind>: Kind {
#[doc(hidden)]
unsafe fn cast(instance: Instance<Self>) -> Instance<T> {
// SAFE: Because we said so.
// TODO: Can we use required components to enforce this?
Instance::from_entity_unchecked(instance.entity())
}
}
impl<T: Kind> CastInto<T> for T {
unsafe fn cast(instance: Instance<Self>) -> Instance<T> {
Instance::from_entity_unchecked(instance.entity())
}
}
/// Extension trait used to spawn instances via [`Commands`].
pub trait SpawnInstance {
/// Spawns a new [`Entity`] which contains the given instance of `T` and returns an [`InstanceCommands<T>`] for it.
fn spawn_instance<T: Component>(&mut self, instance: T) -> InstanceCommands<'_, T>;
}
impl SpawnInstance for Commands<'_, '_> {
fn spawn_instance<T: Component>(&mut self, instance: T) -> InstanceCommands<'_, T> {
let entity = self.spawn(instance).id();
// SAFE: `entity` is spawned as a valid instance of kind `T`.
unsafe { InstanceCommands::from_entity_unchecked(self.entity(entity)) }
}
}
/// Extension trait used to spawn instances via [`World`].
pub trait SpawnInstanceWorld {
/// Spawns a new [`Entity`] which contains the given instance of `T` and returns an [`InstanceRef<T>`] for it.
fn spawn_instance<T: Component>(&'_ mut self, instance: T) -> InstanceRef<'_, T>;
/// Spawns a new [`Entity`] which contains the given instance of `T` and returns an [`InstanceMut<T>`] for it.
fn spawn_instance_mut<T: Component<Mutability = Mutable>>(
&'_ mut self,
instance: T,
) -> InstanceMut<'_, T>;
}
impl SpawnInstanceWorld for World {
fn spawn_instance<T: Component>(&'_ mut self, instance: T) -> InstanceRef<'_, T> {
let mut entity = self.spawn_empty();
entity.insert(instance);
// SAFE: `entity` is spawned as a valid instance of kind `T`.
unsafe { InstanceRef::from_entity_unchecked(entity.into_readonly()) }
}
fn spawn_instance_mut<T: Component<Mutability = Mutable>>(
&'_ mut self,
instance: T,
) -> InstanceMut<'_, T> {
let mut entity = self.spawn_empty();
entity.insert(instance);
// SAFE: `entity` is spawned as a valid instance of kind `T`.
unsafe { InstanceMut::from_entity_unchecked(entity.into_mutable()) }
}
}
/// Extension trait used to insert instances via [`EntityCommands`].
pub trait InsertInstance {
/// Inserts the given instance of `T` into the entity and returns an [`InstanceCommands<T>`] for it.
fn insert_instance<T: Component>(&mut self, instance: T) -> InstanceCommands<'_, T>;
}
impl InsertInstance for EntityCommands<'_> {
fn insert_instance<T: Component>(&mut self, instance: T) -> InstanceCommands<'_, T> {
self.insert(instance);
// SAFE: `entity` is spawned as a valid instance of kind `T`.
unsafe { InstanceCommands::from_entity_unchecked(self.reborrow()) }
}
}
/// Extension trait used to insert instances via [`EntityWorldMut`].
pub trait InsertInstanceWorld {
/// Inserts the given instance of `T` into the entity and returns an [`InstanceRef<T>`] for it.
fn insert_instance<T: Component>(&'_ mut self, instance: T) -> InstanceRef<'_, T>;
/// Inserts the given instance of `T` into the entity and returns an [`InstanceMut<T>`] for it.
///
/// This requires `T` to be [`Mutable`].
fn insert_instance_mut<T: Component<Mutability = Mutable>>(
&'_ mut self,
instance: T,
) -> InstanceMut<'_, T>;
}
impl InsertInstanceWorld for EntityWorldMut<'_> {
fn insert_instance<T: Component>(&'_ mut self, instance: T) -> InstanceRef<'_, T> {
self.insert(instance);
InstanceRef::from_entity(self.as_readonly()).unwrap()
}
fn insert_instance_mut<T: Component<Mutability = Mutable>>(
&'_ mut self,
instance: T,
) -> InstanceMut<'_, T> {
self.insert(instance);
InstanceMut::from_entity(self.as_mutable()).unwrap()
}
}
/// Extension trait used to get [`Component`] data from an [`Instance<T>`] via [`World`].
pub trait ComponentInstance {
/// Returns a reference to the given instance.
fn instance<T: Component>(&'_ self, instance: Instance<T>) -> Option<InstanceRef<'_, T>> {
self.get_instance(instance.entity())
}
/// Returns a reference to the given instance, if it is of [`Kind`] `T`.
fn get_instance<T: Component>(&'_ self, entity: Entity) -> Option<InstanceRef<'_, T>>;
/// Returns a mutable reference to the given instance.
///
/// This requires `T` to be [`Mutable`].
fn instance_mut<T: Component<Mutability = Mutable>>(
&'_ mut self,
instance: Instance<T>,
) -> Option<InstanceMut<'_, T>> {
self.get_instance_mut(instance.entity())
}
/// Returns a mutable reference to the given instance, if it is of [`Kind`] `T`.
///
/// This requires `T` to be [`Mutable`].
fn get_instance_mut<T: Component<Mutability = Mutable>>(
&'_ mut self,
entity: Entity,
) -> Option<InstanceMut<'_, T>>;
}
impl ComponentInstance for World {
fn get_instance<T: Component>(&'_ self, entity: Entity) -> Option<InstanceRef<'_, T>> {
InstanceRef::from_entity(self.get_entity(entity).ok()?)
}
fn get_instance_mut<T: Component<Mutability = Mutable>>(
&'_ mut self,
entity: Entity,
) -> Option<InstanceMut<'_, T>> {
InstanceMut::from_entity(self.get_entity_mut(entity).ok()?.into_mutable())
}
}
impl ComponentInstance for DeferredWorld<'_> {
fn get_instance<T: Component>(&'_ self, entity: Entity) -> Option<InstanceRef<'_, T>> {
InstanceRef::from_entity(self.get_entity(entity).ok()?)
}
fn get_instance_mut<T: Component<Mutability = Mutable>>(
&'_ mut self,
entity: Entity,
) -> Option<InstanceMut<'_, T>> {
InstanceMut::from_entity(self.get_entity_mut(entity).ok()?)
}
}
#[cfg(test)]
mod tests {
use super::*;
use bevy_ecs::system::RunSystemOnce;
fn count<T: Kind>(query: Query<Instance<T>>) -> usize {
query.iter().count()
}
#[test]
fn kind_with() {
#[derive(Component)]
struct Foo;
let mut world = World::new();
world.spawn(Foo);
assert_eq!(world.run_system_once(count::<Foo>).unwrap(), 1);
}
#[test]
fn kind_without() {
#[derive(Component)]
struct Foo;
struct NotFoo;
impl Kind for NotFoo {
type Filter = Without<Foo>;
}
let mut world = World::new();
world.spawn(Foo);
assert_eq!(world.run_system_once(count::<NotFoo>).unwrap(), 0);
}
#[test]
fn kind_multi() {
#[derive(Component)]
struct Foo;
#[derive(Component)]
struct Bar;
let mut world = World::new();
world.spawn((Foo, Bar));
assert_eq!(world.run_system_once(count::<Foo>).unwrap(), 1);
assert_eq!(world.run_system_once(count::<Bar>).unwrap(), 1);
}
#[test]
fn kind_cast() {
#[derive(Component)]
struct Foo;
#[derive(Component)]
struct Bar;
impl CastInto<Bar> for Foo {}
let any = Instance::<Any>::PLACEHOLDER;
let foo = Instance::<Foo>::PLACEHOLDER;
let bar = foo.cast_into::<Bar>();
assert!(foo.cast_into_any() == any);
assert!(bar.cast_into_any() == any);
// assert!(foo.cast_into() == any); // TODO: Can we make this compile?
// assert!(any.cast_into::<Foo>() == foo); // <-- Must not compile!
// assert!(bar.cast_into::<Foo>() == foo); // <-- Must not compile!
assert!(bar.entity() == foo.entity());
}
}