moonshine_kind/
instance.rs

1use std::borrow::Borrow;
2use std::{
3    cmp::Ordering,
4    fmt,
5    hash::{Hash, Hasher},
6    marker::PhantomData,
7    ops::{Deref, DerefMut},
8};
9
10use bevy_ecs::change_detection::MaybeLocation;
11use bevy_ecs::component::Mutable;
12use bevy_ecs::query::EcsAccessType;
13use bevy_ecs::relationship::RelationshipSourceCollection;
14use bevy_ecs::{
15    archetype::Archetype,
16    change_detection::Tick,
17    component::{ComponentId, Components},
18    entity::{EntityMapper, MapEntities},
19    prelude::*,
20    query::{FilteredAccess, QueryData, ReadOnlyQueryData, WorldQuery},
21    storage::{Table, TableRow},
22    system::EntityCommands,
23    world::unsafe_world_cell::UnsafeWorldCell,
24};
25use bevy_reflect::Reflect;
26
27use crate::{Any, CastInto, Kind};
28
29/// Represents an [`Entity`] of [`Kind`] `T`.
30///
31/// `Instance<Any>` is functionally equivalent to an entity.
32///
33/// # Usage
34/// An `Instance<T>` can be used to access entities in a "kind-safe" manner to improve safety and readability.
35///
36/// This type is designed to behave exactly like an [`Entity`].
37///
38/// This means you may use it as a [`Query`] parameter, pass it to [`Commands`] to access [`InstanceCommands<T>`],
39/// or store it as a type-safe reference to an [`Entity`].
40///
41/// Note that an `Instance<T>` has `'static` lifetime and does not contain any [`Component`] data.
42/// It *only* contains type information.
43///
44/// # Example
45/// ```
46/// # use bevy::prelude::*;
47/// # use moonshine_kind::prelude::*;
48///
49/// #[derive(Component)]
50/// struct Apple;
51///
52/// #[derive(Component)]
53/// struct Orange;
54///
55/// struct Fruit;
56///
57/// impl Kind for Fruit {
58///     type Filter = Or<(With<Apple>, With<Orange>)>;
59/// }
60///
61/// #[derive(Resource, Deref, DerefMut)]
62/// struct FruitBasket(Vec<Instance<Fruit>>);
63///
64/// fn collect_fruits(mut basket: ResMut<FruitBasket>, fruits: Query<Instance<Fruit>>) {
65///     for fruit in fruits.iter() {
66///         println!("{fruit:?}");
67///         basket.push(fruit);
68///     }
69/// }
70///
71/// # bevy_ecs::system::assert_is_system(collect_fruits);
72/// ```
73#[derive(Reflect)]
74pub struct Instance<T: Kind>(Entity, #[reflect(ignore)] PhantomData<T>);
75
76impl<T: Kind> Instance<T> {
77    /// Same as [`Entity::PLACEHOLDER`], but for an [`Instance<T>`].
78    pub const PLACEHOLDER: Self = Self(Entity::PLACEHOLDER, PhantomData);
79
80    /// Creates a new instance of kind `T` from some [`Entity`].
81    ///
82    /// # Usage
83    /// This function is useful when you **know** an `Entity` is of a specific kind and you
84    /// need an `Instance<T>` with no way to validate it.
85    ///
86    /// See [`Instance::from_entity`] for a safer alternative.
87    ///
88    /// # Safety
89    /// Assumes `entity` is a valid instance of kind `T`.
90    ///
91    /// # Example
92    /// ```
93    /// # use bevy::prelude::*;
94    /// # use moonshine_kind::prelude::*;
95    ///
96    /// #[derive(Component)]
97    /// struct Apple;
98    ///
99    /// fn init_apple(entity: Entity, commands: &mut Commands) -> Instance<Apple> {
100    ///     commands.entity(entity).insert(Apple);
101    ///     // SAFE: `entity` will be a valid instance of `Apple`.
102    ///     unsafe { Instance::from_entity_unchecked(entity) }
103    /// }
104    /// ```
105    pub unsafe fn from_entity_unchecked(entity: Entity) -> Self {
106        Self(entity, PhantomData)
107    }
108
109    /// Returns the [`Entity`] of this instance.
110    pub fn entity(&self) -> Entity {
111        self.0
112    }
113
114    /// Converts this instance into an instance of another kind [`Kind`] `U`.
115    ///
116    /// # Usage
117    /// A kind `T` is safety convertible to another kind `U` if `T` implements [`CastInto<U>`].
118    pub fn cast_into<U: Kind>(self) -> Instance<U>
119    where
120        T: CastInto<U>,
121    {
122        unsafe { T::cast(self) }
123    }
124
125    /// Converts this instance into an instance of [`Kind`] [`Any`].
126    ///
127    /// # Usage
128    ///
129    /// Any [`Instance<T>`] can be safely cast into an [`Instance<Any>`] using this function.
130    pub fn cast_into_any(self) -> Instance<Any> {
131        // SAFE: All instances are of kind `Any`.
132        unsafe { self.cast_into_unchecked() }
133    }
134
135    /// Converts this instance into an instance of another kind [`Kind`] `U` without any validation.
136    ///
137    /// # Usage
138    /// This function is useful when you **know** an `Instance<T>` is convertible to a specific type and you
139    /// need an `Instance<U>` with no way to validate it.
140    ///
141    /// Always prefer to explicitly declare safe casts with the [`CastInto`] trait and use [`Instance::cast_into`].
142    ///
143    /// # Safety
144    /// Assumes this instance is also a valid `Instance<U>`.
145    pub unsafe fn cast_into_unchecked<U: Kind>(self) -> Instance<U> {
146        Instance::from_entity_unchecked(self.entity())
147    }
148
149    /// Returns a mutable reference to the internal [`Entity`] of this [`Instance`].
150    ///
151    /// # Safety
152    /// You are responsible to ensure the entity is still a valid instance of [`Kind`] `T`.
153    #[deprecated(note = "use `Instance::<T>::from_entity_unchecked` instead")]
154    pub unsafe fn as_entity_mut(&mut self) -> &mut Entity {
155        &mut self.0
156    }
157}
158
159impl<T: Component> Instance<T> {
160    /// Creates a new instance of kind `T` from some [`EntityRef`] if the entity has a [`Component`] of type `T`.
161    pub fn from_entity(entity: EntityRef) -> Option<Self> {
162        if entity.contains::<T>() {
163            // SAFE: `entity` must be of kind `T`.
164            Some(unsafe { Self::from_entity_unchecked(entity.id()) })
165        } else {
166            None
167        }
168    }
169}
170
171impl<T: Kind> Clone for Instance<T> {
172    fn clone(&self) -> Self {
173        *self
174    }
175}
176
177impl<T: Kind> Copy for Instance<T> {}
178
179impl<T: Kind> fmt::Debug for Instance<T> {
180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181        write!(f, "{}({:?})", T::debug_name(), self.0)
182    }
183}
184
185impl<T: Kind> fmt::Display for Instance<T> {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        write!(
188            f,
189            "{}({}v{})",
190            T::debug_name(),
191            self.0.index(),
192            self.0.generation()
193        )
194    }
195}
196
197impl<T: Kind> Hash for Instance<T> {
198    fn hash<H: Hasher>(&self, state: &mut H) {
199        self.0.hash(state);
200    }
201}
202
203impl<T: Kind, U: Kind> PartialEq<Instance<U>> for Instance<T> {
204    fn eq(&self, other: &Instance<U>) -> bool {
205        self.0 == other.0
206    }
207}
208
209impl<T: Kind> PartialEq<Entity> for Instance<T> {
210    fn eq(&self, other: &Entity) -> bool {
211        self.0 == *other
212    }
213}
214
215impl<T: Kind> PartialEq<Instance<T>> for Entity {
216    fn eq(&self, other: &Instance<T>) -> bool {
217        other == self
218    }
219}
220
221impl<T: Kind> Eq for Instance<T> {}
222
223impl<T: Kind> PartialOrd for Instance<T> {
224    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
225        Some(self.cmp(other))
226    }
227}
228
229impl<T: Kind> Ord for Instance<T> {
230    fn cmp(&self, other: &Self) -> Ordering {
231        self.0.cmp(&other.0)
232    }
233}
234
235impl<T: Kind> Deref for Instance<T> {
236    type Target = Entity;
237
238    fn deref(&self) -> &Self::Target {
239        &self.0
240    }
241}
242
243impl<T: Kind> Borrow<Entity> for Instance<T> {
244    fn borrow(&self) -> &Entity {
245        &self.0
246    }
247}
248
249unsafe impl<T: Kind> WorldQuery for Instance<T> {
250    type Fetch<'a> = <T::Filter as WorldQuery>::Fetch<'a>;
251
252    type State = <T::Filter as WorldQuery>::State;
253
254    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
255        <T::Filter as WorldQuery>::shrink_fetch(fetch)
256    }
257
258    unsafe fn init_fetch<'w>(
259        world: UnsafeWorldCell<'w>,
260        state: &Self::State,
261        last_change_tick: Tick,
262        change_tick: Tick,
263    ) -> Self::Fetch<'w> {
264        <T::Filter as WorldQuery>::init_fetch(world, state, last_change_tick, change_tick)
265    }
266
267    const IS_DENSE: bool = <T::Filter as WorldQuery>::IS_DENSE;
268
269    unsafe fn set_archetype<'w>(
270        fetch: &mut Self::Fetch<'w>,
271        state: &Self::State,
272        archetype: &'w Archetype,
273        table: &'w Table,
274    ) {
275        <T::Filter as WorldQuery>::set_archetype(fetch, state, archetype, table)
276    }
277
278    unsafe fn set_table<'w>(fetch: &mut Self::Fetch<'w>, state: &Self::State, table: &'w Table) {
279        <T::Filter as WorldQuery>::set_table(fetch, state, table)
280    }
281
282    fn update_component_access(state: &Self::State, access: &mut FilteredAccess) {
283        <T::Filter as WorldQuery>::update_component_access(state, access)
284    }
285
286    fn get_state(components: &Components) -> Option<Self::State> {
287        <T::Filter as WorldQuery>::get_state(components)
288    }
289
290    fn init_state(world: &mut World) -> Self::State {
291        <T::Filter as WorldQuery>::init_state(world)
292    }
293
294    fn matches_component_set(
295        state: &Self::State,
296        set_contains_id: &impl Fn(ComponentId) -> bool,
297    ) -> bool {
298        <T::Filter as WorldQuery>::matches_component_set(state, set_contains_id)
299    }
300}
301
302unsafe impl<T: Kind> ReadOnlyQueryData for Instance<T> {}
303
304unsafe impl<T: Kind> QueryData for Instance<T> {
305    type ReadOnly = Self;
306
307    const IS_READ_ONLY: bool = <Entity as QueryData>::IS_READ_ONLY;
308
309    const IS_ARCHETYPAL: bool = <Entity as QueryData>::IS_ARCHETYPAL;
310
311    type Item<'w, 's> = Self;
312
313    fn shrink<'wlong: 'wshort, 'wshort, 's>(
314        item: Self::Item<'wlong, 's>,
315    ) -> Self::Item<'wshort, 's> {
316        item
317    }
318
319    unsafe fn fetch<'w, 's>(
320        _state: &'s Self::State,
321        _fetch: &mut Self::Fetch<'w>,
322        entity: Entity,
323        _table_row: TableRow,
324    ) -> Option<Self::Item<'w, 's>> {
325        Some(Instance::from_entity_unchecked(entity))
326    }
327
328    fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
329        // Based on impl for `Entity`
330        std::iter::empty()
331    }
332}
333
334impl<T: Kind> MapEntities for Instance<T> {
335    fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) {
336        self.0 = entity_mapper.get_mapped(self.0);
337    }
338}
339
340impl<T: Kind> From<Instance<T>> for Entity {
341    fn from(instance: Instance<T>) -> Self {
342        instance.entity()
343    }
344}
345
346impl<T: Kind> RelationshipSourceCollection for Instance<T> {
347    type SourceIter<'a> = <Entity as RelationshipSourceCollection>::SourceIter<'a>;
348
349    fn new() -> Self {
350        Self::PLACEHOLDER
351    }
352
353    fn with_capacity(_capacity: usize) -> Self {
354        Self::new()
355    }
356
357    fn reserve(&mut self, additional: usize) {
358        self.0.reserve(additional);
359    }
360
361    fn add(&mut self, entity: Entity) -> bool {
362        self.0.add(entity)
363    }
364
365    fn remove(&mut self, entity: Entity) -> bool {
366        self.0.remove(entity)
367    }
368
369    fn iter(&self) -> Self::SourceIter<'_> {
370        self.0.iter()
371    }
372
373    fn len(&self) -> usize {
374        self.0.len()
375    }
376
377    fn clear(&mut self) {
378        self.0.clear();
379    }
380
381    fn shrink_to_fit(&mut self) {
382        self.0.shrink_to_fit();
383    }
384
385    fn extend_from_iter(&mut self, entities: impl IntoIterator<Item = Entity>) {
386        self.0.extend_from_iter(entities)
387    }
388}
389
390impl From<Entity> for Instance<Any> {
391    fn from(entity: Entity) -> Self {
392        Self(entity, PhantomData)
393    }
394}
395
396impl<T: Kind> ContainsEntity for Instance<T> {
397    fn entity(&self) -> Entity {
398        self.entity()
399    }
400}
401
402/// Similar to [`ContainsEntity`], but for [`Instance<T>`].
403pub trait ContainsInstance<T: Kind> {
404    /// Returns the associated [`Instance<T>`].
405    fn instance(&self) -> Instance<T>;
406
407    /// Returns the [`Entity`] of the associated [`Instance<T>`].
408    fn entity(&self) -> Entity {
409        self.instance().entity()
410    }
411}
412
413/// A [`QueryData`] item which represents a reference to an [`Instance<T>`] and its associated [`Component`].
414///
415/// This is analogous to a `(Instance<T>, &T)` query.
416///
417/// # Usage
418/// If a [`Kind`] is also a component, it is often convenient to access the instance and component data together.
419/// This type is designed to make these queries more ergonomic.
420///
421/// You may use this type as either a [`Query`] parameter, or access it from an [`EntityRef`].
422///
423/// # Example
424/// ```
425/// # use bevy::prelude::*;
426/// # use moonshine_kind::prelude::*;
427///
428/// #[derive(Component)]
429/// struct Apple {
430///     freshness: f32,
431/// }
432///
433/// impl Apple {
434///     fn is_fresh(&self) -> bool {
435///         self.freshness >= 0.5
436///     }
437/// }
438///
439/// // Query Access:
440/// fn fresh_apples(query: Query<InstanceRef<Apple>>) -> Vec<Instance<Apple>> {
441///     query.iter()
442///         .filter_map(|apple| apple.is_fresh().then_some(apple.instance()))
443///         .collect()
444/// }
445///
446/// // Entity Access:
447/// fn fresh_apples_world<'a>(world: &'a World) -> Vec<InstanceRef<'a, Apple>> {
448///    world.try_query::<EntityRef>()
449///         .unwrap()
450///         .iter(&world)
451///         .filter_map(|entity| InstanceRef::from_entity(entity))
452///         .collect()
453/// }
454///
455/// # bevy_ecs::system::assert_is_system(fresh_apples);
456/// ```
457pub struct InstanceRef<'a, T: Component>(Instance<T>, &'a T);
458
459unsafe impl<T: Component> WorldQuery for InstanceRef<'_, T> {
460    type Fetch<'w> = <(Instance<T>, &'static T) as WorldQuery>::Fetch<'w>;
461
462    type State = <(Instance<T>, &'static T) as WorldQuery>::State;
463
464    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
465        <(Instance<T>, &T) as WorldQuery>::shrink_fetch(fetch)
466    }
467
468    unsafe fn init_fetch<'w>(
469        world: UnsafeWorldCell<'w>,
470        state: &Self::State,
471        last_run: Tick,
472        this_run: Tick,
473    ) -> Self::Fetch<'w> {
474        <(Instance<T>, &T) as WorldQuery>::init_fetch(world, state, last_run, this_run)
475    }
476
477    const IS_DENSE: bool = <(Instance<T>, &T) as WorldQuery>::IS_DENSE;
478
479    unsafe fn set_archetype<'w>(
480        fetch: &mut Self::Fetch<'w>,
481        state: &Self::State,
482        archetype: &'w Archetype,
483        table: &'w Table,
484    ) {
485        <(Instance<T>, &T) as WorldQuery>::set_archetype(fetch, state, archetype, table)
486    }
487
488    unsafe fn set_table<'w>(fetch: &mut Self::Fetch<'w>, state: &Self::State, table: &'w Table) {
489        <(Instance<T>, &T) as WorldQuery>::set_table(fetch, state, table)
490    }
491
492    fn update_component_access(state: &Self::State, access: &mut FilteredAccess) {
493        <(Instance<T>, &T) as WorldQuery>::update_component_access(state, access)
494    }
495
496    fn init_state(world: &mut World) -> Self::State {
497        <(Instance<T>, &T) as WorldQuery>::init_state(world)
498    }
499
500    fn get_state(components: &Components) -> Option<Self::State> {
501        <(Instance<T>, &T) as WorldQuery>::get_state(components)
502    }
503
504    fn matches_component_set(
505        state: &Self::State,
506        set_contains_id: &impl Fn(ComponentId) -> bool,
507    ) -> bool {
508        <(Instance<T>, &T) as WorldQuery>::matches_component_set(state, set_contains_id)
509    }
510}
511
512unsafe impl<T: Component> QueryData for InstanceRef<'_, T> {
513    type ReadOnly = Self;
514
515    const IS_READ_ONLY: bool = true;
516
517    const IS_ARCHETYPAL: bool = <&'static T as QueryData>::IS_ARCHETYPAL;
518
519    type Item<'w, 's> = InstanceRef<'w, T>;
520
521    fn shrink<'wlong: 'wshort, 'wshort, 's>(
522        item: Self::Item<'wlong, 's>,
523    ) -> Self::Item<'wshort, 's> {
524        InstanceRef(item.0, item.1)
525    }
526
527    unsafe fn fetch<'w, 's>(
528        state: &'s Self::State,
529        fetch: &mut Self::Fetch<'w>,
530        entity: Entity,
531        table_row: TableRow,
532    ) -> Option<Self::Item<'w, 's>> {
533        <(Instance<T>, &T) as QueryData>::fetch(state, fetch, entity, table_row)
534            .map(|(instance, data)| InstanceRef(instance, data))
535    }
536
537    fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
538        <(Instance<T>, &T) as QueryData>::iter_access(state)
539    }
540}
541
542unsafe impl<T: Component> ReadOnlyQueryData for InstanceRef<'_, T> {}
543
544impl<'a, T: Component> InstanceRef<'a, T> {
545    /// Creates a new [`InstanceRef<T>`] from an [`EntityRef`] if it contains a given [`Component`] of type `T`.
546    pub fn from_entity(entity: EntityRef<'a>) -> Option<Self> {
547        Some(Self(
548            // SAFE: Kind is validated by `entity.get()` above.
549            unsafe { Instance::from_entity_unchecked(entity.id()) },
550            entity.get()?,
551        ))
552    }
553
554    /// Creates a new [`InstanceRef<T>`] from [`EntityRef`] without any validation.
555    ///
556    /// # Safety
557    /// Assumes `entity` is a valid instance of kind `T`.
558    pub unsafe fn from_entity_unchecked(entity: EntityRef<'a>) -> Self {
559        Self(
560            Instance::from_entity_unchecked(entity.id()),
561            entity.get().unwrap(),
562        )
563    }
564}
565
566impl<T: Component> Clone for InstanceRef<'_, T> {
567    fn clone(&self) -> Self {
568        *self
569    }
570}
571
572impl<T: Component> Copy for InstanceRef<'_, T> {}
573
574impl<T: Component> From<InstanceRef<'_, T>> for Instance<T> {
575    fn from(item: InstanceRef<T>) -> Self {
576        item.instance()
577    }
578}
579
580impl<T: Component> From<&InstanceRef<'_, T>> for Instance<T> {
581    fn from(item: &InstanceRef<T>) -> Self {
582        item.instance()
583    }
584}
585
586impl<T: Component> PartialEq for InstanceRef<'_, T> {
587    fn eq(&self, other: &Self) -> bool {
588        self.0 == other.0
589    }
590}
591
592impl<T: Component> Eq for InstanceRef<'_, T> {}
593
594impl<T: Component> Deref for InstanceRef<'_, T> {
595    type Target = T;
596
597    fn deref(&self) -> &Self::Target {
598        self.1
599    }
600}
601
602impl<T: Component> AsRef<Instance<T>> for InstanceRef<'_, T> {
603    fn as_ref(&self) -> &Instance<T> {
604        &self.0
605    }
606}
607
608impl<T: Component> AsRef<T> for InstanceRef<'_, T> {
609    fn as_ref(&self) -> &T {
610        self.1
611    }
612}
613
614impl<T: Component> ContainsInstance<T> for InstanceRef<'_, T> {
615    fn instance(&self) -> Instance<T> {
616        self.0
617    }
618}
619
620/// A [`QueryData`] item which represents a mutable reference to an [`Instance<T>`] and its associated [`Component`].
621///
622/// This is analogous to a `(Instance<T>, &mut T)` query.
623///
624/// # Usage
625/// This type behaves similar like [`InstanceRef<T>`] but allows mutable access to its associated [`Component`].
626///
627/// The main difference is that you cannot create an [`InstanceMut<T>`] from an [`EntityMut`].
628/// See [`InstanceMut::from_entity`] for more details.
629///
630/// See [`InstanceRef<T>`] for more information and examples.
631pub struct InstanceMut<'a, T: Component>(Instance<T>, Mut<'a, T>);
632
633unsafe impl<T: Component> WorldQuery for InstanceMut<'_, T> {
634    type Fetch<'w> = <(Instance<T>, &'static mut T) as WorldQuery>::Fetch<'w>;
635
636    type State = <(Instance<T>, &'static mut T) as WorldQuery>::State;
637
638    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
639        <(Instance<T>, &mut T) as WorldQuery>::shrink_fetch(fetch)
640    }
641
642    unsafe fn init_fetch<'w>(
643        world: UnsafeWorldCell<'w>,
644        state: &Self::State,
645        last_run: Tick,
646        this_run: Tick,
647    ) -> Self::Fetch<'w> {
648        <(Instance<T>, &mut T) as WorldQuery>::init_fetch(world, state, last_run, this_run)
649    }
650
651    const IS_DENSE: bool = <(Instance<T>, &T) as WorldQuery>::IS_DENSE;
652
653    unsafe fn set_archetype<'w>(
654        fetch: &mut Self::Fetch<'w>,
655        state: &Self::State,
656        archetype: &'w Archetype,
657        table: &'w Table,
658    ) {
659        <(Instance<T>, &mut T) as WorldQuery>::set_archetype(fetch, state, archetype, table)
660    }
661
662    unsafe fn set_table<'w>(fetch: &mut Self::Fetch<'w>, state: &Self::State, table: &'w Table) {
663        <(Instance<T>, &mut T) as WorldQuery>::set_table(fetch, state, table)
664    }
665
666    fn update_component_access(state: &Self::State, access: &mut FilteredAccess) {
667        <(Instance<T>, &T) as WorldQuery>::update_component_access(state, access)
668    }
669
670    fn init_state(world: &mut World) -> Self::State {
671        <(Instance<T>, &T) as WorldQuery>::init_state(world)
672    }
673
674    fn get_state(components: &Components) -> Option<Self::State> {
675        <(Instance<T>, &T) as WorldQuery>::get_state(components)
676    }
677
678    fn matches_component_set(
679        state: &Self::State,
680        set_contains_id: &impl Fn(ComponentId) -> bool,
681    ) -> bool {
682        <(Instance<T>, &T) as WorldQuery>::matches_component_set(state, set_contains_id)
683    }
684}
685
686unsafe impl<'b, T: Component<Mutability = Mutable>> QueryData for InstanceMut<'b, T> {
687    type ReadOnly = InstanceRef<'b, T>;
688
689    const IS_READ_ONLY: bool = false;
690
691    const IS_ARCHETYPAL: bool = <&'static mut T as QueryData>::IS_ARCHETYPAL;
692
693    type Item<'w, 's> = InstanceMut<'w, T>;
694
695    fn shrink<'wlong: 'wshort, 'wshort, 's>(
696        item: Self::Item<'wlong, 's>,
697    ) -> Self::Item<'wshort, 's> {
698        InstanceMut(item.0, item.1)
699    }
700
701    unsafe fn fetch<'w, 's>(
702        state: &'s Self::State,
703        fetch: &mut Self::Fetch<'w>,
704        entity: Entity,
705        table_row: TableRow,
706    ) -> Option<Self::Item<'w, 's>> {
707        <(Instance<T>, &mut T) as QueryData>::fetch(state, fetch, entity, table_row)
708            .map(|(instance, data)| InstanceMut(instance, data))
709    }
710
711    fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
712        <(Instance<T>, &mut T) as QueryData>::iter_access(state)
713    }
714}
715
716impl<'a, T: Component<Mutability = Mutable>> InstanceMut<'a, T> {
717    /// Creates a new [`InstanceMut<T>`] from an [`EntityWorldMut`] if it contains a given [`Component`] of type `T`.
718    pub fn from_entity(entity: EntityMut<'a>) -> Option<Self> {
719        let id = entity.id();
720        let data = entity.into_mut()?;
721        Some(Self(
722            // SAFE: Kind is validated by `entity.get_mut()` above.
723            unsafe { Instance::from_entity_unchecked(id) },
724            data,
725        ))
726    }
727
728    /// Creates a new [`InstanceMut<T>`] from an [`EntityMut`] without any validation.
729    ///
730    /// # Safety
731    /// Assumes `entity` is a valid instance of kind `T`.
732    pub unsafe fn from_entity_unchecked(entity: EntityMut<'a>) -> Self {
733        let id = entity.id();
734        let data = entity.into_mut().unwrap();
735        Self(Instance::from_entity_unchecked(id), data)
736    }
737}
738
739impl<T: Component> From<InstanceMut<'_, T>> for Instance<T> {
740    fn from(item: InstanceMut<T>) -> Self {
741        item.instance()
742    }
743}
744
745impl<T: Component> From<&InstanceMut<'_, T>> for Instance<T> {
746    fn from(item: &InstanceMut<T>) -> Self {
747        item.instance()
748    }
749}
750
751impl<T: Component> PartialEq for InstanceMut<'_, T> {
752    fn eq(&self, other: &Self) -> bool {
753        self.0 == other.0
754    }
755}
756
757impl<T: Component> Eq for InstanceMut<'_, T> {}
758
759impl<T: Component> Deref for InstanceMut<'_, T> {
760    type Target = T;
761
762    fn deref(&self) -> &Self::Target {
763        self.1.as_ref()
764    }
765}
766
767impl<T: Component> DerefMut for InstanceMut<'_, T> {
768    fn deref_mut(&mut self) -> &mut Self::Target {
769        self.1.as_mut()
770    }
771}
772
773impl<T: Component> AsRef<Instance<T>> for InstanceMut<'_, T> {
774    fn as_ref(&self) -> &Instance<T> {
775        &self.0
776    }
777}
778
779impl<T: Component> AsRef<T> for InstanceMut<'_, T> {
780    fn as_ref(&self) -> &T {
781        self.1.as_ref()
782    }
783}
784
785impl<T: Component> AsMut<T> for InstanceMut<'_, T> {
786    fn as_mut(&mut self) -> &mut T {
787        self.1.as_mut()
788    }
789}
790
791impl<T: Component> DetectChanges for InstanceMut<'_, T> {
792    fn is_added(&self) -> bool {
793        self.1.is_added()
794    }
795
796    fn is_changed(&self) -> bool {
797        self.1.is_changed()
798    }
799
800    fn last_changed(&self) -> Tick {
801        self.1.last_changed()
802    }
803
804    fn added(&self) -> Tick {
805        self.1.added()
806    }
807
808    fn changed_by(&self) -> MaybeLocation {
809        self.1.changed_by()
810    }
811}
812
813impl<T: Component> DetectChangesMut for InstanceMut<'_, T> {
814    type Inner = T;
815
816    fn set_changed(&mut self) {
817        self.1.set_changed();
818    }
819
820    fn set_last_changed(&mut self, last_changed: Tick) {
821        self.1.set_last_changed(last_changed);
822    }
823
824    fn bypass_change_detection(&mut self) -> &mut Self::Inner {
825        self.1.bypass_change_detection()
826    }
827
828    fn set_added(&mut self) {
829        self.1.set_added();
830    }
831
832    fn set_last_added(&mut self, last_added: Tick) {
833        self.1.set_last_added(last_added);
834    }
835}
836
837impl<T: Component> ContainsInstance<T> for InstanceMut<'_, T> {
838    fn instance(&self) -> Instance<T> {
839        self.0
840    }
841}
842
843/// Extension trait to access [`InstanceCommands<T>`] from [`Commands`].
844///
845/// See [`InstanceCommands`] for more information.
846pub trait GetInstanceCommands<T: Kind> {
847    /// Returns the [`InstanceCommands<T>`] for an [`Instance<T>`].
848    fn instance(&mut self, instance: Instance<T>) -> InstanceCommands<'_, T>;
849}
850
851impl<T: Kind> GetInstanceCommands<T> for Commands<'_, '_> {
852    fn instance(&mut self, instance: Instance<T>) -> InstanceCommands<'_, T> {
853        InstanceCommands(self.entity(instance.entity()), PhantomData)
854    }
855}
856
857/// [`EntityCommands`] with kind semantics.
858///
859/// # Usage
860/// On its own, this type is not very useful. Instead, it is designed to be extended using traits.
861/// This allows you to design commands for a specific kind of an entity in a type-safe manner.
862///
863/// # Example
864/// ```
865/// # use bevy::prelude::*;
866/// # use moonshine_kind::prelude::*;
867///
868/// #[derive(Component)]
869/// struct Apple;
870///
871/// #[derive(Component)]
872/// struct Eat;
873///
874/// trait EatApple {
875///     fn eat(&mut self);
876/// }
877///
878/// impl EatApple for InstanceCommands<'_, Apple> {
879///     fn eat(&mut self) {
880///         info!("Crunch!");
881///         self.despawn();
882///     }
883/// }
884///
885/// fn eat_apples(apples: Query<Instance<Apple>, With<Eat>>, mut commands: Commands) {
886///     for apple in apples.iter() {
887///         commands.instance(apple).eat();
888///     }
889/// }
890///
891/// # bevy_ecs::system::assert_is_system(eat_apples);
892pub struct InstanceCommands<'a, T: Kind>(EntityCommands<'a>, PhantomData<T>);
893
894impl<'a, T: Kind> InstanceCommands<'a, T> {
895    /// Creates a new [`InstanceCommands<T>`] from [`EntityCommands`] without any validation.
896    ///
897    /// # Safety
898    /// Assumes `entity` is a valid instance of kind `T`.
899    pub unsafe fn from_entity_unchecked(entity: EntityCommands<'a>) -> Self {
900        Self(entity, PhantomData)
901    }
902
903    /// Creates a new [`InstanceCommands<T>`] from [`EntityRef`] if it contains a [`Component`] of type `T`.
904    pub fn from_entity(entity: EntityRef, commands: &'a mut Commands) -> Option<Self>
905    where
906        T: Component,
907    {
908        if entity.contains::<T>() {
909            Some(Self(commands.entity(entity.id()), PhantomData))
910        } else {
911            None
912        }
913    }
914
915    /// Returns the associated [`Instance<T>`].
916    pub fn instance(&self) -> Instance<T> {
917        // SAFE: `self.entity()` must be a valid instance of kind `T`.
918        unsafe { Instance::from_entity_unchecked(self.id()) }
919    }
920
921    /// Returns the associated [`EntityCommands`].
922    pub fn as_entity(&mut self) -> &mut EntityCommands<'a> {
923        &mut self.0
924    }
925
926    /// Equivalent to [`EntityCommands::insert`], but it returns `self` to maintain kind semantics.
927    pub fn insert(&mut self, bundle: impl Bundle) -> &mut Self {
928        self.0.insert(bundle);
929        self
930    }
931
932    /// Equivalent to [`EntityCommands::insert`], but it returns `self` to maintain kind semantics.
933    pub fn remove<U: Component>(&mut self) -> &mut Self {
934        self.0.remove::<U>();
935        self
936    }
937
938    /// Equivalent to [`EntityCommands::try_insert`], but it returns `self` to maintain kind semantics.
939    pub fn try_remove<U: Component>(&mut self) -> &mut Self {
940        self.0.try_remove::<U>();
941        self
942    }
943
944    /// Returns an [`InstanceCommands`] with a smaller lifetime.
945    ///
946    /// This is useful if you have `&mut InstanceCommands` but you need `InstanceCommands`.
947    pub fn reborrow(&mut self) -> InstanceCommands<'_, T> {
948        InstanceCommands(self.0.reborrow(), PhantomData)
949    }
950
951    /// Converts this [`InstanceCommands<T>`] into an [`InstanceCommands<U>`], given that `T` implements [`CastInto<U>`].
952    pub fn cast_into<U: Kind>(self) -> InstanceCommands<'a, U>
953    where
954        T: CastInto<U>,
955    {
956        // SAFE: `CastInto<U>` is implemented for `T`.
957        unsafe { InstanceCommands::from_entity_unchecked(self.0) }
958    }
959}
960
961impl<'a, T: Kind> From<InstanceCommands<'a, T>> for Instance<T> {
962    fn from(commands: InstanceCommands<'a, T>) -> Self {
963        commands.instance()
964    }
965}
966
967impl<'a, T: Kind> From<&InstanceCommands<'a, T>> for Instance<T> {
968    fn from(commands: &InstanceCommands<'a, T>) -> Self {
969        commands.instance()
970    }
971}
972
973impl<'a, T: Kind> Deref for InstanceCommands<'a, T> {
974    type Target = EntityCommands<'a>;
975
976    fn deref(&self) -> &Self::Target {
977        &self.0
978    }
979}
980
981impl<T: Kind> DerefMut for InstanceCommands<'_, T> {
982    fn deref_mut(&mut self) -> &mut Self::Target {
983        &mut self.0
984    }
985}
986
987impl<T: Kind> ContainsInstance<T> for InstanceCommands<'_, T> {
988    fn instance(&self) -> Instance<T> {
989        self.instance()
990    }
991}
992
993/// A macro which implements [`EntityEvent`] from an [`Instance<T>`].
994///
995/// This is useful when you have an [`EntityEvent`] which refers to its target by [`Instance<T>`].
996///
997/// ```
998/// use bevy::prelude::*;
999/// use bevy::ecs::event::EntityTrigger;
1000/// use moonshine_kind::prelude::*;
1001/// use moonshine_kind::impl_entity_event_from_instance;
1002///
1003/// #[derive(Component)]
1004/// struct Fruit;
1005///
1006/// #[derive(Event)]
1007/// #[event(trigger = EntityTrigger)]
1008/// struct Eat {
1009///     target: Instance<Fruit>
1010/// }
1011///
1012/// impl_entity_event_from_instance!(Eat { .target, .. });
1013///
1014/// let mut world = World::new();
1015/// let fruit = world.spawn_instance(Fruit).instance();
1016/// world.trigger_with(Eat { target: fruit }, EntityTrigger);
1017/// ```
1018#[macro_export]
1019macro_rules! impl_entity_event_from_instance {
1020    ($name:ident < $($gen:tt),+ $(,)? > $(where $($where:tt)+)? ) => {
1021        $crate::impl_entity_event_from_instance!($name<$($gen),+> { .instance, .. } $(where $($where)+)?);
1022    };
1023
1024    ($name:ident < $($gen:tt),+ $(,)? > { .$field:ident, .. } $(where $($where:tt)+)? ) => {
1025        impl<$($gen),+> EntityEvent for $name<$($gen),+>
1026        $(where $($where)+)? {
1027            fn event_target(&self) -> Entity {
1028                self.$field.entity()
1029            }
1030        }
1031    };
1032
1033    ($name:ident) => {
1034        $crate::impl_entity_event_from_instance!($name { .instance, .. })
1035    };
1036
1037    ($name:ident { .$field:ident, .. }) => {
1038        impl EntityEvent for $name {
1039            fn event_target(&self) -> Entity {
1040                self.$field.entity()
1041            }
1042        }
1043
1044    }
1045}
1046
1047#[test]
1048fn test_impl_entity_event_from_instance() {
1049    #![allow(unused)]
1050
1051    #[derive(Event)]
1052    struct Foo {
1053        instance: Instance<Any>,
1054    }
1055
1056    #[derive(Event)]
1057    struct Bar {
1058        inst: Instance<Any>,
1059    }
1060
1061    #[derive(Event)]
1062    struct Baz<T: Kind> {
1063        instance: Instance<T>,
1064    }
1065
1066    #[derive(Event)]
1067    struct Bat<T: Kind> {
1068        inst: Instance<T>,
1069    }
1070
1071    impl_entity_event_from_instance!(Foo);
1072    impl_entity_event_from_instance!(Bar { .inst, .. });
1073    impl_entity_event_from_instance!(Baz<T> where T: Kind);
1074    impl_entity_event_from_instance!(Bat<T> { .inst, .. } where T: Kind);
1075}