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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
use crate::{
    entity::EntitiesStorage,
    storage::{FastIndexExt, IntoSendStorage},
    sync::StorageWriteGuard,
};
use std::marker;
use crate::Component;
use crate::ComponentSend;
use crate::Bitmask;
use crate::entity::{Entities, Entity};
use super::{ChangesData, DataAccesses, FromComponent, IterOptionWrapper, OptionStorageMut, SafeIter, UnorderedData};
#[cfg(feature="parallel_iter")]
use super::ParOptionStorageMut;
use crate::storage::{Storage, StorageRef, IntoIterMut, IntoChangesIter};
#[cfg(feature = "parallel_iter")]
use crate::storage::ParStorage;
use std::ops::{Deref, DerefMut};
use std::borrow::{Borrow, BorrowMut};
use hashbrown::HashSet;
use streaming_iterator::{StreamingIterator, StreamingIteratorMut};
use std::any::TypeId;

type GetMut<'a, T> = <<T as Component>::Storage as Storage<'a, T>>::GetMut;
type DerefTarget<'a, T> = <<T as Component>::Storage as Storage<'a, T>>::DerefTarget;

/// Operator that matches all entity's that contain this component
/// for read and write access
///
/// ```
/// # #[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 mut entities = world.entities();
/// for pos in entities.iter_for_mut::<Write<Position>>(){
///     //...
/// }
/// ```
///
/// Will iterate over all position components
pub struct Write<'a, T: Component>
where for<'s> <T as Component>::Storage: Storage<'s, T>
{
    component: GetMut<'a,T>,
}

impl<'a, T: Component> FromComponent<'a, GetMut<'a,T>> for Write<'a,T>
where for<'s> <T as Component>::Storage: Storage<'s, T>
{
    fn from_component(component: GetMut<'a,T>) -> Write<'a,T>{
        Write{
            component
        }
    }
}

impl<'a, T: Component> Deref for Write<'a, T>
where
    GetMut<'a,T>: Borrow<DerefTarget<'a,T>>,
    for<'s> <T as Component>::Storage: Storage<'s, T>
{
    type Target = DerefTarget<'a,T>;
    fn deref(&self) -> &DerefTarget<'a,T>{
        self.component.borrow()
    }
}

impl<'a, T: Component> DerefMut for Write<'a, T>
where
    GetMut<'a,T>: BorrowMut<DerefTarget<'a,T>>,
    for<'s> <T as Component>::Storage: Storage<'s, T>
{
    fn deref_mut(&mut self) -> &mut DerefTarget<'a,T>{
        self.component.borrow_mut()
    }
}

//TODO Remove S parameter and change it with T::Storage but impl of ChangesData fails then
// cause the storage is not DerefMut<T::Storage>
pub struct StorageWrite<'a, S, T, BS: DerefMut<Target=S>>{
    pub(crate) storage: BS,
    pub(crate) _marker: marker::PhantomData<&'a T>,
}

impl<'a, S, T, BS> FastIndexExt for StorageWrite<'a, S, T, BS>
where
    for<'b> <T as Component>::Storage: Storage<'b, T>,
    S: for<'s> Storage<'s,T>,
    BS: DerefMut<Target=S>,
    T: Component
{
    type FastIndex = usize;
    type StaticTypeId = T;

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

impl<'a, 'r, S, T, BS> StorageRef<'r> for StorageWrite<'a, S, T, BS>
where
    for<'b> <T as Component>::Storage: Storage<'b, T>,
    S: for<'s> Storage<'s,T>,
    BS: DerefMut<Target=S>,
    T: Component,
{
    type Data = Write<'a,T>;
    type Component = <S as Storage<'r,T>>::GetMut;

    unsafe fn get_fast_unchecked(&'r mut self, idx: usize) -> <S as Storage<'r,T>>::GetMut{
        self.storage.fast_get_mut(idx)
    }

    unsafe fn get_unchecked(&'r mut self, guid: usize) -> <S as Storage<'r,T>>::GetMut{
        self.storage.get_mut(guid)
    }

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

impl<'a, 'r, S, T, BS> IntoSendStorage<'r> for StorageWrite<'a, S, T, BS>
where
    for<'b> T::Storage: Storage<'b, T>,
    S: for<'s> Storage<'s,T> + 'r,
    BS: DerefMut<Target=S>,
    T: Component,
{
    type SendStorage = StorageWrite<'a, S, T, &'r mut S>;

    fn into_send_storage(&'r mut self) -> Self::SendStorage {
        StorageWrite {
            storage: &mut self.storage,
            _marker: marker::PhantomData,
        }
    }
}

impl<'a, 'r, S, T, BS> OptionStorageMut<'r> for StorageWrite<'a, S, T, BS>
where
    for<'s> T::Storage: Storage<'s, T>,
    S: for<'s> Storage<'s,T> + 'r,
    BS: DerefMut<Target=S>,
    T: Component,
{
    type IterMut = IterOptionWrapper<<S as Storage<'r, T>>::IterMut>;

    fn iter_mut(this: Option<&'r mut Self>) -> Self::IterMut {
        IterOptionWrapper{ it: this.map(|s| s.storage.iter_mut()) }
    }
}

pub struct EntitiesWriteIter<'r, S, T, E>
where S: Storage<'r, T>
{
    storage: &'r mut S,
    entities: E,
    current: Option<<S as Storage<'r, T>>::GetMut>,
}

impl<'r, S, T, E> StreamingIterator for EntitiesWriteIter<'r, S, T, E>
where
    S: Storage<'r, T>,
    T: Component,
    E: Iterator<Item = Entity>,
    <S as Storage<'r, T>>::DerefTarget: Sized,
    <S as Storage<'r, T>>::GetMut: DerefMut<Target = <S as Storage<'r, T>>::DerefTarget>
{
    type Item = <S as Storage<'r, T>>::DerefTarget;

    // fn advance(&mut self) {
    //     self.current = self.entities.next().map(|e| if self.storage.contains(e.guid()){
    //         Some(unsafe{ self.storage.get_mut(e.guid()) })
    //     }else{
    //         None
    //     })
    // }

    fn advance(&mut self) {
        while let Some(e) = self.entities.next() {
            if self.storage.contains(e.guid()){
                self.current = Some(unsafe{ self.storage.get_mut(e.guid()) });
                return;
            }
        }
        self.current = None;
    }

    fn get(&self) -> Option<&Self::Item> {
        self.current.as_deref()
    }
}


impl<'r, S, T, E> StreamingIteratorMut for EntitiesWriteIter<'r, S, T, E>
where
    S: Storage<'r, T>,
    T: Component,
    E: Iterator<Item = Entity>,
    <S as Storage<'r, T>>::DerefTarget: Sized,
    <S as Storage<'r, T>>::GetMut: DerefMut<Target = <S as Storage<'r, T>>::DerefTarget>
{
    fn get_mut(&mut self) -> Option<&mut Self::Item> {
        self.current.as_deref_mut()
    }
}

#[cfg(feature = "parallel_iter")]
impl<'a, 'r, T, S, BS> ParOptionStorageMut<'r> for StorageWrite<'a, S, T, BS>
where
    for<'b> T::Storage: Storage<'b, T>,
    S: for<'s> Storage<'s,T> + 'r,
    BS: DerefMut<Target=S>,
    S: ParStorage<'r,T>,
    T: Component
{
    type ParIterMut = IterOptionWrapper<<S as ParStorage<'r, T>>::ParIterMut>;

    fn par_iter_mut(this: Option<&'r mut Self>) -> Self::ParIterMut {
        IterOptionWrapper{ it: this.map(|this| this.storage.par_iter_mut()) }
    }
}

unsafe impl<T: Component> SafeIter<'_> for Write<'_, T>
where for<'s> <T as Component>::Storage: Storage<'s, T>{}

impl<'a, T: Component> UnorderedData<'a> for Write<'a,T>
where
    StorageWriteGuard<'a, T>: IntoIterMut,
    for<'s> <T as Component>::Storage: Storage<'s, T>
{
    type Iter = IterOptionWrapper<<StorageWriteGuard<'a, T> as IntoIterMut>::IterMut>;
    type IterMut = IterOptionWrapper<<StorageWriteGuard<'a, T> as IntoIterMut>::IterMut>;
    type Components = T;
    type ComponentsRef = <<T as Component>::Storage as Storage<'a, T>>::GetMut;
    type Storage = StorageWrite<'a,
        <T as Component>::Storage,
        Self::Components,
        StorageWriteGuard<'a, T>
    >;

    fn query_mask<E: EntitiesStorage>(entities: &E) -> Bitmask{
        Bitmask::has(entities.component_mask::<T>())
    }

    fn into_iter<E: EntitiesStorage>(entities: &'a E) -> Self::Iter{
        IterOptionWrapper {
            it: entities.storage_mut::<T>()
                .map(|s| s.into_iter_mut())
        }
    }

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

    fn storage<E: EntitiesStorage>(entities: &'a E) -> Option<Self::Storage>{
        Some(StorageWrite{
            storage: entities.storage_mut::<T>()?,
            _marker: marker::PhantomData,
        })
    }
}

impl<'a, T: Component> DataAccesses for Write<'a, T>
where for<'s> <T as Component>::Storage: Storage<'s, T>
{
    fn reads() -> Vec<TypeId>{ vec![] }
    fn writes() -> Vec<TypeId>{ vec![TypeId::of::<T>()] }
}


impl<'a, T: ComponentSend> ChangesData<'a> for Write<'a, T>
where
    for<'b> <T as Component>::Storage: Storage<'b,T>,
    for<'b> StorageWriteGuard<'b, T>: IntoIterMut,
    StorageWriteGuard<'a, T>: IntoChangesIter<'a, T, ChangesItem = <<T as Component>::Storage as Storage<'a, T>>::GetMut>,
{
    type SubStorage = StorageWrite<'a,
        <StorageWriteGuard<'a, T> as IntoChangesIter<'a, T>>::RawSubStorage,
        Self::Components,
        <StorageWriteGuard<'a, T> as IntoChangesIter<'a, T>>::SubStorage
    >;

    fn extend_changes<F>(entities: &'a Entities, f: F)
    where F: FnMut(Self::ComponentsRef) -> bool
    {
        if let Some(storage) = entities.storage_mut::<T>() {
            storage.extend_changes(f)
        }

    }

    unsafe fn storage_and_changes(entities: &'a Entities) -> Option<(Self::SubStorage, &'a mut HashSet<usize>)> {
        let (storage, changes) = entities.storage_mut::<T>()?
            .into_storage_and_changes();

        let storage = StorageWrite{
            storage,
            _marker: marker::PhantomData,
        };

        Some((storage, changes))
    }
}


// impl<'a, T: ComponentThreadLocal> ChangesDataLocal<'a> for Write<'a, T>
// where
//     for<'b> <T as Component>::Storage: Storage<'b,T>,
//     for<'b> StorageWriteGuard<'b, T>: IntoIterMut,
//     StorageWriteGuard<'a, T>: IntoChangesIter<'a, T, ChangesItem = <<T as Component>::Storage as Storage<'a, T>>::GetMut>,
// {
//     type SubStorage = StorageWrite<'a,
//         <StorageWriteGuard<'a, T> as IntoChangesIter<'a, T>>::RawSubStorage,
//         <StorageWriteGuard<'a, T> as IntoChangesIter<'a, T>>::SubStorage,
//         Self::Components>;

//     fn extend_changes<F>(entities: EntitiesThreadLocal<'a>, f: F)
//     where F: FnMut(Self::ComponentsRef) -> bool
//     {
//         if let Some(storage) = entities.storage_thread_local_mut::<T>() {
//             storage.extend_changes(f)
//         }

//     }

//     unsafe fn storage_and_changes(entities: EntitiesThreadLocal<'a>) -> Option<(Self::SubStorage, &mut HashSet<usize>)>{
//         let (storage, changes) = entities.storage_thread_local_mut::<T>()?
//             .into_storage_and_changes();

//         let storage = StorageWrite{
//             storage,
//             _marker: marker::PhantomData,
//         };

//         Some((storage, changes))
//     }
// }