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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
//! Table access and iteration utilities.
//!
//! This module provides direct access to tables and their component data. Tables are the
//! internal storage structure in Flecs that group entities with the same component composition
//! (archetype). Understanding and working with tables is essential for high-performance ECS operations.
//!
//! # What are Tables?
//!
//! In Flecs, entities with the same set of components are stored together in tables. Each table
//! represents a unique archetype - a specific combination of components. This storage model enables:
//!
//! - **Cache-friendly iteration**: Components of the same type are stored contiguously in memory
//! - **Fast component access**: Direct array indexing without indirection
//! - **Efficient queries**: Query matching can be done at the table level
//!
//! # Module Organization
//!
//! - [`Table`]: The main wrapper providing access to table metadata and component arrays
//! - [`TableIter`]: Iterator for traversing tables and accessing component data during queries
//! - [`Field`] and [`FieldMut`]: Typed access to component columns (fields) within a table
//! - [`FieldUntyped`] and [`FieldUntypedMut`]: Untyped access for dynamic component types
//! - [`FieldIndex`]: Type-safe index for accessing specific entity rows in a field
//! - [`TableFlags`]: Bitflags describing table properties and capabilities
//!
//! # Common Use Cases
//!
//! ## Accessing Table Information
//!
//! ```rust, no_run
//! # use flecs_ecs::prelude::*;
//! # #[derive(Component)]
//! # struct Position { x: f32, y: f32 }
//! # #[derive(Component)]
//! # struct Velocity { x: f32, y: f32 }
//! # let world = World::new();
//! let e = world
//!     .entity()
//!     .set(Position { x: 1.0, y: 2.0 })
//!     .set(Velocity { x: 0.0, y: 0.0 });
//! if let Some(table) = e.table() {
//!     // Access table directly
//!     println!(
//!         "Entity is in table: {table:?}, with archetype: {:?}",
//!         table.archetype()
//!     );
//! }
//! ```
//!
//! ## Iterating with Fields
//!
//! The most common pattern is using [`TableIter`] within queries to access component data:
//!
//! ```rust,no_run
//! # use flecs_ecs::prelude::*;
//! # #[derive(Component)]
//! # struct Position { x: f32, y: f32 }
//! # #[derive(Component)]
//! # struct Velocity { x: f32, y: f32 }
//! # let world = World::new();
//! # world.entity().set(Position { x: 1.0, y: 2.0 }).set(Velocity { x: 0.1, y: 0.2 });
//! let query = world.new_query::<(&mut Position, &Velocity)>();
//!
//! query.run(|mut it| {
//!     while it.next() {
//!         // For each matching table
//!         let mut pos = it.field_mut::<Position>(0);
//!         let vel = it.field::<Velocity>(1);
//!
//!         for i in it.iter() {
//!             // For each entity in the table
//!             pos[i].x += vel[i].x;
//!             pos[i].y += vel[i].y;
//!         }
//!     }
//! });
//! ```
//!
//! ## Type-Safe Indexing
//!
//! [`FieldIndex`] provides bounds-check-free indexing when iterating:
//!
//! ```rust,no_run
//! # use flecs_ecs::prelude::*;
//! # #[derive(Component)]
//! # struct Position { x: f32, y: f32 }
//! # let world = World::new();
//! # world.entity().set(Position { x: 1.0, y: 2.0 });
//! # let query = world.new_query::<&Position>();
//! query.run(|mut it| {
//!     while it.next() {
//!         let pos = it.field::<Position>(0);
//!
//!         // iter() returns FieldIndex, which allows unchecked access
//!         for i in it.iter() {
//!             let position = &pos[i]; // No bounds check
//!         }
//!     }
//! });
//! ```

mod field;
mod flags;
mod iter;
mod multi_src_get;

use core::{ffi::CStr, ffi::c_void, ptr::NonNull};
pub use field::{Field, FieldAt, FieldAtMut, FieldIndex, FieldMut, FieldUntyped, FieldUntypedMut};
pub(crate) use field::{flecs_field, flecs_field_w_size};
pub use multi_src_get::*;

pub use flags::TableFlags;
pub use iter::TableIter;
#[cfg(any(debug_assertions, feature = "flecs_force_enable_ecs_asserts"))]
pub(crate) use iter::{table_lock, table_unlock};

use crate::core::*;
use crate::sys;

#[cfg(feature = "std")]
extern crate std;

extern crate alloc;
use alloc::{string::String, vec::Vec};

/// A wrapper class that gives direct access to the component arrays of a table, the table data
#[derive(Debug, Clone, Copy, Eq)]
#[repr(C)]
pub struct Table<'a> {
    pub(crate) table: NonNull<sys::ecs_table_t>,
    world: WorldRef<'a>,
}

impl PartialEq for Table<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.table == other.table
    }
}

impl<'a> Table<'a> {
    /// Creates a wrapper around a table
    ///
    /// # Arguments
    ///
    /// * `world` - The world the table is in
    /// * `table` - The table to wrap
    pub fn new(world: impl WorldProvider<'a>, table: NonNull<sys::ecs_table_t>) -> Self {
        Self {
            world: world.world(),
            table,
        }
    }

    /// Returns the raw table pointer
    pub fn raw_table_ptr(&self) -> *mut sys::ecs_table_t {
        self.table.as_ptr()
    }
}

#[derive(Debug, Clone, Copy)]
pub struct TableRange<'a> {
    pub table: Table<'a>,
    offset: i32,
    count: i32,
}

impl<'a> TableRange<'a> {
    /// Creates a new table range
    ///
    /// # Arguments
    ///
    /// * `table` - The table to wrap
    /// * `offset` - The offset to start from
    /// * `count` - The count of the range
    ///
    /// # Returns
    ///
    /// A new table range
    pub fn new(table: Table<'a>, offset: i32, count: i32) -> Self {
        Self {
            table,
            offset,
            count,
        }
    }

    /// Creates a new table range from raw table ptr.
    ///
    /// # Arguments
    ///
    /// * `world` - The world the table is in
    /// * `table` - The table to wrap
    /// * `offset` - The offset to start from
    /// * `count` - The count of the range
    ///
    /// # Returns
    ///
    /// A new table range
    ///
    /// # Safety
    ///
    /// The world and table pointers must be valid
    pub(crate) fn new_raw(
        world: impl WorldProvider<'a>,
        table: NonNull<sys::ecs_table_t>,
        offset: i32,
        count: i32,
    ) -> Self {
        Self {
            table: Table::new(world, table),
            offset,
            count,
        }
    }
}

pub trait TableOperations<'a>: IntoTable {
    fn table(&self) -> Table<'a>;
    fn offset(&self) -> i32;
    fn world(&self) -> WorldRef<'a>;

    /// Returns the table count
    fn count(&self) -> i32 {
        let table = self.table_ptr_mut();
        unsafe { sys::ecs_table_count(table) }
    }

    /// Get number of allocated elements in table
    fn size(&self) -> i32 {
        let table = self.table_ptr_mut();
        unsafe { sys::ecs_table_size(table) }
    }

    /// Get array with entity ids
    fn entities(&self) -> &[Entity] {
        let table = self.table_ptr_mut();
        let entities = unsafe { sys::ecs_table_entities(table) };
        if entities.is_null() {
            return &[];
        }
        let count = self.count();
        unsafe { core::slice::from_raw_parts(entities as *const Entity, count as usize) }
    }

    fn clear_entities(&self) {
        let world = self.world().world_ptr_mut();
        let table = self.table_ptr_mut();
        unsafe { sys::ecs_table_clear_entities(world, table) };
    }

    /// Converts table type to string
    fn to_string(&self) -> Option<String> {
        unsafe {
            let raw_ptr = sys::ecs_table_str(self.world().world_ptr(), self.table_ptr_mut());

            if raw_ptr.is_null() {
                return None;
            }

            let len = CStr::from_ptr(raw_ptr).to_bytes().len();

            Some(String::from_utf8_unchecked(Vec::from_raw_parts(
                raw_ptr as *mut u8,
                len,
                len,
            )))
        }
    }

    /// Returns the type of the table
    fn archetype(&self) -> Archetype<'a> {
        let type_vec = unsafe { sys::ecs_table_get_type(self.table_ptr_mut()) };
        let slice = if unsafe { !(*type_vec).array.is_null() && (*type_vec).count != 0 } {
            unsafe {
                core::slice::from_raw_parts((*type_vec).array as _, (*type_vec).count as usize)
            }
        } else {
            &[]
        };
        let world = self.world();
        // Safety: we already know table_ptr is NonNull
        unsafe {
            Archetype::new_locked(
                world,
                slice,
                TableLock::new(world, NonNull::new_unchecked(self.table_ptr_mut())),
            )
        }
    }

    /// Find type index for (component) id
    ///
    /// # Arguments
    ///
    /// * `id` - The id of the component
    ///
    /// # Returns
    ///
    /// The index of the id in the table type, or `None` if the id is not found
    fn find_type_index(&self, id: impl IntoId) -> Option<i32> {
        let index = unsafe {
            sys::ecs_table_get_type_index(
                self.world().world_ptr(),
                self.table_ptr_mut(),
                *id.into_id(self.world()),
            )
        };
        if index == -1 { None } else { Some(index) }
    }

    /// Find index for (component) id in table type
    ///
    /// This operation returns the index of first occurrence of the id in the table type. The id may be a wildcard.
    /// The found id may be different from the provided id if it is a wildcard.
    ///
    /// This is a constant time operation.
    ///
    /// # Arguments
    ///
    /// * `id` - The id of the component
    ///
    /// # Returns
    ///
    /// The index of the id in the table, or `None` if the id is not in the table
    fn find_column_index(&self, id: impl IntoId) -> Option<i32> {
        let index = unsafe {
            sys::ecs_table_get_column_index(
                self.world().world_ptr(),
                self.table_ptr_mut(),
                *id.into_id(self.world()),
            )
        };
        if index == -1 { None } else { Some(index) }
    }

    /// Test if table has (component) id
    ///
    /// This is a constant time operation.
    ///
    /// # Arguments
    ///
    /// * `id` - The id of the component
    ///
    /// # Returns
    ///
    /// True if the table has the component id, false otherwise
    fn has(&self, id: impl IntoId) -> bool {
        self.find_type_index(id).is_some()
    }

    /// Get column, components array ptr from table by column index.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the component
    ///
    /// # Returns
    ///
    /// Some(Pointer) to the column, or `None` if not a component
    fn column_untyped(&self, index: i32) -> Option<*mut c_void> {
        let ptr = unsafe { sys::ecs_table_get_column(self.table_ptr_mut(), index, self.offset()) };
        if ptr.is_null() { None } else { Some(ptr) }
    }

    /// Get column, components array ptr from table by component type.
    ///
    /// # Type parameters
    ///
    /// * `T` - The type of the component
    ///
    /// # Returns
    ///
    /// Some(Pointer) to the column, or `None` if not found
    //TODO this should return a field IMO
    fn get_mut<T: ComponentId>(&mut self) -> Option<&mut [T]> {
        self.get_mut_untyped(T::entity_id(self.world()))
            .map(|ptr| unsafe {
                core::slice::from_raw_parts_mut(ptr as *mut T, (self.count()) as usize)
            })
    }

    /// Get column, components array ptr from table by component type.
    ///
    /// # Arguments
    ///
    /// * `id` - The id of the component
    ///
    /// # Returns
    ///
    /// Some(Pointer) to the column, or `None` if not found
    fn get_mut_untyped(&self, id: sys::ecs_id_t) -> Option<*mut c_void> {
        if let Some(index) = self.find_column_index(id) {
            self.column_untyped(index)
        } else {
            None
        }
    }

    /// Get column, components array ptr from table by pair ids.
    ///
    /// # Arguments
    ///
    /// * `first` - The id of the first component
    /// * `second` - The id of the second component
    ///
    /// # Returns
    ///
    /// Some(Pointer) to the column, or `None` if not found
    fn get_pair_ids_mut_untyped(
        &self,
        first: impl Into<Entity>,
        second: impl Into<Entity>,
    ) -> Option<*mut c_void> {
        self.get_mut_untyped(ecs_pair(*first.into(), *second.into()))
    }

    /// Get column, components array ptr from table by pair of component types.
    ///
    /// # Type parameters
    ///
    /// * `First` - The type of the first component
    /// * `Second` - The type of the second component
    ///
    /// # Returns
    ///
    /// Some(Pointer) to the column, or `None` if not found
    fn get_pair_mut_untyped<First: ComponentId, Second: ComponentId>(&self) -> Option<*mut c_void> {
        let world = self.world();
        self.get_pair_ids_mut_untyped(First::entity_id(world), Second::entity_id(world))
    }

    /// Get column size from table at the provided column index.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the column
    ///
    /// # Returns
    ///
    /// The size of the column
    fn column_size(&self, index: i32) -> usize {
        unsafe { sys::ecs_table_get_column_size(self.table_ptr_mut(), index) }
    }

    /// Return depth for table in tree for relationship type.
    /// Depth is determined by counting the number of targets encountered while traversing up the
    /// relationship tree for rel. Only acyclic relationships are supported.
    ///
    /// # Arguments
    ///
    /// * `rel` - The id of the relationship
    ///
    /// # Returns
    ///
    /// The depth of the relationship
    fn depth(&self, rel: impl IntoEntity) -> i32 {
        let world = self.world();
        unsafe {
            sys::ecs_table_get_depth(
                world.world_ptr_mut(),
                self.table_ptr_mut(),
                *rel.into_entity(world),
            )
        }
    }

    /// get table records array
    fn records(&self) -> &[sys::ecs_table_record_t] {
        let records = unsafe { sys::flecs_table_records(self.table_ptr_mut()) };

        unsafe { core::slice::from_raw_parts(records.array, records.count as usize) }
    }

    /// get table id
    fn id(&self) -> u64 {
        unsafe { sys::flecs_table_id(self.table_ptr_mut()) }
    }

    /// lock table
    fn lock(&self) {
        unsafe { sys::ecs_table_lock(self.world().world_ptr_mut(), self.table_ptr_mut()) };
    }

    /// unlock table
    fn unlock(&self) {
        unsafe { sys::ecs_table_unlock(self.world().world_ptr_mut(), self.table_ptr_mut()) };
    }

    fn has_flags(&self, flags: TableFlags) -> bool {
        unsafe { sys::ecs_table_has_flags(self.table_ptr_mut(), flags.bits()) }
    }
}

impl<'a> TableOperations<'a> for Table<'a> {
    fn table(&self) -> Table<'a> {
        *self
    }

    fn offset(&self) -> i32 {
        0
    }

    fn world(&self) -> WorldRef<'a> {
        self.world
    }

    /// Returns the table count
    fn count(&self) -> i32 {
        unsafe { sys::ecs_table_count(self.table_ptr_mut()) }
    }
}

impl<'a> TableOperations<'a> for TableRange<'a> {
    fn table(&self) -> Table<'a> {
        self.table
    }

    fn offset(&self) -> i32 {
        self.offset
    }

    fn world(&self) -> WorldRef<'a> {
        self.table.world
    }

    /// Returns the table range count
    fn count(&self) -> i32 {
        self.count
    }
}

/// A lock on a [`Table`].
///
/// When a table is locked, modifications to it will throw an assert. When the
/// table is locked recursively, it will take an equal amount of unlock
/// operations to actually unlock the table.
///
/// Table locks can be used to build safe iterators where it is guaranteed that
/// the contents of a table are not modified while it is being iterated.
///
/// The operation only works when called on the world, and has no side effects
/// when called on a stage. The assumption is that when called on a stage,
/// operations are deferred already.
pub(crate) struct TableLock<'a> {
    world: WorldRef<'a>,
    table: NonNull<sys::ecs_table_t>,
}

impl<'a> TableLock<'a> {
    pub fn new(world: impl WorldProvider<'a>, table: NonNull<sys::ecs_table_t>) -> Self {
        unsafe { sys::ecs_table_lock(world.world_ptr_mut(), table.as_ptr()) };
        Self {
            world: world.world(),
            table,
        }
    }
}

impl Drop for TableLock<'_> {
    fn drop(&mut self) {
        if std::thread::panicking() {
            return;
        }

        unsafe {
            sys::ecs_table_unlock(self.world.world_ptr_mut(), self.table.as_ptr());
        }
    }
}