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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
use core::{any::TypeId, marker::PhantomData, ops::ControlFlow};

use crate::{archetype::Archetype, entity::EntityId, epoch::EpochId};

use super::{fetch::Fetch, merge_access, Access, DefaultQuery, ImmutableQuery, IntoQuery, Query};

/// Binary operator for [`BooleanQuery`].
pub trait BooleanFetchOp: 'static {
    /// Applies binary operator to two values.
    /// Returns `ControlFlow::Continue` if the operation should continue.
    /// Returns `ControlFlow::Break` if applying anything else would not change the result.
    fn op(a: bool, b: bool) -> ControlFlow<bool, bool>;

    /// Returns `true` if the result of the operation is `true` for the given mask.
    /// The mask is a bitset where each bit represents a single value.
    /// `count` is the number of bits to consider in the mask.
    fn mask(mask: u16, count: usize) -> bool;
}

pub enum AndOp {}

impl BooleanFetchOp for AndOp {
    fn op(a: bool, b: bool) -> ControlFlow<bool, bool> {
        if a && b {
            ControlFlow::Continue(true)
        } else {
            ControlFlow::Break(false)
        }
    }

    fn mask(mask: u16, count: usize) -> bool {
        mask == (1 << count) - 1
    }
}

pub enum OrOp {}

impl BooleanFetchOp for OrOp {
    fn op(a: bool, b: bool) -> ControlFlow<bool, bool> {
        if a || b {
            ControlFlow::Break(true)
        } else {
            ControlFlow::Continue(false)
        }
    }

    fn mask(mask: u16, _count: usize) -> bool {
        mask != 0
    }
}

pub enum XorOp {}

impl BooleanFetchOp for XorOp {
    fn op(a: bool, b: bool) -> ControlFlow<bool, bool> {
        match (a, b) {
            (false, false) => ControlFlow::Continue(false),
            (true, true) => ControlFlow::Break(false),
            _ => ControlFlow::Continue(true),
        }
    }

    fn mask(mask: u16, _count: usize) -> bool {
        mask.is_power_of_two()
    }
}

/// Combines multiple queries.
/// Applies boolean operation to query filtering.
/// Yields tuple of query items wrapper in `Option`.
pub struct BooleanQuery<T, Op> {
    tuple: T,
    op: PhantomData<Op>,
}

impl<T, Op> BooleanQuery<T, Op> {
    /// Creates a new [`BooleanQuery`].
    pub fn from_tuple(tuple: T) -> Self {
        BooleanQuery {
            tuple,
            op: PhantomData,
        }
    }
}

/// Boolean filter combines two filters and boolean operation.
pub struct BooleanFetch<T, Op> {
    tuple: T,
    archetype: u16,
    chunk: u16,
    item: u16,
    op: PhantomData<Op>,
}

macro_rules! boolean_shortcut {
    ([$archetype:ident $op:ident] $a:ident $($b:ident)*) => {{
        let mut result = $a.visit_archetype($archetype);
        $(
            match $op::op(result, $b.visit_archetype($archetype)) {
                ControlFlow::Continue(r) => result = r,
                ControlFlow::Break(r) => return r,
            }
        )*
        result
    }};
}

macro_rules! impl_boolean {
    () => { /* Don't implement for empty tuple */ };
    ($($a:ident)+) => {
        #[allow(non_snake_case)]
        #[allow(unused_variables, unused_mut, unused_assignments)]
        unsafe impl<'a, Op $(, $a)+> Fetch<'a> for BooleanFetch<($($a,)+), Op>
        where
            $($a: Fetch<'a>,)+
            Op: BooleanFetchOp,
        {
            type Item = ($(Option<$a::Item>,)+);

            #[inline(always)]
            fn dangling() -> Self {
                BooleanFetch {
                    tuple: ($($a::dangling(),)+),
                    archetype: 0,
                    chunk: 0,
                    item: 0,
                    op: PhantomData,
                }
            }

            #[inline(always)]
            unsafe fn get_item(&mut self, idx: usize) -> ($(Option<$a::Item>,)+) {
                let ($($a,)+) = &mut self.tuple;
                let mut mi = 0;
                ($({
                    let elem = if self.item & (1 << mi) != 0 {
                        Some($a.get_item(idx))
                    } else {
                        None
                    };
                    mi += 1;
                    elem
                },)+)
            }

            #[inline(always)]
            unsafe fn visit_item(&mut self, idx: usize) -> bool {
                let ($($a,)+) = &mut self.tuple;
                let mut mi = 0;
                $(
                    if self.chunk & (1 << mi) != 0 {
                        if $a.visit_item(idx) {
                            self.item |= 1 << mi;
                        }
                    }
                    mi += 1;
                )+
                Op::mask(self.item, mi)
            }

            #[inline(always)]
            unsafe fn visit_chunk(&mut self, chunk_idx: usize) -> bool {
                let ($($a,)+) = &mut self.tuple;
                let mut mi = 0;
                $(
                    if self.archetype & (1 << mi) != 0 {
                        if $a.visit_chunk(chunk_idx) {
                            self.chunk |= 1 << mi;
                        }
                    }
                    mi += 1;
                )+
                Op::mask(self.chunk, mi)
            }

            #[inline(always)]
            unsafe fn touch_chunk(&mut self, chunk_idx: usize) {
                let ($($a,)+) = &mut self.tuple;
                let mut mi = 0;
                $(
                    if self.chunk & (1 << mi) != 0 {
                        $a.touch_chunk(chunk_idx);
                    }
                )+
            }
        }

        #[allow(non_snake_case)]
        impl<'a, Op $(, $a)+> BooleanQuery<($($a,)+), Op>
        where
            Op: BooleanFetchOp,
        {
            /// Creates a new [`BooleanQuery`].
            #[inline(always)]
            pub fn new($($a: $a),+) -> Self {
                BooleanQuery {
                    tuple: ($($a,)+),
                    op: PhantomData
                }
            }
        }

        #[allow(non_snake_case)]
        impl<Op $(, $a)+> IntoQuery for BooleanQuery<($($a,)+), Op>
        where
            $($a: IntoQuery,)+
            Op: BooleanFetchOp,
        {
            type Query = BooleanQuery<($($a::Query,)+), Op>;

            #[inline(always)]
            fn into_query(self) -> Self::Query {
                let ($($a,)+) = self.tuple;
                BooleanQuery {
                    tuple: ($($a.into_query(),)+),
                    op: PhantomData,
                }
            }
        }

        impl<Op $(, $a)+> DefaultQuery for BooleanQuery<($($a,)+), Op>
        where
            $($a: DefaultQuery,)+
            Op: BooleanFetchOp,
        {
            #[inline]
            fn default_query() -> Self::Query {
                BooleanQuery {
                    tuple: ($($a::default_query(),)+),
                    op: PhantomData,
                }
            }
        }

        #[allow(non_snake_case)]
        #[allow(unused_variables, unused_mut, unused_assignments)]
        unsafe impl<Op $(, $a)+> Query for BooleanQuery<($($a,)+), Op>
        where
            $($a: Query,)+
            Op: BooleanFetchOp,
        {
            type Item<'a> = ($(Option<$a::Item<'a>>,)+);
            type Fetch<'a> = BooleanFetch<($($a::Fetch<'a>,)+), Op>;

            #[inline(always)]
            fn access(&self, ty: TypeId) -> Option<Access> {
                let ($($a,)+) = &self.tuple;
                let mut result = None;
                $(result = merge_access(result, $a.access(ty));)+
                result
            }

            #[inline(always)]
            unsafe fn access_archetype(&self, archetype: &Archetype, f: &dyn Fn(TypeId, Access)) {
                let ($($a,)+) = &self.tuple;
                $($a.access_archetype(archetype, f);)+
            }

            #[inline(always)]
            fn visit_archetype(&self, archetype: &Archetype) -> bool {
                let ($($a,)+) = &self.tuple;
                boolean_shortcut!([archetype Op] $($a)+)
            }

            #[inline(always)]
            unsafe fn fetch<'a>(
                &mut self,
                archetype: &'a Archetype,
                epoch: EpochId,
            ) -> BooleanFetch<($($a::Fetch<'a>,)+), Op> {
                let ($($a,)+) = &mut self.tuple;
                let mut mask = 0;
                let mut mi = 0;
                BooleanFetch {
                    tuple: ($({
                        let fetch = if $a.visit_archetype(archetype) {
                            mask |= (1 << mi);
                            $a.fetch(archetype, epoch)
                        } else {
                            Fetch::dangling()
                        };
                        mi += 1;
                        fetch
                    },)+),
                    archetype: mask,
                    chunk: 0,
                    item: 0,
                    op: PhantomData,
                }
            }

            #[inline]
            fn reserved_entity_item<'a>(&self, id: EntityId) -> Option<Self::Item<'a>> {
                let ($($a,)+) = &self.tuple;
                let mut mask = 0;
                let mut mi = 0;
                $(
                    let $a = $a.reserved_entity_item(id);
                    if $a.is_some() {
                        mask |= 1 << mi;
                    }
                    mi += 1;
                )+
                if Op::mask(mask, mi) {
                    Some(($($a,)+))
                } else {
                    None
                }
            }
        }

        unsafe impl<Op $(, $a)+> ImmutableQuery for BooleanQuery<($($a,)+), Op>
        where
            $($a: ImmutableQuery,)+
            Op: BooleanFetchOp,
        {
        }
    };
}

for_tuple!(impl_boolean);

/// Combines tuple of filters and yields only entities that pass all of them.
pub type And<T> = BooleanQuery<T, AndOp>;

/// Combines tuple of filters and yields only entities that pass any of them.
pub type Or<T> = BooleanQuery<T, OrOp>;

/// Combines tuple of filters and yields only entities that pass exactly one.
pub type Xor<T> = BooleanQuery<T, XorOp>;

/// Combines two filters and yields only entities that pass all of them.
pub type And2<A, B> = And<(A, B)>;

/// Combines three filters and yields only entities that pass all of them.
pub type And3<A, B, C> = And<(A, B, C)>;

/// Combines four filters and yields only entities that pass all of them.
pub type And4<A, B, C, D> = And<(A, B, C, D)>;

/// Combines five filters and yields only entities that pass all of them.
pub type And5<A, B, C, D, E> = And<(A, B, C, D, E)>;

/// Combines six filters and yields only entities that pass all of them.
pub type And6<A, B, C, D, E, F> = And<(A, B, C, D, E, F)>;

/// Combines seven filters and yields only entities that pass all of them.
pub type And7<A, B, C, D, E, F, G> = And<(A, B, C, D, E, F, G)>;

/// Combines eight filters and yields only entities that pass all of them.
pub type And8<A, B, C, D, E, F, G, H> = And<(A, B, C, D, E, F, G, H)>;

/// Combines two filters and yields only entities that pass any of them.
pub type Or2<A, B> = Or<(A, B)>;

/// Combines three filters and yields only entities that pass any of them.
pub type Or3<A, B, C> = Or<(A, B, C)>;

/// Combines four filters and yields only entities that pass any of them.
pub type Or4<A, B, C, D> = Or<(A, B, C, D)>;

/// Combines five filters and yields only entities that pass any of them.
pub type Or5<A, B, C, D, E> = Or<(A, B, C, D, E)>;

/// Combines six filters and yields only entities that pass any of them.
pub type Or6<A, B, C, D, E, F> = Or<(A, B, C, D, E, F)>;

/// Combines seven filters and yields only entities that pass any of them.
pub type Or7<A, B, C, D, E, F, G> = Or<(A, B, C, D, E, F, G)>;

/// Combines eight filters and yields only entities that pass any of them.
pub type Or8<A, B, C, D, E, F, G, H> = Or<(A, B, C, D, E, F, G, H)>;

/// Combines two filters and yields only entities that pass exactly one.
pub type Xor2<A, B> = Xor<(A, B)>;

/// Combines three filters and yields only entities that pass exactly one.
pub type Xor3<A, B, C> = Xor<(A, B, C)>;

/// Combines four filters and yields only entities that pass exactly one.
pub type Xor4<A, B, C, D> = Xor<(A, B, C, D)>;

/// Combines five filters and yields only entities that pass exactly one.
pub type Xor5<A, B, C, D, E> = Xor<(A, B, C, D, E)>;

/// Combines six filters and yields only entities that pass exactly one.
pub type Xor6<A, B, C, D, E, F> = Xor<(A, B, C, D, E, F)>;

/// Combines seven filters and yields only entities that pass exactly one.
pub type Xor7<A, B, C, D, E, F, G> = Xor<(A, B, C, D, E, F, G)>;

/// Combines eight filters and yields only entities that pass exactly one.
pub type Xor8<A, B, C, D, E, F, G, H> = Xor<(A, B, C, D, E, F, G, H)>;