sparsey 0.13.3

Entity Component System based on sparse sets
Documentation
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Query and iterate entities and components.

mod iter;
mod query_all;
mod query_one;
mod query_part;

#[cfg(feature = "parallel")]
mod par_iter;

pub use self::iter::*;
pub use self::query_all::*;
pub use self::query_one::*;
pub use self::query_part::*;

#[cfg(feature = "parallel")]
pub use self::par_iter::*;

use crate::component::QueryGroupInfo;
use crate::entity::Entity;
use crate::World;
use core::mem::MaybeUninit;
use core::ops::Range;
use core::ptr;

/// Trait for querying and iterating one or more views.
///
/// # Safety
///
/// This trait is considered an implementation detail and cannot be safely
/// implemented outside the crate.
pub unsafe trait Query {
    /// View borrowed from a [`World`].
    type View<'a>;

    /// Item type returned by queries.
    type Item<'a>: Send;

    /// Type returned by [`slice`](Self::slice_raw) operations.
    type Slice<'a>;

    /// [`SparseVec`](crate::entity::SparseVec) type used for sparse iteration.
    type Sparse<'a>: Copy;

    /// Data used for sparse and dense iteration.
    type Data<'a>: Copy;

    /// Borrows a view from the `world`.
    #[must_use]
    fn borrow(world: &World) -> Self::View<'_>;

    /// Borrows a view from the `world` along with grouping information.
    #[must_use]
    fn borrow_with_group_info(world: &World) -> (Self::View<'_>, Option<QueryGroupInfo>);

    /// Returns whether `entity` is present in all parts of the `view`.
    #[must_use]
    fn contains_all(view: &Self::View<'_>, entity: Entity) -> bool;

    /// Returns whether `entity` is present in none of the parts of the `view`.
    #[must_use]
    fn contains_none(view: &Self::View<'_>, entity: Entity) -> bool;

    /// Returns the item mapped to `entity`, if any.
    #[must_use]
    fn get<'a>(view: &'a mut Self::View<'_>, entity: Entity) -> Option<Self::Item<'a>>;

    /// Splits the view into its entities and sparse vecs.
    #[must_use]
    fn split_filter_parts<'a>(view: &'a Self::View<'_>)
        -> (Option<&'a [Entity]>, Self::Sparse<'a>);

    /// Splits the view into its entities, sparse vecs and data.
    #[must_use]
    fn split_sparse_parts<'a>(
        view: &'a Self::View<'_>,
    ) -> (Option<&'a [Entity]>, Self::Sparse<'a>, Self::Data<'a>);

    /// Splits the view into its entities and data.
    #[must_use]
    fn split_dense_parts<'a>(view: &'a Self::View<'_>) -> (Option<&'a [Entity]>, Self::Data<'a>);

    /// Returns whether the sparse index is present in all sparse vecs.
    #[must_use]
    fn contains_all_raw(sparse: Self::Sparse<'_>, sparse_index: usize) -> bool;

    /// Returns whether the sparse index is present in none of the sparse vecs.
    #[must_use]
    fn contains_none_raw(sparse: Self::Sparse<'_>, sparse_index: usize) -> bool;

    /// Returns the item mapped to `entity`, if any.
    #[must_use]
    unsafe fn get_sparse_raw<'a>(
        sparse: Self::Sparse<'a>,
        data: Self::Data<'a>,
        entity: Entity,
    ) -> Option<Self::Item<'a>>;

    /// Returns the item mapped to `index` or `entity`.
    #[must_use]
    unsafe fn get_dense_raw(data: Self::Data<'_>, index: usize, entity: Entity) -> Self::Item<'_>;

    /// Slices the data at the given `range`.
    #[must_use]
    unsafe fn slice_raw<'a>(
        data: Self::Data<'a>,
        entities: &'a [Entity],
        range: Range<usize>,
    ) -> Self::Slice<'a>;
}

#[allow(clippy::unused_unit)]
unsafe impl Query for () {
    type View<'a> = ();
    type Item<'a> = ();
    type Slice<'a> = ();
    type Sparse<'a> = ();
    type Data<'a> = ();

    #[inline]
    fn borrow(_world: &World) -> Self::View<'_> {
        // Empty
    }

    #[inline]
    fn borrow_with_group_info(_world: &World) -> (Self::View<'_>, Option<QueryGroupInfo>) {
        ((), Some(QueryGroupInfo::Empty))
    }

    #[inline]
    fn contains_all(_view: &Self::View<'_>, _entity: Entity) -> bool {
        true
    }

    #[inline]
    fn contains_none(_view: &Self::View<'_>, _entity: Entity) -> bool {
        true
    }

    #[inline]
    fn get<'a>(_view: &'a mut Self::View<'_>, _entity: Entity) -> Option<Self::Item<'a>> {
        Some(())
    }

    #[inline]
    fn split_filter_parts<'a>(
        _view: &'a Self::View<'a>,
    ) -> (Option<&'a [Entity]>, Self::Sparse<'a>) {
        (None, ())
    }

    #[inline]
    fn split_sparse_parts<'a>(
        _view: &'a Self::View<'_>,
    ) -> (Option<&'a [Entity]>, Self::Sparse<'a>, Self::Data<'a>) {
        (None, (), ())
    }

    #[inline]
    fn split_dense_parts<'a>(_view: &'a Self::View<'_>) -> (Option<&'a [Entity]>, Self::Data<'a>) {
        (None, ())
    }

    #[inline]
    fn contains_all_raw(_sparse: Self::Sparse<'_>, _sparse_index: usize) -> bool {
        true
    }

    #[inline]
    fn contains_none_raw(_sparse: Self::Sparse<'_>, _sparse_index: usize) -> bool {
        true
    }

    #[inline]
    unsafe fn get_sparse_raw<'a>(
        _sparse: Self::Sparse<'a>,
        _data: Self::Data<'a>,
        _entity: Entity,
    ) -> Option<Self::Item<'a>> {
        Some(())
    }

    #[inline]
    unsafe fn get_dense_raw(
        _data: Self::Data<'_>,
        _index: usize,
        _entity: Entity,
    ) -> Self::Item<'_> {
        // Empty
    }

    #[inline]
    unsafe fn slice_raw<'a>(
        _data: Self::Data<'a>,
        _entities: &'a [Entity],
        _range: Range<usize>,
    ) -> Self::Slice<'a> {
        // Empty
    }
}

unsafe impl<Q> Query for Q
where
    Q: QueryPart,
{
    type View<'a> = <Q as QueryPart>::View<'a>;
    type Item<'a> = <Q as QueryPart>::Item<'a>;
    type Slice<'a> = <Q as QueryPart>::Slice<'a>;
    type Sparse<'a> = <Q as QueryPart>::Sparse<'a>;
    type Data<'a> = <Q as QueryPart>::Data<'a>;

    fn borrow(world: &World) -> Self::View<'_> {
        <Q as QueryPart>::borrow(world)
    }

    fn borrow_with_group_info(world: &World) -> (Self::View<'_>, Option<QueryGroupInfo>) {
        let (view, info) = <Q as QueryPart>::borrow_with_group_info(world);
        let info = info.map_or(QueryGroupInfo::Empty, QueryGroupInfo::One);
        (view, Some(info))
    }

    fn contains_all(view: &Self::View<'_>, entity: Entity) -> bool {
        <Q as QueryPart>::contains(view, entity)
    }

    fn contains_none(view: &Self::View<'_>, entity: Entity) -> bool {
        !<Q as QueryPart>::contains(view, entity)
    }

    fn get<'a>(view: &'a mut Self::View<'_>, entity: Entity) -> Option<Self::Item<'a>> {
        let key = <Q as QueryPart>::get_sparse_key(view, entity)?;
        unsafe { Some(<Q as QueryPart>::get_sparse(view, key)) }
    }

    fn split_filter_parts<'a>(
        view: &'a Self::View<'_>,
    ) -> (Option<&'a [Entity]>, Self::Sparse<'a>) {
        <Q as QueryPart>::split_filter_parts(view)
    }

    fn split_sparse_parts<'a>(
        view: &'a Self::View<'_>,
    ) -> (Option<&'a [Entity]>, Self::Sparse<'a>, Self::Data<'a>) {
        <Q as QueryPart>::split_sparse_parts(view)
    }

    fn split_dense_parts<'a>(view: &'a Self::View<'_>) -> (Option<&'a [Entity]>, Self::Data<'a>) {
        <Q as QueryPart>::split_dense_parts(view)
    }

    fn contains_all_raw(sparse: Self::Sparse<'_>, sparse_index: usize) -> bool {
        <Q as QueryPart>::contains_raw(sparse, sparse_index)
    }

    fn contains_none_raw(sparse: Self::Sparse<'_>, sparse_index: usize) -> bool {
        !<Q as QueryPart>::contains_raw(sparse, sparse_index)
    }

    unsafe fn get_sparse_raw<'a>(
        sparse: Self::Sparse<'_>,
        data: Self::Data<'a>,
        entity: Entity,
    ) -> Option<Self::Item<'a>> {
        let key = <Q as QueryPart>::get_sparse_key_raw(sparse, entity)?;
        Some(<Q as QueryPart>::get_sparse_raw(data, key))
    }

    unsafe fn get_dense_raw(data: Self::Data<'_>, index: usize, entity: Entity) -> Self::Item<'_> {
        <Q as QueryPart>::get_dense_raw(data, index, entity)
    }

    unsafe fn slice_raw<'a>(
        data: Self::Data<'a>,
        entities: &'a [Entity],
        range: Range<usize>,
    ) -> Self::Slice<'a> {
        <Q as QueryPart>::slice_raw(data, entities, range)
    }
}

macro_rules! impl_query {
    ($(($Ty:ident, $idx:tt)),+) => {
        unsafe impl<$($Ty),+> Query for ($($Ty,)+)
        where
            $($Ty: QueryPart,)+
        {
            type View<'a> = ($($Ty::View<'a>,)+);
            type Item<'a> = ($($Ty::Item<'a>,)+);
            type Slice<'a> = ($($Ty::Slice<'a>,)+);
            type Sparse<'a> = ($($Ty::Sparse<'a>,)+);
            type Data<'a> = ($($Ty::Data<'a>,)+);

            fn borrow(world: &World) -> Self::View<'_> {
                ($($Ty::borrow(world),)+)
            }

            fn borrow_with_group_info(world: &World) -> (Self::View<'_>, Option<QueryGroupInfo>) {
                let view_and_group_info = ($($Ty::borrow_with_group_info(world),)+);

                let get_group_info = || -> Option<QueryGroupInfo> {
                    let mut group_info = QueryGroupInfo::Empty;

                    $(
                        if let Some(info) = &view_and_group_info.$idx.1 {
                            group_info = group_info.add_view(info)?;
                        }
                    )+

                    Some(group_info)
                };

                (
                    ($(view_and_group_info.$idx.0,)+),
                    get_group_info(),
                )
            }

            fn contains_all(view: &Self::View<'_>, entity: Entity) -> bool {
                $($Ty::contains(&view.$idx, entity))&&+
            }

            fn contains_none(view: &Self::View<'_>, entity: Entity) -> bool {
                $(!$Ty::contains(&view.$idx, entity))&&+
            }

            fn get<'a>(view: &'a mut Self::View<'_>, entity: Entity) -> Option<Self::Item<'a>> {
                let key = ($($Ty::get_sparse_key(&view.$idx, entity)?,)+);
                unsafe { Some(($($Ty::get_sparse(&mut view.$idx, key.$idx),)+)) }
            }

            fn split_filter_parts<'a>(
                view: &'a Self::View<'_>,
            ) -> (Option<&'a [Entity]>, Self::Sparse<'a>) {
                let mut entities = Option::<&[Entity]>::None;

                let sparse = ($({
                    let (view_entities, sparse) = $Ty::split_filter_parts(&view.$idx);

                    if let Some(view_entities) = view_entities {
                        if let Some(old_entities) = entities {
                            if view_entities.len() < old_entities.len() {
                                entities = Some(view_entities);
                            }
                        } else {
                            entities = Some(view_entities);
                        }
                    }

                    sparse
                },)+);

                (entities, sparse)
            }

            fn split_sparse_parts<'a>(
                view: &'a Self::View<'_>,
            ) -> (Option<&'a [Entity]>, Self::Sparse<'a>, Self::Data<'a>) {
                let mut entities = Option::<&[Entity]>::None;
                let mut sparse: MaybeUninit<Self::Sparse<'a>> = MaybeUninit::uninit();
                let mut data: MaybeUninit<Self::Data<'a>> = MaybeUninit::uninit();

                $({
                    let (view_entities, view_sparse, view_data)
                        = $Ty::split_sparse_parts(&view.$idx);

                    if let Some(view_entities) = view_entities {
                        if let Some(old_entities) = entities {
                            if view_entities.len() < old_entities.len() {
                                entities = Some(view_entities);
                            }
                        } else {
                            entities = Some(view_entities);
                        }
                    }

                    unsafe {
                        ptr::addr_of_mut!((*sparse.as_mut_ptr()).$idx).write(view_sparse);
                        ptr::addr_of_mut!((*data.as_mut_ptr()).$idx).write(view_data);
                    }
                })+;

                unsafe {
                    (entities, sparse.assume_init(), data.assume_init())
                }
            }

            fn split_dense_parts<'a>(
                view: &'a Self::View<'_>,
            ) -> (Option<&'a [Entity]>, Self::Data<'a>) {
                let mut entities = Option::<&[Entity]>::None;

                let data = ($({
                    let (view_entities, data) = $Ty::split_dense_parts(&view.$idx);

                    if entities.is_none() && view_entities.is_some() {
                        entities = view_entities;
                    }

                    data
                },)+);

                (entities, data)
            }

            fn contains_all_raw(sparse: Self::Sparse<'_>, sparse_index: usize) -> bool {
                $($Ty::contains_raw(sparse.$idx, sparse_index))&&+
            }

            fn contains_none_raw(sparse: Self::Sparse<'_>, sparse_index: usize) -> bool {
                $(!$Ty::contains_raw(sparse.$idx, sparse_index))&&+
            }

            unsafe fn get_sparse_raw<'a>(
                sparse: Self::Sparse<'a>,
                data: Self::Data<'a>,
                entity: Entity,
            ) -> Option<Self::Item<'a>> {
                let key = ($($Ty::get_sparse_key_raw(sparse.$idx, entity)?,)+);
                Some(($($Ty::get_sparse_raw(data.$idx, key.$idx),)+))
            }

            unsafe fn get_dense_raw(
                data: Self::Data<'_>,
                index: usize,
                entity: Entity,
            ) -> Self::Item<'_> {
                ($($Ty::get_dense_raw(data.$idx, index, entity),)+)
            }

            unsafe fn slice_raw<'a>(
                data: Self::Data<'a>,
                entities: &'a [Entity],
                range: Range<usize>,
            ) -> Self::Slice<'a> {
               ($($Ty::slice_raw(data.$idx, entities, range.clone()),)+)
            }
        }
    };
}

#[rustfmt::skip]
mod impls {
    use super::*;

    impl_query!((A, 0));
    impl_query!((A, 0), (B, 1));
    impl_query!((A, 0), (B, 1), (C, 2));
    impl_query!((A, 0), (B, 1), (C, 2), (D, 3));
    impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4));
    impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5));
    impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6));
    impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7));
    impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8));
    impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9));
    impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10));
    impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11));
    impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11), (M, 12));
    impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11), (M, 12), (N, 13));
    impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11), (M, 12), (N, 13), (O, 14));
    impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11), (M, 12), (N, 13), (O, 14), (P, 15));
}