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
use crate::{IntoSendStorage, entity::EntitiesStorage, storage::FastIndexExt, sync::{StorageWriteGuard, OrderedIndexGuard}};
use std::marker;
use crate::Component;
use crate::ComponentSend;
use crate::Bitmask;
use super::{ChangesOrderedData, OrderedData, SafeIter};
use crate::storage::{StorageRef, HierarchicalStorage, IntoOrderedIterMut,  IntoOrderedChangesIter};
use crate::utils::{delete_lifetime, delete_lifetime_mut};
use crate::idtree;
use std::ops::DerefMut;
use hashbrown::HashSet;

/// Operator over hierarchical components that will select an entity's
/// component and it's parent for read and write
///
/// ```
/// # #[macro_use] extern crate rinecs_derive;
/// # use rinecs::*;
/// # #[derive(HierarchicalComponent, Debug)]
/// # struct Position{x: f32, y: f32}
/// # let mut world = World::new();
/// # let mut entities = world.entities();
/// for (pos, parent_pos) in entities.ordered_iter_for_mut::<WriteAndParent<Position>>(){
///     if let Some(parent_pos) = parent_pos {
///         pos.x += parent_pos.x;
///         pos.y += parent_pos.y;
///     }
/// }
/// ```
///
/// Will accumulate the positions of each object to that of their parents
/// so in the end i'll object will end up with the absolute position in the world
pub struct WriteAndParent<'a, T: Component>{
    _marker: marker::PhantomData<&'a T>,
}

pub struct ParentStorageWrite<'a, S, BS, T>
where S: HierarchicalStorage<'a,T> + 'a,
    BS: DerefMut<Target = S>,
    T: Component
{
    storage: BS,
    _marker: marker::PhantomData<&'a T>,
}

impl<'a, S, BS, T> FastIndexExt for ParentStorageWrite<'a, S, BS, T>
where S: HierarchicalStorage<'a,T> + 'a,
    BS: DerefMut<Target = S>,
    T: Component
{
    type FastIndex = idtree::NodeId;
    type StaticTypeId = T;

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

impl<'a, 'r, S, BS, T> StorageRef<'r> for ParentStorageWrite<'a, S, BS, T>
where S: HierarchicalStorage<'a,T> + 'a,
    BS: DerefMut<Target = S>,
    T: Component
{
    type Component = (&'r mut T, Option<&'r T>);
    type Data = WriteAndParent<'a, T>;

    unsafe fn get_fast_unchecked(&'r mut self, idx: idtree::NodeId) -> Self::Component {
        let mut node = self.storage.fast_get_node_mut(idx);
        let parent = node.parent().map(|p| delete_lifetime(&p as &T));
        let node = delete_lifetime_mut(&mut node as &mut T);
        (node, parent)
    }

    unsafe fn get_unchecked(&'r mut self, guid: usize) -> Self::Component {
        let mut node = self.storage.get_node_mut(guid);
        let parent = node.parent().map(|p| delete_lifetime(&p as &T));
        let node = delete_lifetime_mut(&mut node as &mut T);
        (node, parent)
    }

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

impl<'a, 'r, T> IntoSendStorage<'r> for ParentStorageWrite<'a, <T as Component>::Storage, StorageWriteGuard<'a, T>, T>
where
    'a: 'r,
    T: Component,
    <T as Component>::Storage: HierarchicalStorage<'a,T> + 'a
{
    type SendStorage = ParentStorageWrite<'a, <T as Component>::Storage, &'r mut <T as Component>::Storage, T>;

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

pub struct WriteAndParentIter<'a, T: Component, I>
    where for<'b> <T as Component>::Storage: HierarchicalStorage<'b,T>,
{
    it: Option<I>,
    marker: marker::PhantomData<&'a T>,
}

impl<'a,T,I> Iterator for WriteAndParentIter<'a, T, I>
    where T: Component,
        for<'b> <T as Component>::Storage: HierarchicalStorage<'b,T>,
        I: Iterator<Item = idtree::NodeRefMut<'a, T>>,
{
    type Item = (&'a mut T, Option<&'a T>);
    fn next(&mut self) -> Option<(&'a mut T, Option<&'a T>)>{
        self.it.as_mut().and_then(|it| it.next().map(|mut n| {
            let n_ref = unsafe{ delete_lifetime_mut(&mut n as &mut T) };
            let p = unsafe{ n.parent().map(|p| delete_lifetime(p as &T)) };
            (n_ref, p)
        }))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.it.as_ref().map(|it| it.size_hint()).unwrap_or((0, None))
    }
}

unsafe impl<T: Component> SafeIter<'_> for WriteAndParent<'_, T>{}

impl<'a, T: Component> OrderedData<'a> for WriteAndParent<'a,T>
    where for<'b> <T as Component>::Storage: HierarchicalStorage<'b,T>,
          for<'b> StorageWriteGuard<'b, T>: IntoOrderedIterMut
{
    type Iter = WriteAndParentIter<'a, T, <StorageWriteGuard<'a, T> as IntoOrderedIterMut>::OrderedIterMut>;
    type Components = T;
    type ComponentsRef = (&'a mut T, Option<&'a T>);
    type Storage = ParentStorageWrite<'a,
        <T as Component>::Storage,
        StorageWriteGuard<'a, T>,
        Self::Components>;
    fn query_mask<E: EntitiesStorage>(entities: &E) -> Bitmask{
        Bitmask::has(entities.component_mask::<T>())
    }

    fn into_iter<E: EntitiesStorage>(entities: &'a E) -> Self::Iter{
        WriteAndParentIter{
            it: entities.storage_mut::<T>().map(|s| s.into_ordered_iter_mut()),
            marker: marker::PhantomData
        }
    }

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

    fn ordered_ids<S: FastIndexExt, E: EntitiesStorage>(entities: &'a E, query_mask: Bitmask, unordered_storage: &S) -> OrderedIndexGuard<'a>{
        entities.ordered_entities_for::<T,S>(query_mask, unordered_storage)
    }
}

impl<'a, T: ComponentSend> ChangesOrderedData<'a> for WriteAndParent<'a, T>
    where for<'b> <T as Component>::Storage: HierarchicalStorage<'b,T>,
        for<'b> StorageWriteGuard<'b, T>: IntoOrderedIterMut,
        StorageWriteGuard<'a, T>: IntoOrderedChangesIter<'a, T, OrderedChangesItem = idtree::NodeRefMut<'a, T>>,
{
    type SubStorage = ParentStorageWrite<'a,
        <StorageWriteGuard<'a, T> as IntoOrderedChangesIter<'a, T>>::RawSubStorage,
        <StorageWriteGuard<'a, T> as IntoOrderedChangesIter<'a, T>>::SubStorage,
        Self::Components>;

    fn extend_changes<F, E: EntitiesStorage>(entities: &'a E, mut f: F)
    where F: FnMut(Self::ComponentsRef) -> bool
    {
        if let Some(storage) = entities.storage_mut::<T>() {
            storage.ordered_extend_changes(|mut n| {
                let n_ref = unsafe{ delete_lifetime_mut(&mut n as &mut T) };
                let p = unsafe{ n.parent().map(|p| delete_lifetime(p as &T)) };
                f((n_ref, p))
            })
        }
    }

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

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

        Some((storage, changes))
    }
}