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
use std::marker;

/// Matches entities that have any of the passed components
/// with read only access to those components
///
/// It returns an element per component being None those that
/// don't exist for that entity
///
/// ```
/// # #[macro_use] extern crate rinecs_derive;
/// # use rinecs::*;
/// # #[derive(Component, Debug)]
/// # struct Position{x: f32, y: f32}
/// # #[derive(Component, Debug)]
/// # struct Velocity{x: f32, y: f32}
/// # let mut world = World::new();
/// # let entities = world.entities();
/// for (has_pos, has_vel) in entities.iter_for::<HasOr<(Position, Velocity)>>(){
///     if has_pos {
///     }
///
///     if has_vel {
///     }
/// }
/// ```
///
/// Matches all entities that have a Position a Velocity or both. pos and vel
/// will be None for entities that don't have Position or Velocity respectively
pub struct HasOr<T>{
    _marker: marker::PhantomData<T>,
}

pub trait Bools {
    type B;
}

impl<C> Bools for C {
    type B = bool;
}

//-------------------------------------------------------------------
// HasOr storage and iterators
macro_rules! impl_or_iter {
    ($intoiter_or: ident, $iter_or: ident, $storage_or: ident, $($t: ident, $s: ident),*) => (

    impl<$($t),*> FromComponent<'_, ($(<$t as super::Bools>::B),*)> for HasOr<($($t),*)> {
        fn from_component(_: ($(<$t as super::Bools>::B),*)) -> HasOr<($($t),*)>{
            HasOr{
                _marker: marker::PhantomData
            }
        }
    }

    pub struct $intoiter_or<'a, $($t),*> {
        ptr: *const HiddenFastIndex,
        end: *const HiddenFastIndex,
        storage: $storage_or<'a, $($t),*, LazyIndexGuard<'a>>,
    }


    impl<'a, $($t: 'static),*> Iterator for $intoiter_or<'a, $($t),*> {
        type Item = ($(<$t as super::Bools>::B),*);
        fn next(&mut self) -> Option<Self::Item>{
            unsafe {
                if self.ptr == self.end {
                    None
                } else {
                    let ids = &*self.ptr;
                    let ids = ids.unchecked_downcast_ref();
                    self.ptr = self.ptr.offset(1);
                    Some(self.storage.get_fast_unchecked(*ids))
                }
            }
        }

        fn size_hint(&self) -> (usize, Option<usize>) {
            let len = self.end as usize - self.ptr as usize;
            (len, Some(len))
        }
    }

    impl<'a, $($t: 'static),*> ExactSizeIterator for $intoiter_or<'a, $($t),*> {
        #[inline]
        fn len(&self) -> usize {
            self.end as usize - self.ptr as usize
        }
    }

    pub struct $iter_or<'a, 'r, $($t),*> {
        ptr: *const HiddenFastIndex,
        end: *const HiddenFastIndex,
        storage: Option<$storage_or<'a, $($t),*, &'r [HiddenFastIndex]>>,
    }

    impl<'a, 's, $($t: 'static),*> Iterator for $iter_or<'a, 's, $($t),*> {
        type Item = ($(<$t as super::Bools>::B),*);
        fn next(&mut self) -> Option<Self::Item>{
            unsafe {
                if self.ptr == self.end {
                    None
                } else {
                    let storage = self.storage.as_mut().unchecked_unwrap();
                    let ids = &*self.ptr;
                    let ids = ids.unchecked_downcast_ref();
                    self.ptr = self.ptr.offset(1);
                    Some(storage.get_fast_unchecked(*ids))
                }
            }
        }

        fn size_hint(&self) -> (usize, Option<usize>) {
            let len = self.end as usize - self.ptr as usize;
            (len, Some(len))
        }
    }

    impl<'a, 's, $($t: 'static),*> ExactSizeIterator for $iter_or<'a, 's, $($t),*> {
        #[inline]
        fn len(&self) -> usize {
            self.end as usize - self.ptr as usize
        }
    }

    #[allow(non_snake_case, dead_code)]
    pub struct $storage_or<'a, $($t),*, I> {
        ids: I,
        entities_masks: &'a [(Entity, MaskType)],
        $(
            $s: MaskType,
            $t: marker::PhantomData<$t>,
        )*
    }

    impl<'a, 'r, I, $($t: 'static),*> FastIndexExt for $storage_or<'a, $($t),*, I> {
        type FastIndex = ($(<$t as super::Bools>::B),*);
        type StaticTypeId = ($($t),*);

        fn fast_index(&self, guid: usize) -> ($(<$t as super::Bools>::B),*) {
            let entity_mask = self.entities_masks[guid].1.clone();
            ($(entity_mask.clone() & self.$s.clone() != MaskType::zero()),*)
        }
    }

    unsafe impl<'a, 'r, I, $($t),*> ReadOnlyStorage for $storage_or<'a, $($t),*, I>{}

    impl<'a, 'r, I, $($t: 'static),*> StorageRef<'r> for $storage_or<'a, $($t),*, I> {
        type Data = HasOr<($($t),*)>;
        type Component = ($(<$t as super::Bools>::B),*);

        unsafe fn get_fast_unchecked(&'r mut self, idx: ($(<$t as super::Bools>::B),*)) -> ($(<$t as super::Bools>::B),*){
            idx
        }

        #[allow(non_snake_case)]
        unsafe fn get_unchecked(&'r mut self, guid: usize) -> ($(<$t as super::Bools>::B),*){
            let entity_mask = self.entities_masks[guid].1.clone();
            ($(entity_mask.clone() & self.$s.clone() != MaskType::zero()),*)
        }

        fn contains(&self, guid: usize) -> bool{
            let entity_mask = &self.entities_masks[guid].1;
            $(entity_mask & &self.$s != MaskType::zero()) ||*
        }
    }

    impl<'a, 'r, $($t: 'static,)* I> IntoSendStorage<'r> for $storage_or<'a, $($t),*, I>
    where I: Indices
    {
        type SendStorage = $storage_or<'a, $($t),*, &'r [HiddenFastIndex]>;

        fn into_send_storage(&'r mut self) -> Self::SendStorage {
            $storage_or {
                ids: self.ids.index(self),
                entities_masks: self.entities_masks,
                $(
                    $s: self.$s.clone(),
                    $t: marker::PhantomData,
                )*
            }
        }
    }

    impl<'a, 'r, $($t: 'static,)* I> OptionStorage<'r> for $storage_or<'a, $($t),*, I>
    where I: Indices
    {
        type Iter = $iter_or<'a, 'r, $($t),*>;
        fn iter(this: Option<&'r Self>) -> Self::Iter {
            let ptr_range = this
                .map(|this| this.ids.as_ptr_range(this))
                .unwrap_or(ptr::null() .. ptr::null());
            $iter_or{
                ptr: ptr_range.start,
                end: ptr_range.end,
                storage: this.map(|this| $storage_or {
                    ids: this.ids.index(this),
                    entities_masks: this.entities_masks,
                    $(
                        $s: this.$s.clone(),
                        $t: marker::PhantomData,
                    )*
                })
            }
        }
    }

    unsafe impl<$($t),*> SafeIter<'_> for HasOr<($($t),*)> {}

    impl<'a, $($t: 'static),*> UnorderedData<'a> for HasOr<($($t),*)> {
        type Iter = $intoiter_or<'a, $($t),*>;
        type IterMut = $intoiter_or<'a, $($t),*>;
        type Components = ($($t,)*);
        type ComponentsRef = ($(<$t as super::Bools>::B),*);
        type Storage = $storage_or<'a, $($t),*, LazyIndexGuard<'a>>;

        fn query_mask<E: EntitiesStorage>(entities: &E) -> Bitmask {
            Bitmask::or($(entities.component_mask::<$t>()) | *)
        }

        fn into_iter<E: EntitiesStorage>(entities: &'a E) -> Self::Iter {
            let storage = <Self as UnorderedData>::storage(entities).unwrap();
            $intoiter_or{
                ptr: storage.ids.index(&storage).as_ptr(),
                end: unsafe{ storage.ids.index(&storage).as_ptr().add(storage.ids.index(&storage).len()) },
                storage: storage,
            }
        }

        fn into_iter_mut<E: EntitiesStorage>(entities: &'a E) -> Self::Iter {
            Self::into_iter(entities)
        }

        #[allow(non_snake_case)]
        fn storage<E: EntitiesStorage>(entities: &'a E) -> Option<Self::Storage> {
            let ids = entities.lazy_entities_for_mask(<Self as UnorderedData>::query_mask(entities));
            let entities_masks = entities.entities_ref();
            let ($($s),*) = ($(entities.component_mask::<$t>(),)*);
            Some($storage_or {
                ids,
                entities_masks,
                $(
                    $t: marker::PhantomData,
                    $s,
                )*
            })
        }
    }

    impl<$($t),*> DataAccesses for HasOr<($($t),*)> {
        fn reads() -> Vec<TypeId>{ vec![] }
        fn writes() -> Vec<TypeId>{ vec![] }
    }
)}



mod or_storage{
    use std::marker;
    use crate::storage::{StorageRef, FastIndexExt, IntoSendStorage, HiddenFastIndex, ReadOnlyStorage};
    use crate::operators::{UnorderedData, DataAccesses, SafeIter, FromComponent, OptionStorage};
    use crate::entity::{Entity, EntitiesStorage};
    use crate::bitmask::{MaskType, Bitmask};
    use super::HasOr;
    use crate::sync::{LazyIndexGuard, Indices};
    use unchecked_unwrap::UncheckedUnwrap;
    use std::any::TypeId;
    use std::ptr;
    #[cfg(components_64)]
    use num_traits::Zero;

    // impl_or_iter!(Iter1, StorageRef1, T1, S1);
    #[cfg(any(feature="storage_macros_2", feature="storage_macros_4", feature="storage_macros_8", feature="storage_macros_16"))]
    impl_or_iter!(IntoIter2, Iter2, StorageRef2, T1, S1, T2, S2);
    #[cfg(any(feature="storage_macros_4", feature="storage_macros_8", feature="storage_macros_16"))]
    impl_or_iter!(IntoIter3, Iter3, StorageRef3, T1, S1, T2, S2, T3, S3);
    #[cfg(any(feature="storage_macros_4", feature="storage_macros_8", feature="storage_macros_16"))]
    impl_or_iter!(IntoIter4, Iter4, StorageRef4, T1, S1, T2, S2, T3, S3, T4, S4);
    #[cfg(any(feature="storage_macros_8", feature="storage_macros_16"))]
    impl_or_iter!(IntoIter5, Iter5, StorageRef5, T1, S1, T2, S2, T3, S3, T4, S4, T5, S5);
    #[cfg(any(feature="storage_macros_8", feature="storage_macros_16"))]
    impl_or_iter!(IntoIter6, Iter6, StorageRef6, T1, S1, T2, S2, T3, S3, T4, S4, T5, S5, T6, S6);
    #[cfg(any(feature="storage_macros_8", feature="storage_macros_16"))]
    impl_or_iter!(IntoIter7, Iter7, StorageRef7, T1, S1, T2, S2, T3, S3, T4, S4, T5, S5, T6, S6, T7, S7);
    #[cfg(any(feature="storage_macros_8", feature="storage_macros_16"))]
    impl_or_iter!(IntoIter8, Iter8, StorageRef8, T1, S1, T2, S2, T3, S3, T4, S4, T5, S5, T6, S6, T7, S7, T8, S8);
    #[cfg(any(feature="storage_macros_16"))]
    impl_or_iter!(IntoIter9, Iter9, StorageRef9, T1, S1, T2, S2, T3, S3, T4, S4, T5, S5, T6, S6, T7, S7, T8, S8, T9, S9);
    #[cfg(any(feature="storage_macros_16"))]
    impl_or_iter!(IntoIter10, Iter10, StorageRef10, T1, S1, T2, S2, T3, S3, T4, S4, T5, S5, T6, S6, T7, S7, T8, S8, T9, S9, T10, S10);
    #[cfg(any(feature="storage_macros_16"))]
    impl_or_iter!(IntoIter11, Iter11, StorageRef11, T1, S1, T2, S2, T3, S3, T4, S4, T5, S5, T6, S6, T7, S7, T8, S8, T9, S9, T10, S10, T11, S11);
    #[cfg(any(feature="storage_macros_16"))]
    impl_or_iter!(IntoIter12, Iter12, StorageRef12, T1, S1, T2, S2, T3, S3, T4, S4, T5, S5, T6, S6, T7, S7, T8, S8, T9, S9, T10, S10, T11, S11, T12, S12);
    #[cfg(any(feature="storage_macros_16"))]
    impl_or_iter!(IntoIter13, Iter13, StorageRef13, T1, S1, T2, S2, T3, S3, T4, S4, T5, S5, T6, S6, T7, S7, T8, S8, T9, S9, T10, S10, T11, S11, T12, S12, T13, S13);
    #[cfg(any(feature="storage_macros_16"))]
    impl_or_iter!(IntoIter14, Iter14, StorageRef14, T1, S1, T2, S2, T3, S3, T4, S4, T5, S5, T6, S6, T7, S7, T8, S8, T9, S9, T10, S10, T11, S11, T12, S12, T13, S13, T14, S14);
    #[cfg(any(feature="storage_macros_16"))]
    impl_or_iter!(IntoIter15, Iter15, StorageRef15, T1, S1, T2, S2, T3, S3, T4, S4, T5, S5, T6, S6, T7, S7, T8, S8, T9, S9, T10, S10, T11, S11, T12, S12, T13, S13, T14, S14, T15, S15);
    #[cfg(any(feature="storage_macros_16"))]
    impl_or_iter!(IntoIter16, Iter16, StorageRef16, T1, S1, T2, S2, T3, S3, T4, S4, T5, S5, T6, S6, T7, S7, T8, S8, T9, S9, T10, S10, T11, S11, T12, S12, T13, S13, T14, S14, T15, S15, T16, S16);
}