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
use std::{collections::VecDeque, marker::PhantomData};

use hecs::{Component, Entity, QueryBorrow};
use hecs_schedule::GenericWorld;
use smallvec::{smallvec, SmallVec};

use crate::{Child, Hierarchy, Parent};

const STACK_SIZE: usize = 64;

/// Iterates children along with Query `Q`. Children who do not satisfy `Q` will be skipped.
/// Count is known in advanced and will not fold iterator.
pub struct ChildrenIter<'a, T: Component> {
    query: QueryBorrow<'a, &'a Child<T>>,
    remaining: usize,
    current: Option<Entity>,
    marker: PhantomData<T>,
}

impl<'a, T: Component> ChildrenIter<'a, T> {
    pub(crate) fn new<W: GenericWorld>(
        world: &'a W,
        num_children: usize,
        current: Option<Entity>,
    ) -> Self {
        Self {
            query: world.try_query().unwrap(),
            remaining: num_children,
            current,
            marker: PhantomData,
        }
    }
}

impl<'a, T> Iterator for ChildrenIter<'a, T>
where
    T: Component,
{
    type Item = Entity;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }

        self.remaining -= 1;

        let current = self.current?;
        let data = self.query.view().get(current)?;

        self.current = Some(data.next);
        Some(current)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }

    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.remaining
    }
}

pub struct AncestorIter<'a, T: Component> {
    query: QueryBorrow<'a, &'a Child<T>>,
    current: Entity,
    marker: PhantomData<T>,
}

impl<'a, T: Component> AncestorIter<'a, T> {
    pub(crate) fn new<W: GenericWorld>(world: &'a W, current: Entity) -> Self {
        Self {
            query: world.try_query().unwrap(),
            current,
            marker: PhantomData,
        }
    }
}

impl<'a, T: Component> Iterator for AncestorIter<'a, T> {
    type Item = Entity;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(child) = self.query.view().get(self.current) {
            self.current = child.parent;
            Some(child.parent)
        } else {
            None
        }
    }
}

#[derive(Debug)]
struct StackFrame {
    current: Entity,
    remaining: usize,
}

pub struct DepthFirstIterator<'a, T: Component> {
    children: QueryBorrow<'a, &'a Child<T>>,
    parents: QueryBorrow<'a, &'a Parent<T>>,
    marker: PhantomData<T>,
    /// Since StackFrame is so small, use smallvec optimizations
    stack: SmallVec<[StackFrame; STACK_SIZE]>,
}

impl<'a, T: Component> DepthFirstIterator<'a, T> {
    pub(crate) fn new<W: GenericWorld>(world: &'a W, root: Entity) -> Self {
        let children = world.try_query().unwrap();
        let mut parents = world.try_query::<&Parent<T>>().unwrap();

        let stack = parents
            .view()
            .get(root)
            .and_then(|parent| {
                let first_child = parent.first_child(world).ok()?;
                Some(smallvec![StackFrame {
                    current: first_child,
                    remaining: parent.num_children,
                }])
            })
            .unwrap_or_default();

        Self {
            children,
            parents,
            stack,
            marker: PhantomData,
        }
    }
}

pub struct DepthFirstVisitor<'a, W, T: Component, F> {
    world: &'a W,
    children: QueryBorrow<'a, &'a Child<T>>,
    parents: QueryBorrow<'a, &'a Parent<T>>,
    marker: PhantomData<T>,
    /// Since StackFrame is so small, use smallvec optimizations
    stack: SmallVec<[StackFrame; STACK_SIZE]>,
    accept: F,
}

impl<'a, F: Fn(&W, Entity) -> bool + Component, W: GenericWorld, T: Component>
    DepthFirstVisitor<'a, W, T, F>
{
    pub(crate) fn new(world: &'a W, root: Entity, accept: F) -> Self {
        let children = world.try_query().unwrap();
        let mut parents = world.try_query::<&Parent<T>>().unwrap();

        let stack = parents
            .view()
            .get(root)
            .and_then(|parent| {
                if (accept)(world, root) {
                    let first_child = parent.first_child(world).ok()?;
                    Some(smallvec![StackFrame {
                        current: first_child,
                        remaining: parent.num_children,
                    }])
                } else {
                    None
                }
            })
            .unwrap_or_default();

        Self {
            world,
            accept,
            children,
            parents,
            stack,
            marker: PhantomData,
        }
    }
}

impl<'a, F: Fn(&W, Entity) -> bool + Component, W: GenericWorld, T: Component> Iterator
    for DepthFirstVisitor<'a, W, T, F>
{
    type Item = Entity;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            // The the topmost stackframe
            let top = self.stack.last_mut()?;
            // There are more children in current stackframe
            if top.remaining > 0 {
                let current = top.current;

                let children = self.children.view();
                let data = children.get(top.current).unwrap();

                // Go to the next child in the linked list of children
                top.current = data.next;
                top.remaining -= 1;

                if !(self.accept)(self.world, current) {
                    continue;
                }

                // If current is a parent, push a new stack frame with the first child
                if let Some(parent) = self.parents.view().get(current) {
                    self.stack.push(StackFrame {
                        current: parent.view_first_child(&children).unwrap(),
                        remaining: parent.num_children,
                    })
                }

                return Some(current);
            } else {
                // End of linked list of children, pop stack frame
                self.stack.pop();
            }
        }
    }
}

impl<'a, T: Component> Iterator for DepthFirstIterator<'a, T> {
    type Item = Entity;

    fn next(&mut self) -> Option<Self::Item> {
        // The the topmost stackframe
        let top = self.stack.last_mut()?;

        // There are more children in current stackframe
        if top.remaining > 0 {
            let current = top.current;

            let children = self.children.view();
            let data = children.get(top.current).unwrap();

            // Go to the next child in the linked list of children
            top.current = data.next;
            top.remaining -= 1;

            // If current is a parent, push a new stack frame with the first child
            if let Some(parent) = self.parents.view().get(current) {
                self.stack.push(StackFrame {
                    current: parent.view_first_child(&children).unwrap(),
                    remaining: parent.num_children,
                })
            }

            Some(current)
        } else {
            // End of linked list of children, pop stack frame
            self.stack.pop();
            self.next()
        }
    }
}

pub struct BreadthFirstIterator<'a, W, T> {
    world: &'a W,
    marker: PhantomData<T>,
    queue: VecDeque<Entity>,
}

impl<'a, W: GenericWorld + Hierarchy, T: 'static + Send + Sync> BreadthFirstIterator<'a, W, T> {
    pub(crate) fn new(world: &'a W, root: Entity) -> Self {
        // Add immediate children of root to queue
        let queue = world.children::<T>(root).collect();

        Self {
            world,
            queue,
            marker: PhantomData,
        }
    }
}

impl<'a, W: GenericWorld + Hierarchy, T: 'static + Send + Sync> Iterator
    for BreadthFirstIterator<'a, W, T>
{
    type Item = Entity;

    fn next(&mut self) -> Option<Self::Item> {
        let front = self.queue.pop_front()?;

        // Add any potention children of front to the back of queue
        self.queue.extend(self.world.children::<T>(front));

        Some(front)
    }
}