flecs_ecs 0.2.1

Rust API for the C/CPP flecs ECS library <https://github.com/SanderMertens/flecs>
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! Multi-source field access for table iterators.
//!
//! This module provides the [`TableIter::get()`] method which enables safe access to
//! fields from different sources (different tables), handling mutable aliasing checks
//! when the `flecs_safety_locks` feature is enabled.
//!
//! # Mutable Access
//!
//! To get mutable access to a field, wrap its index with `Mut()`:
//!
//! ```rust
//! # use flecs_ecs::prelude::*;
//! # use flecs_ecs::core::table::Mut;
//! # #[derive(Component)]
//! # struct Position { x: f32, y: f32 }
//! # #[derive(Component)]
//! # struct Parent;
//! # let world = World::new();
//! # let parent = world.entity().set(Position { x: 0.0, y: 0.0 });
//! # world.entity().set(Position { x: 1.0, y: 1.0 }).child_of(parent);
//! # let query = world.query::<(&mut Position, &Position)>().term_at(1).parent().build();
//! query.run(|mut it| {
//!     while it.next() {
//!         // Get mutable field 0 and immutable field 1
//!         // Uses Mut(0) to indicate field 0 is mutable
//!         match it.get::<Position, _>((Mut(0), 1)) {
//!             (Ok(mut pos), Ok(parent_pos)) => {
//!                 for i in it.iter() {
//!                     pos[i].x = parent_pos[i].x;
//!                     pos[i].y = parent_pos[i].y;
//!                 }
//!             }
//!             _ => {}
//!         }
//!     }
//! });
//! ```
//!
//! when aliasing is possible, this can be handled with the (Ok(_), Err(_)) match arm.
//!
//! ```rust
//! # use flecs_ecs::prelude::*;
//! # #[derive(Component, Debug)]
//! # struct TP {
//! #     x: i32,
//! # }
//! # #[derive(Component, Debug)]
//! # struct Relx;
//! # #[derive(Component, Debug)]
//! # struct Unit;
//! # let world = World::new();
//! let parent = world.entity().set(TP { x: 1 });
//! parent.add((id::<Relx>(), parent));
//! world
//!     .entity()
//!     .add(Unit)
//!     .set(TP { x: 4 })
//!     .add((id::<Relx>(), parent));
//! let mut ok_alias = false;
//! let mut ok_normal = false;
//! world
//!     .query::<(&mut TP, &TP)>()
//!     .with((id::<Relx>(), "$parent"))
//!     .term_at(1)
//!     .set_src("$parent")
//!     .build()
//!     .run(|mut it| {
//!         while it.next() {
//!             match it.get::<TP, _>((Mut(0), 1)) {
//!                 (Ok(_tp1), Ok(_tp2)) => {
//!                     // table no alias issues
//!                     ok_normal = true;
//!                 }
//!                 (Ok(_tp), Err(_)) => {
//!                     // aliasing detected, only one reference allowed & returned
//!                     ok_alias = true;
//!                 }
//!                 _ => {
//!                     unreachable!();
//!                 }
//!             }
//!         }
//!     });
//! #[cfg(feature = "flecs_safety_locks")]
//! assert!(ok_alias, "Expected to detect aliasing and return an error");
//! assert!(
//!     ok_normal,
//!     "Expected to get a valid result without aliasing error"
//! );
//! ```
//!
//! # Aliasing Detection
//!
//! When `flecs_safety_locks` is enabled, attempting to get mutable and immutable
//! access to the same table will return an error, preventing undefined behavior
//! from mutable aliasing.

use flecs_ecs::prelude::*;

use super::iter::FieldError;

impl<const IS_RUN: bool, P> TableIter<'_, IS_RUN, P>
where
    P: ComponentId,
{
    pub fn get<'w, T: ComponentId, F>(&'w self, fields_indices: F) -> F::TupleType<'w>
    where
        F: FieldsTuple<T> + 'w,
    {
        let world = self.world();
        fields_indices.get_tuple(&world, self)
    }
}

/// Wrapper to indicate that a field should be accessed mutably.
///
/// Used with [`TableIter::get()`] to specify which fields require mutable access.
pub struct Mut(pub usize);

pub trait FieldsTuple<T: ComponentId>: Sized {
    type TupleType<'w>
    where
        Self: 'w;

    fn get_tuple<'a, const IS_RUN: bool, P: ComponentId>(
        self,
        world: &WorldRef,
        iter: &'a TableIter<'a, IS_RUN, P>,
    ) -> Self::TupleType<'a>;
}

pub trait IterableTypeFieldOperation<T: 'static + ComponentId> {
    type ActualType<'w>
    where
        Self: 'w;

    fn get_data<'a, const IS_RUN: bool, P: ComponentId>(
        self,
        iter: &'a TableIter<'a, IS_RUN, P>,
    ) -> Self::ActualType<'a>
    where
        Self: 'a;
}

impl<T: 'static + ComponentId> IterableTypeFieldOperation<T> for usize {
    type ActualType<'w>
        = Result<Field<'w, T::UnderlyingType, true>, FieldError>
    where
        Self: 'w;

    fn get_data<'a, const IS_RUN: bool, P: ComponentId>(
        self,
        iter: &'a TableIter<'a, IS_RUN, P>,
    ) -> Self::ActualType<'a>
    where
        Self: 'a,
    {
        iter.field_result::<T>(self as i8)
    }
}

impl<T: 'static + ComponentId> IterableTypeFieldOperation<T> for Mut {
    type ActualType<'w>
        = Result<FieldMut<'w, T::UnderlyingType, true>, FieldError>
    where
        Self: 'w;

    fn get_data<'a, const IS_RUN: bool, P: ComponentId>(
        self,
        iter: &'a TableIter<'a, IS_RUN, P>,
    ) -> Self::ActualType<'a>
    where
        Self: 'a,
    {
        iter.field_result_mut::<T>(self.0 as i8)
    }
}

// macro_rules! impl_fields_tuple {
//     ($($t:ident),*) => {
//         //impl<$($t: IterableTypeFieldOperation),*> FieldsTuple for ($($t,)*) {
//         impl<T: 'static + ComponentId, $($t),*> FieldsTuple<T> for ($($t,)*)
//         where

//             $($t: IterableTypeFieldOperation<T>),*
//         {
//             type TupleType<'w> = ($(
//                 < $t as IterableTypeFieldOperation<T>>::ActualType<'w>,
//             )*)
//             where
//                 Self: 'w;

//             fn get_tuple<'a, const IS_RUN: bool, P: ComponentId>(
//                 self,
//                 _world: &WorldRef,
//                 iter: &'a TableIter<'a, IS_RUN, P>,
//             ) -> Self::TupleType<'a> {
//                 //idk
//             }
//         }
//     }
// }

impl<A, B, T> FieldsTuple<T> for (A, B)
where
    T: 'static + ComponentId,
    A: IterableTypeFieldOperation<T>,
    B: IterableTypeFieldOperation<T>,
{
    type TupleType<'w>
        = (
        <A as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <B as IterableTypeFieldOperation<T>>::ActualType<'w>,
    )
    where
        Self: 'w;

    fn get_tuple<'a, const IS_RUN: bool, P: ComponentId>(
        self,
        _world: &WorldRef,
        iter: &'a TableIter<'a, IS_RUN, P>,
    ) -> Self::TupleType<'a> {
        (self.0.get_data(iter), self.1.get_data(iter))
    }
}

//for A B C
impl<A, B, C, T> FieldsTuple<T> for (A, B, C)
where
    T: 'static + ComponentId,
    A: IterableTypeFieldOperation<T>,
    B: IterableTypeFieldOperation<T>,
    C: IterableTypeFieldOperation<T>,
{
    type TupleType<'w>
        = (
        <A as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <B as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <C as IterableTypeFieldOperation<T>>::ActualType<'w>,
    )
    where
        Self: 'w;

    fn get_tuple<'a, const IS_RUN: bool, P: ComponentId>(
        self,
        _world: &WorldRef,
        iter: &'a TableIter<'a, IS_RUN, P>,
    ) -> Self::TupleType<'a> {
        (
            self.0.get_data(iter),
            self.1.get_data(iter),
            self.2.get_data(iter),
        )
    }
}
impl<A, B, C, D, T> FieldsTuple<T> for (A, B, C, D)
where
    T: 'static + ComponentId,
    A: IterableTypeFieldOperation<T>,
    B: IterableTypeFieldOperation<T>,
    C: IterableTypeFieldOperation<T>,
    D: IterableTypeFieldOperation<T>,
{
    type TupleType<'w>
        = (
        <A as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <B as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <C as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <D as IterableTypeFieldOperation<T>>::ActualType<'w>,
    )
    where
        Self: 'w;

    fn get_tuple<'a, const IS_RUN: bool, P: ComponentId>(
        self,
        _world: &WorldRef,
        iter: &'a TableIter<'a, IS_RUN, P>,
    ) -> Self::TupleType<'a> {
        (
            self.0.get_data(iter),
            self.1.get_data(iter),
            self.2.get_data(iter),
            self.3.get_data(iter),
        )
    }
}
impl<A, B, C, D, E, T> FieldsTuple<T> for (A, B, C, D, E)
where
    T: 'static + ComponentId,
    A: IterableTypeFieldOperation<T>,
    B: IterableTypeFieldOperation<T>,
    C: IterableTypeFieldOperation<T>,
    D: IterableTypeFieldOperation<T>,
    E: IterableTypeFieldOperation<T>,
{
    type TupleType<'w>
        = (
        <A as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <B as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <C as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <D as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <E as IterableTypeFieldOperation<T>>::ActualType<'w>,
    )
    where
        Self: 'w;

    fn get_tuple<'a, const IS_RUN: bool, P: ComponentId>(
        self,
        _world: &WorldRef,
        iter: &'a TableIter<'a, IS_RUN, P>,
    ) -> Self::TupleType<'a> {
        (
            self.0.get_data(iter),
            self.1.get_data(iter),
            self.2.get_data(iter),
            self.3.get_data(iter),
            self.4.get_data(iter),
        )
    }
}
impl<A, B, C, D, E, F, T> FieldsTuple<T> for (A, B, C, D, E, F)
where
    T: 'static + ComponentId,
    A: IterableTypeFieldOperation<T>,
    B: IterableTypeFieldOperation<T>,
    C: IterableTypeFieldOperation<T>,
    D: IterableTypeFieldOperation<T>,
    E: IterableTypeFieldOperation<T>,
    F: IterableTypeFieldOperation<T>,
{
    type TupleType<'w>
        = (
        <A as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <B as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <C as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <D as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <E as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <F as IterableTypeFieldOperation<T>>::ActualType<'w>,
    )
    where
        Self: 'w;

    fn get_tuple<'a, const IS_RUN: bool, P: ComponentId>(
        self,
        _world: &WorldRef,
        iter: &'a TableIter<'a, IS_RUN, P>,
    ) -> Self::TupleType<'a> {
        (
            self.0.get_data(iter),
            self.1.get_data(iter),
            self.2.get_data(iter),
            self.3.get_data(iter),
            self.4.get_data(iter),
            self.5.get_data(iter),
        )
    }
}
impl<A, B, C, D, E, F, G, T> FieldsTuple<T> for (A, B, C, D, E, F, G)
where
    T: 'static + ComponentId,
    A: IterableTypeFieldOperation<T>,
    B: IterableTypeFieldOperation<T>,
    C: IterableTypeFieldOperation<T>,
    D: IterableTypeFieldOperation<T>,
    E: IterableTypeFieldOperation<T>,
    F: IterableTypeFieldOperation<T>,
    G: IterableTypeFieldOperation<T>,
{
    type TupleType<'w>
        = (
        <A as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <B as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <C as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <D as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <E as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <F as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <G as IterableTypeFieldOperation<T>>::ActualType<'w>,
    )
    where
        Self: 'w;

    fn get_tuple<'a, const IS_RUN: bool, P: ComponentId>(
        self,
        _world: &WorldRef,
        iter: &'a TableIter<'a, IS_RUN, P>,
    ) -> Self::TupleType<'a> {
        (
            self.0.get_data(iter),
            self.1.get_data(iter),
            self.2.get_data(iter),
            self.3.get_data(iter),
            self.4.get_data(iter),
            self.5.get_data(iter),
            self.6.get_data(iter),
        )
    }
}
impl<A, B, C, D, E, F, G, H, T> FieldsTuple<T> for (A, B, C, D, E, F, G, H)
where
    T: 'static + ComponentId,
    A: IterableTypeFieldOperation<T>,
    B: IterableTypeFieldOperation<T>,
    C: IterableTypeFieldOperation<T>,
    D: IterableTypeFieldOperation<T>,
    E: IterableTypeFieldOperation<T>,
    F: IterableTypeFieldOperation<T>,
    G: IterableTypeFieldOperation<T>,
    H: IterableTypeFieldOperation<T>,
{
    type TupleType<'w>
        = (
        <A as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <B as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <C as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <D as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <E as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <F as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <G as IterableTypeFieldOperation<T>>::ActualType<'w>,
        <H as IterableTypeFieldOperation<T>>::ActualType<'w>,
    )
    where
        Self: 'w;

    fn get_tuple<'a, const IS_RUN: bool, P: ComponentId>(
        self,
        _world: &WorldRef,
        iter: &'a TableIter<'a, IS_RUN, P>,
    ) -> Self::TupleType<'a> {
        (
            self.0.get_data(iter),
            self.1.get_data(iter),
            self.2.get_data(iter),
            self.3.get_data(iter),
            self.4.get_data(iter),
            self.5.get_data(iter),
            self.6.get_data(iter),
            self.7.get_data(iter),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Component, Debug)]
    struct TP {
        _x: i32,
    }

    #[derive(Component, Debug)]
    struct Relx;

    #[derive(Component, Debug)]
    struct Unit;

    #[test]
    #[cfg(feature = "flecs_safety_locks")]
    fn multi_src_same_table_err() {
        let world = World::new();
        let parent = world.entity().set(TP { _x: 1 });
        parent.add((id::<Relx>(), parent));
        world
            .entity()
            .add(Unit)
            .set(TP { _x: 4 })
            .add((id::<Relx>(), parent));
        let mut ok_alias = false;
        let mut ok_normal = false;
        world
            .query::<(&mut TP, &TP)>()
            .with((id::<Relx>(), "$parent"))
            .term_at(1)
            .set_src("$parent")
            .build()
            .run(|mut it| {
                while it.next() {
                    match it.get::<TP, _>((Mut(0), 1)) {
                        (Ok(_tp1), Ok(_tp2)) => {
                            // table no alias issues
                            ok_normal = true;
                        }
                        (Ok(_tp), Err(_)) => {
                            // aliasing detected, only one reference allowed & returned
                            ok_alias = true;
                        }
                        _ => {
                            unreachable!();
                        }
                    }
                }
            });

        assert!(ok_alias, "Expected to detect aliasing and return an error");
        assert!(
            ok_normal,
            "Expected to get a valid result without aliasing error"
        );
    }

    #[test]
    fn multi_src_diff_table_ok() {
        let world = World::new();

        let parent = world.entity().set(TP { _x: 1 });
        world.entity().set(TP { _x: 4 }).child_of(parent);

        let mut ok = false;

        world
            .query::<(&mut TP, &TP)>()
            .term_at(1)
            .parent()
            .build()
            .run(|mut it| {
                while it.next() {
                    match it.get::<TP, _>((Mut(0), 1)) {
                        (Ok(_), Ok(_)) => {
                            ok = true;
                        }
                        (Ok(_), Err(_)) => {}
                        _ => {
                            unreachable!();
                        }
                    }
                }
            });

        assert!(ok, "Expected to get a valid result");
    }
}