summaryrefslogtreecommitdiff
path: root/ecs/src/query.rs
blob: 9b8aeed24ce6f13e9459bb3ee806ac55578e5f20 (plain)
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
462
463
464
465
466
use std::any::type_name;
use std::borrow::Cow;
use std::marker::PhantomData;

use seq_macro::seq;

use crate::component::{Component, FromLockedOptional, Ref as ComponentRef};
use crate::entity::Handle as EntityHandle;
use crate::query::flexible::{Iter as FlexibleQueryIter, Query as FlexibleQuery};
use crate::system::{Param as SystemParam, System};
use crate::uid::Uid;
use crate::util::VecExt;
use crate::World;

pub mod flexible;
pub mod term;

#[derive(Debug)]
pub struct Query<'world, FieldTerms, FieldlessTerms = ()>
where
    FieldTerms: TermWithFieldTuple,
    FieldlessTerms: TermWithoutFieldTuple,
{
    world: &'world World,
    inner: FlexibleQuery<'world, 'static>,
    _pd: PhantomData<(FieldTerms, FieldlessTerms)>,
}

impl<'world, FieldTerms, FieldlessTerms> Query<'world, FieldTerms, FieldlessTerms>
where
    FieldTerms: TermWithFieldTuple,
    FieldlessTerms: TermWithoutFieldTuple,
{
    /// Iterates over the entities matching this query, the iterator item being the entity
    /// components.
    #[must_use]
    pub fn iter<'query>(
        &'query self,
    ) -> Iter<'query, 'world, FieldTerms, FlexibleQueryIter<'query>>
    {
        tracing::trace!("Searching for {}", std::any::type_name::<FieldTerms>());

        Iter {
            world: self.world,
            iter: self.inner.iter(),
            comps_pd: PhantomData,
        }
    }

    /// Iterates over the entities matching this query, the iterator item being the entity
    /// [`Uid`] and the matching entity components.
    #[must_use]
    pub fn iter_with_euids<'query>(
        &'query self,
    ) -> ComponentAndEuidIter<'query, 'world, FieldTerms, FlexibleQueryIter<'query>>
    {
        tracing::trace!("Searching for {}", std::any::type_name::<FieldTerms>());

        ComponentAndEuidIter {
            world: self.world,
            iter: self.inner.iter(),
            comps_pd: PhantomData,
        }
    }

    /// Iterates over the entities matching this query using the iterator returned by
    /// `func`.
    ///
    /// This function exists so that a custom [`EntityHandle`] iterator can be given to
    /// [`Iter`] without giving the user access to a reference to the [`World`].
    #[must_use]
    pub fn iter_with<'query, OutIter>(
        &'query self,
        func: impl FnOnce(FlexibleQueryIter<'query>) -> OutIter,
    ) -> Iter<'query, 'world, FieldTerms, OutIter>
    where
        OutIter: Iterator<Item = EntityHandle<'query>>,
    {
        tracing::trace!("Searching for {}", std::any::type_name::<FieldTerms>());

        Iter {
            world: self.world,
            iter: func(self.inner.iter()),
            comps_pd: PhantomData,
        }
    }

    /// Returns the UID of the entity at the given query iteration index.
    #[must_use]
    pub fn get_entity_uid(&self, entity_index: usize) -> Option<Uid>
    {
        Some(self.inner.iter().nth(entity_index)?.uid())
    }

    pub(crate) fn new(world: &'world World) -> Self
    {
        let mut terms_builder = Terms::builder();

        FieldTerms::apply_terms_to_builder(&mut terms_builder);
        FieldlessTerms::apply_terms_to_builder(&mut terms_builder);

        Self {
            world,
            inner: world.flexible_query(terms_builder.build()),
            _pd: PhantomData,
        }
    }
}

impl<'query, 'world, FieldTerms, FieldlessTerms> IntoIterator
    for &'query Query<'world, FieldTerms, FieldlessTerms>
where
    FieldTerms: TermWithFieldTuple + 'world,
    FieldlessTerms: TermWithoutFieldTuple,
{
    type IntoIter = Iter<'query, 'world, FieldTerms, FlexibleQueryIter<'query>>;
    type Item = FieldTerms::Fields<'query>;

    fn into_iter(self) -> Self::IntoIter
    {
        self.iter()
    }
}

impl<'world, FieldTerms, FieldlessTerms> SystemParam<'world>
    for Query<'world, FieldTerms, FieldlessTerms>
where
    FieldTerms: TermWithFieldTuple,
    FieldlessTerms: TermWithoutFieldTuple,
{
    type Input = ();

    fn initialize<SystemImpl>(
        _system: &mut impl System<'world, SystemImpl>,
        _input: Self::Input,
    )
    {
    }

    fn new<SystemImpl>(
        _system: &'world impl System<'world, SystemImpl>,
        world: &'world World,
    ) -> Self
    {
        Self::new(world)
    }
}

#[derive(Debug)]
pub struct Terms<'a>
{
    required_components: Cow<'a, [Uid]>,
    excluded_components: Cow<'a, [Uid]>,
}

impl<'a> Terms<'a>
{
    pub fn builder() -> TermsBuilder<'a>
    {
        TermsBuilder::default()
    }
}

#[derive(Debug, Default)]
pub struct TermsBuilder<'a>
{
    required_components: Cow<'a, [Uid]>,
    excluded_components: Cow<'a, [Uid]>,
}

pub trait TermsBuilderInterface<'a>
{
    fn with<ComponentT: Component>(self) -> Self;

    fn without<ComponentT: Component>(self) -> Self;

    fn with_required_ids(self, ids: &'a mut [Uid]) -> Self;
}

macro_rules! impl_terms_builder {
    ($($impl_content: tt)*) => {
        impl<'a> TermsBuilderInterface<'a> for TermsBuilder<'a> {
            $($impl_content)*
        }

        impl<'a> TermsBuilderInterface<'a> for &mut TermsBuilder<'a> {
            $($impl_content)*
        }
    };
}

impl_terms_builder! {
    #[allow(unused_mut)]
    fn with<ComponentT: Component>(mut self) -> Self
    {
        if ComponentT::is_optional() {
            return self;
        }

        self.required_components
            .to_mut()
            .insert_at_partition_point_by_key(ComponentT::id(), |id| *id);

        self
    }

    #[allow(unused_mut)]
    fn without<ComponentT: Component>(mut self) -> Self
    {
        if ComponentT::is_optional() {
            panic!(
                "{}::without cannot take optional component",
                type_name::<Self>()
            );
        }

        self.excluded_components
            .to_mut()
            .insert_at_partition_point_by_key(ComponentT::id(), |id| *id);

        self
    }

    #[allow(unused_mut)]
    fn with_required_ids(mut self, ids: &'a mut [Uid]) -> Self
    {
        if ids.is_empty() {
            return self;
        }

        if !ids.is_sorted() {
            ids.sort();
        }

        if self.required_components.is_empty() {
            self.required_components = Cow::Borrowed(ids);

            return self;
        }

        let first_id_pp_index = self.required_components.partition_point(|req_comp_id| {
            req_comp_id <= ids.first().expect("Cannot happend since not empty")
        });

        let removed = self
            .required_components
            .to_mut()
            .splice(first_id_pp_index..first_id_pp_index, ids.iter().copied());

        assert_eq!(removed.count(), 0);

        self
    }
}

impl<'a> TermsBuilder<'a>
{
    pub fn build(self) -> Terms<'a>
    {
        assert!(self.required_components.is_sorted());
        assert!(self.excluded_components.is_sorted());

        Terms {
            required_components: self.required_components,
            excluded_components: self.excluded_components,
        }
    }
}

pub trait TermWithoutField
{
    fn apply_to_terms_builder(terms_builder: &mut TermsBuilder<'_>);
}

pub trait TermWithField
{
    type Field<'a>;

    fn apply_to_terms_builder(terms_builder: &mut TermsBuilder<'_>);

    fn get_field<'world>(
        entity_handle: &EntityHandle<'world>,
        world: &'world World,
    ) -> Self::Field<'world>;
}

impl<ComponentRefT: ComponentRef> TermWithField for ComponentRefT
{
    type Field<'a> = ComponentRefT::Handle<'a>;

    fn apply_to_terms_builder(terms_builder: &mut TermsBuilder<'_>)
    {
        terms_builder.with::<ComponentRefT::Component>();
    }

    fn get_field<'world>(
        entity_handle: &EntityHandle<'world>,
        world: &'world World,
    ) -> Self::Field<'world>
    {
        Self::Field::from_locked_optional_component(
            entity_handle
                .get_component(ComponentRefT::Component::id())
                .map(|component| &component.component),
            world,
        )
        .unwrap_or_else(|err| {
            panic!(
                "Taking component {} lock failed: {err}",
                type_name::<ComponentRefT::Component>()
            );
        })
    }
}

pub trait TermWithoutFieldTuple
{
    fn apply_terms_to_builder(terms_builder: &mut TermsBuilder<'_>);
}

pub trait TermWithFieldTuple
{
    type Fields<'component>;

    fn apply_terms_to_builder(terms_builder: &mut TermsBuilder<'_>);

    fn get_fields<'component>(
        entity_handle: &EntityHandle<'component>,
        world: &'component World,
    ) -> Self::Fields<'component>;
}

pub struct Iter<'query, 'world, FieldTerms, EntityHandleIter>
where
    FieldTerms: TermWithFieldTuple + 'world,
    EntityHandleIter: Iterator<Item = EntityHandle<'query>>,
{
    world: &'world World,
    iter: EntityHandleIter,
    comps_pd: PhantomData<FieldTerms>,
}

impl<'query, 'world, FieldTerms, EntityHandleIter>
    Iter<'query, 'world, FieldTerms, EntityHandleIter>
where
    FieldTerms: TermWithFieldTuple + 'world,
    EntityHandleIter: Iterator<Item = EntityHandle<'query>>,
    'world: 'query,
{
    /// Creates a new iterator from the given entity handle iterator.
    ///
    /// # Important
    /// All of the yielded entities of the entity handle iterator should match the
    /// terms `Terms`. The [`Self::next`] function will panic if it encounters a
    /// entity that does not match the terms `Terms`.
    pub fn new(world: &'world World, iter: EntityHandleIter) -> Self
    {
        Self { world, iter, comps_pd: PhantomData }
    }
}

impl<'query, 'world, FieldTerms, EntityHandleIter> Iterator
    for Iter<'query, 'world, FieldTerms, EntityHandleIter>
where
    FieldTerms: TermWithFieldTuple + 'world,
    EntityHandleIter: Iterator<Item = EntityHandle<'query>>,
    'world: 'query,
{
    type Item = FieldTerms::Fields<'query>;

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

        Some(FieldTerms::get_fields(&entity_handle, self.world))
    }
}

pub struct ComponentAndEuidIter<'query, 'world, FieldTerms, EntityHandleIter>
where
    FieldTerms: TermWithFieldTuple + 'world,
    EntityHandleIter: Iterator<Item = EntityHandle<'query>>,
{
    world: &'world World,
    iter: EntityHandleIter,
    comps_pd: PhantomData<FieldTerms>,
}

impl<'query, 'world, FieldTerms, EntityHandleIter> Iterator
    for ComponentAndEuidIter<'query, 'world, FieldTerms, EntityHandleIter>
where
    FieldTerms: TermWithFieldTuple + 'world,
    EntityHandleIter: Iterator<Item = EntityHandle<'query>>,
    'world: 'query,
{
    type Item = (Uid, FieldTerms::Fields<'query>);

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

        Some((
            entity_handle.uid(),
            FieldTerms::get_fields(&entity_handle, self.world),
        ))
    }
}

macro_rules! impl_term_sequence {
    ($c: tt) => {
        seq!(I in 0..=$c {
            impl<#(Term~I: TermWithoutField,)*> TermWithoutFieldTuple for (#(Term~I,)*)
            {
                fn apply_terms_to_builder(terms_builder: &mut TermsBuilder<'_>)
                {
                    #(
                        Term~I::apply_to_terms_builder(terms_builder);
                    )*
                }
            }

            impl<#(Term~I: TermWithField,)*> TermWithFieldTuple for (#(Term~I,)*)
            {
                type Fields<'component> = (#(Term~I::Field<'component>,)*);

                fn apply_terms_to_builder(terms_builder: &mut TermsBuilder<'_>)
                {
                    #(
                        Term~I::apply_to_terms_builder(terms_builder);
                    )*
                }

                fn get_fields<'component>(
                    entity_handle: &EntityHandle<'component>,
                    world: &'component World,
                ) -> Self::Fields<'component>
                {
                    (#(Term~I::get_field(entity_handle, world),)*)
                }
            }
        });
    };
}

seq!(C in 0..=16 {
    impl_term_sequence!(C);
});

impl TermWithoutFieldTuple for ()
{
    fn apply_terms_to_builder(_terms_builder: &mut TermsBuilder<'_>) {}
}

impl TermWithFieldTuple for ()
{
    type Fields<'component> = ();

    fn apply_terms_to_builder(_terms_builder: &mut TermsBuilder<'_>) {}

    fn get_fields<'component>(
        _entity_handle: &EntityHandle<'_>,
        _world: &'component World,
    ) -> Self::Fields<'component>
    {
    }
}