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
#[cfg(feature="parking_lot")]
use parking_lot::*;
#[cfg(not(feature="parking_lot"))]
use std::sync::RwLockReadGuard;
use sync::ReadGuardRef;
use std::marker;
use ::Component;
use ::ComponentSend;
use ::ComponentThreadLocal;
use ::Bitmask;
use ::NToOneComponent;
use ::NToOneComponentSend;
use ::NToOneComponentThreadLocal;
use entity::{Entities, EntitiesThreadLocal};
use super::{FromComponent, UnorderedData, UnorderedDataLocal};
use storage::{Storage, StorageRef};
#[cfg(feature = "multithreaded")]
use super::ParUnorderedData;
#[cfg(feature = "multithreaded")]
use super::read::ReadStorageParIter;
use std::borrow::Borrow;
use std::ops::Deref;

/// Operator that matches entities that contain a component through a reference
///
/// A reference to another entity is any component that implements
/// `Deref<Target=Entity>`
///
/// The first parameter to ReadRef indicates the reference component the
/// second the referenced
///
/// ```
/// # #[macro_use] extern crate rinecs_derive;
/// # use rinecs::*;
/// #[derive(Component, Debug)]
/// struct Position(f32,f32);
///
/// #[derive(Component, Debug)]
/// struct GeometryRef(Entity);
///
/// #[derive(Component, Debug)]
/// struct Geometry;
///
/// # let mut world = World::new();
/// # world.register::<GeometryRef>();
/// # world.register::<Geometry>();
/// # world.register::<Position>();
///
/// let geom = world.new_entity()
///     .add(Geometry)
///     .build();
///
/// world.new_entity()
///     .add(GeometryRef(geom))
///     .add(Position(0., 0.))
///     .build();
///
/// world.new_entity()
///     .add(GeometryRef(geom))
///     .add(Position(10., 10.))
///     .build();
///
/// # let entities = world.entities();
/// for (geom, pos) in entities.iter_for::<(ReadRef<GeometryRef, Geometry>, Read<Position>)>(){
///     // draw geometry at position
/// }
/// ```
///
/// Will select all entities that reference a Geometry through a GeometryRef
/// and have a position then draw the geometry at that position.
///
/// This allow to have only one copy of the geometry that is referenced by multiple
/// entities
///
/// When deriving Component for a tuple struct with only one element
/// it'll also derive Deref for that element so in this case
/// GeometryRef automatically can be used with ReadRef
pub struct ReadRef<'a, T: 'a + NToOneComponent, Ref: 'a + Component>{
    _marker: marker::PhantomData<&'a T>,
    component: &'a Ref,
}

impl<'a, T: 'a + NToOneComponent, Ref: 'a + Component> FromComponent<'a, &'a Ref> for ReadRef<'a, T, Ref>{
    fn from_component(component: &'a Ref) -> ReadRef<'a,T,Ref>{
        ReadRef{
            component,
            _marker: marker::PhantomData
        }
    }
}

impl<'a, T: 'a + NToOneComponent, Ref: 'a + Component> Deref for ReadRef<'a, T, Ref>{
    type Target = Ref;
    fn deref(&self) -> &Ref{
        self.component
    }
}
pub struct StorageReadRef<'a, S, T, SRef, Ref>
    where S: Storage<'a,T> + 'a,
          T: 'a + NToOneComponentSend,
          SRef: Storage<'a,Ref> + 'a,
          Ref: 'a + Component
{
    storage: RwLockReadGuard<'a, S>,
    storage_ref: RwLockReadGuard<'a, SRef>,
    _marker: marker::PhantomData<&'a T>,
    _marker_ref: marker::PhantomData<&'a Ref>,
}

impl<'a, S, T, SRef, Ref> StorageRef<'a, Option<<SRef as Storage<'a,Ref>>::Get>> for StorageReadRef<'a, S, T, SRef, Ref>
    where S: Storage<'a,T> + 'a,
          T: 'a + NToOneComponentSend,
          SRef: Storage<'a,Ref> + 'a,
          Ref: 'a + ComponentSend + Send,
          <S as Storage<'a,T>>::Get: Borrow<T>,
{
    fn get(&self, guid: usize) -> Option<<SRef as Storage<'a,Ref>>::Get>{
        unsafe{
            let t = self.storage.get(guid);
            if self.storage_ref.contains(t.borrow().guid()) {
                let tref = self.storage_ref.get(t.borrow().guid());
                Some(tref)
            }else{
                None
            }
        }
    }

    fn contains(&self, guid: usize) -> bool{
        self.storage.contains(guid)
    }
}

pub struct ReadRefIter<'a, S, SRef, Ref>{
    _ids: ::IndexGuard<'a>,
    ptr: *const usize,
    end: *const usize,
    storage: S,
    _markersref: marker::PhantomData<SRef>,
    _markerref: marker::PhantomData<Ref>,
}


impl<'a, S, SRef, Ref> Iterator for ReadRefIter<'a, S, SRef, Ref>
    where S: StorageRef<'a, Option<<SRef as Storage<'a,Ref>>::Get>>,
          SRef: Storage<'a,Ref> + 'a,
{
    type Item = Option<<SRef as Storage<'a,Ref>>::Get>;
    fn next(&mut self) -> Option<Self::Item>{
        unsafe {
            if self.ptr == self.end {
                None
            } else {
                let guid = *self.ptr;
                self.ptr = self.ptr.offset(1);
                Some(self.storage.get(guid))
            }
        }
    }
}


impl<'a, T, Ref> UnorderedData<'a> for ReadRef<'a,T,Ref>
    where T: 'a + NToOneComponentSend,
          Ref: Component + Send,
          <<T as Component>::Storage as Storage<'a, T>>::Get: Borrow<T>
{
    type Iter = ReadRefIter<'a, Self::Storage, <Ref as Component>::Storage, Ref>;
    type Components = Option<Ref>;
    type ComponentsRef = Option<<<Ref as Component>::Storage as Storage<'a, Ref>>::Get>;
    type Storage = StorageReadRef<'a, <T as Component>::Storage, T, <Ref as Component>::Storage, Ref>;
    fn components_mask(entities: Entities<'a>) -> Bitmask {
        Bitmask::has(entities.components_mask::<T>())
    }

    fn into_iter(entities: Entities<'a>) -> Self::Iter{
        let ids = entities.entities_for_mask(<Self as UnorderedData>::components_mask(entities));
        ReadRefIter{
            ptr: ids.index.as_ptr(),
            end: unsafe{ ids.index.as_ptr().add(ids.index.len()) },
            _ids: ids,
            storage: <Self as UnorderedData>::storage(entities),
            _markersref: marker::PhantomData,
            _markerref: marker::PhantomData,
        }
    }

    fn storage(entities: Entities<'a>) -> Self::Storage{
        StorageReadRef{
            storage: entities.storage::<T>()
                .unwrap_or_else(|| panic!("Trying to use unregistered storage for component {}", T::type_name())),
            storage_ref: entities.storage::<Ref>()
                .unwrap_or_else(|| panic!("Trying to use unregistered storage for component {}", Ref::type_name())),
            _marker: marker::PhantomData,
            _marker_ref: marker::PhantomData,
        }
    }
}


#[cfg(feature = "multithreaded")]
impl<'a, T, Ref> ParUnorderedData<'a> for ReadRef<'a,T,Ref>
    where T: 'a + NToOneComponentSend,
          Ref: Component + Send,
          <<T as Component>::Storage as Storage<'a, T>>::Get: Borrow<T>
{
    type ParIter = ReadStorageParIter<'a, Self::ComponentsRef, Self::Storage>;

    fn into_pariter(entities: Entities<'a>) -> Self::ParIter{
        let ids = entities.entities_for_mask(<Self as UnorderedData>::components_mask(entities));
        ReadStorageParIter::new(ids, <Self as UnorderedData>::storage(entities))
    }
}

pub struct StorageReadRefLocal<'a, S, T, SRef, Ref>
    where S: Storage<'a,T> + 'a,
          T: 'a + NToOneComponentThreadLocal,
          SRef: Storage<'a,Ref> + 'a,
          Ref: 'a + Component
{
    storage: ReadGuardRef<'a, S>,
    storage_ref: ReadGuardRef<'a, SRef>,
    _marker: marker::PhantomData<&'a T>,
    _marker_ref: marker::PhantomData<&'a Ref>,
}

impl<'a, S, T, SRef, Ref> StorageRef<'a, Option<<SRef as Storage<'a,Ref>>::Get>> for StorageReadRefLocal<'a, S, T, SRef, Ref>
    where S: Storage<'a,T> + 'a,
          T: 'a + NToOneComponentThreadLocal,
          SRef: Storage<'a, Ref> + 'a,
          Ref: 'a + ComponentThreadLocal,
          <S as Storage<'a,T>>::Get: Borrow<T>,
{
    fn get(&self, guid: usize) -> Option<<SRef as Storage<'a, Ref>>::Get> {
        unsafe{
            let t = self.storage.get(guid);
            if self.storage_ref.contains(t.borrow().guid()){
                let tref = self.storage_ref.get(t.borrow().guid());
                Some(tref)
            }else{
                None
            }
        }
    }

    fn contains(&self, guid: usize) -> bool{
        self.storage.contains(guid)
    }
}

impl<'a, T, Ref> UnorderedDataLocal<'a> for ReadRef<'a,T,Ref>
    where T: 'a + NToOneComponentThreadLocal,
          Ref: Component,
          <<T as Component>::Storage as Storage<'a, T>>::Get: Borrow<T>
{
    type Iter = ReadRefIter<'a, Self::Storage, <Ref as Component>::Storage, Ref>;
    type Components = Option<Ref>;
    type ComponentsRef = Option<<<Ref as Component>::Storage as Storage<'a, Ref>>::Get>;
    type Storage = StorageReadRefLocal<'a, <T as Component>::Storage, T, <Ref as Component>::Storage, Ref>;
    fn components_mask_thread_local(entities: EntitiesThreadLocal<'a>) -> Bitmask {
        Bitmask::has(entities.components_mask::<T>())
    }

    fn into_iter_thread_local(entities: EntitiesThreadLocal<'a>) -> Self::Iter{
        let ids = entities.entities_for_mask(<Self as UnorderedDataLocal>::components_mask_thread_local(entities));
        ReadRefIter{
            ptr: ids.index.as_ptr(),
            end: unsafe{ ids.index.as_ptr().add(ids.index.len()) },
            _ids: ids,
            storage: <Self as UnorderedDataLocal>::storage_thread_local(entities),
            _markersref: marker::PhantomData,
            _markerref: marker::PhantomData,
        }
    }

    fn storage_thread_local(entities: EntitiesThreadLocal<'a>) -> Self::Storage{
        StorageReadRefLocal{
            storage: entities.storage_thread_local::<T>()
                .unwrap_or_else(|| panic!("Trying to use unregistered storage for component {}", T::type_name())),
            storage_ref: entities.storage_thread_local::<Ref>()
                .unwrap_or_else(|| panic!("Trying to use unregistered storage for component {}", Ref::type_name())),
            _marker: marker::PhantomData,
            _marker_ref: marker::PhantomData,
        }
    }
}