flecs_ecs 0.2.2

Rust API for the C/CPP flecs ECS library <https://github.com/SanderMertens/flecs>
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
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
//! Registering and working with components

use core::{ffi::c_void, fmt::Debug, fmt::Display, marker::PhantomData, ops::Deref, ptr};

use crate::core::*;
#[cfg(feature = "flecs_meta")]
use crate::prelude::FetchedId;
use crate::sys;

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

extern crate alloc;
use alloc::boxed::Box;
use flecs_ecs_derive::extern_abi;

/// Component class.
/// Class used to register components and component metadata.
pub struct Component<'a, T> {
    pub base: UntypedComponent<'a>,
    _marker: PhantomData<T>,
}

impl<T> Display for Component<'_, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.base.entity)
    }
}

impl<T> Debug for Component<'_, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:?}", self.base.entity)
    }
}

impl<T> Clone for Component<'_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for Component<'_, T> {}

impl<'a, T> Deref for Component<'a, T> {
    type Target = UntypedComponent<'a>;

    fn deref(&self) -> &Self::Target {
        &self.base
    }
}

impl<'a, T: ComponentId> Component<'a, T> {
    /// Create a new component that is marked within Rust.
    ///
    /// # Arguments
    ///
    /// * `world`: the world.
    pub(crate) fn new(world: impl WorldProvider<'a>) -> Self {
        let world = world.world();
        let id = T::__register_or_get_id::<false>(world);

        let world = world.world();
        Self {
            base: UntypedComponent::new_from(world, id),
            _marker: PhantomData,
        }
    }

    /// Create a new component with a name.
    ///
    /// # Arguments
    ///
    /// * `world`: the world.
    /// * `name`: the name of the component.
    pub(crate) fn new_named(world: impl WorldProvider<'a>, name: &str) -> Self {
        let id = T::__register_or_get_id_named::<false>(world.world(), name);

        let world = world.world();
        Self {
            base: UntypedComponent::new_from(world, id),
            _marker: PhantomData,
        }
    }

    #[doc(hidden)]
    pub fn new_w_id(world: impl WorldProvider<'a>, id: impl IntoEntity) -> Self {
        Self {
            base: UntypedComponent::new_from(world, id),
            _marker: PhantomData,
        }
    }
}
impl<'a, T> Component<'a, T> {
    /// Create a new component that is not marked within Rust.
    ///
    /// # Arguments
    ///
    /// * `world`: the world.
    #[cfg(feature = "flecs_meta")]
    pub(crate) fn new_id(world: impl WorldProvider<'a>, id: FetchedId<T>) -> Self {
        let world = world.world();

        Self {
            base: UntypedComponent::new_from(world, id),
            _marker: PhantomData,
        }
    }

    /// Create a new component with a name.
    ///
    /// # Arguments
    ///
    /// * `world`: the world.
    /// * `name`: the name of the component.
    ///   Return the component as an entity
    #[cfg(feature = "flecs_meta")]
    pub fn new_named_id(world: impl WorldProvider<'a>, id: FetchedId<T>, name: &str) -> Self {
        let _name = compact_str::format_compact!("{}\0", name);
        let world = world.world();
        let entity = world.entity_from_id(id.id());
        entity.get_name().map_or_else(
            || {
                entity.set_name(name);
            },
            |current_name| {
                if current_name != name {
                    entity.set_name(name);
                }
            },
        );

        Self {
            base: UntypedComponent::new_from(world, id),
            _marker: PhantomData,
        }
    }
    /// Return the component as an entity
    #[inline(always)]
    pub fn entity(self) -> EntityView<'a> {
        self.base.entity
    }

    /// Get the binding context for the component.
    ///
    /// # Arguments
    ///
    /// * `type_hooks`: the type hooks.
    fn get_binding_context(type_hooks: &mut sys::ecs_type_hooks_t) -> &mut ComponentBindingCtx {
        let mut binding_ctx: *mut ComponentBindingCtx = type_hooks.binding_ctx as *mut _;

        if binding_ctx.is_null() {
            let new_binding_ctx = Box::<ComponentBindingCtx>::default();
            let static_ref = Box::leak(new_binding_ctx);
            binding_ctx = static_ref;
            type_hooks.binding_ctx = binding_ctx as *mut c_void;
            type_hooks.binding_ctx_free = Some(Self::binding_ctx_drop);
        }
        unsafe { &mut *binding_ctx }
    }

    /// Get the type hooks for the component.
    pub fn get_hooks(&self) -> sys::ecs_type_hooks_t {
        let type_hooks: *const sys::ecs_type_hooks_t =
            unsafe { sys::ecs_get_hooks_id(self.world.world_ptr(), *self.id) };
        if type_hooks.is_null() {
            sys::ecs_type_hooks_t::default()
        } else {
            unsafe { *type_hooks }
        }
    }

    /// Function to free the binding context.
    #[extern_abi]
    unsafe fn binding_ctx_drop(ptr: *mut c_void) {
        let ptr_struct: *mut ComponentBindingCtx = ptr as *mut ComponentBindingCtx;
        unsafe {
            ptr::drop_in_place(ptr_struct);
        }
    }

    /// Register on add hook.
    pub fn on_add<Func>(self, func: Func) -> Self
    where
        Func: FnMut(EntityView, &mut T) + 'static,
    {
        let mut type_hooks: sys::ecs_type_hooks_t = self.get_hooks();

        ecs_assert!(
            type_hooks.on_add.is_none(),
            FlecsErrorCode::InvalidOperation,
            "on_add hook already set for component {}",
            core::any::type_name::<T>()
        );

        let binding_ctx = Self::get_binding_context(&mut type_hooks);
        let boxed_func = Box::new(func);
        let static_ref = Box::leak(boxed_func);
        binding_ctx.on_add = Some(static_ref as *mut _ as *mut c_void);
        binding_ctx.free_on_add = Some(Self::on_add_drop::<Func>);
        type_hooks.on_add = Some(Self::run_add::<Func>);
        unsafe { sys::ecs_set_hooks_id(self.world.world_ptr_mut(), *self.id, &type_hooks) };
        self
    }

    /// Register on remove hook.
    pub fn on_remove<Func>(self, func: Func) -> Self
    where
        Func: FnMut(EntityView, &mut T) + 'static,
    {
        let mut type_hooks: sys::ecs_type_hooks_t = self.get_hooks();

        ecs_assert!(
            type_hooks.on_remove.is_none(),
            FlecsErrorCode::InvalidOperation,
            "on_remove hook already set for component {}",
            core::any::type_name::<T>()
        );

        let binding_ctx = Self::get_binding_context(&mut type_hooks);
        let boxed_func = Box::new(func);
        let static_ref = Box::leak(boxed_func);
        binding_ctx.on_remove = Some(static_ref as *mut _ as *mut c_void);
        binding_ctx.free_on_remove = Some(Self::on_remove_drop::<Func>);
        type_hooks.on_remove = Some(Self::run_remove::<Func>);
        unsafe { sys::ecs_set_hooks_id(self.world.world_ptr_mut(), *self.id, &type_hooks) };
        self
    }

    /// Register on set hook.
    pub fn on_set<Func>(self, func: Func) -> Self
    where
        Func: FnMut(EntityView, &mut T) + 'static,
    {
        let mut type_hooks: sys::ecs_type_hooks_t = self.get_hooks();

        ecs_assert!(
            type_hooks.on_set.is_none(),
            FlecsErrorCode::InvalidOperation,
            "on_set hook already set for component {}",
            core::any::type_name::<T>()
        );

        let binding_ctx = Self::get_binding_context(&mut type_hooks);
        let boxed_func = Box::new(func);
        let static_ref = Box::leak(boxed_func);
        binding_ctx.on_set = Some(static_ref as *mut _ as *mut c_void);
        binding_ctx.free_on_set = Some(Self::on_set_drop::<Func>);
        type_hooks.on_set = Some(Self::run_set::<Func>);
        unsafe { sys::ecs_set_hooks_id(self.world.world_ptr_mut(), *self.id, &type_hooks) };
        self
    }

    /// Register on replace hook.
    pub fn on_replace<Func>(self, func: Func) -> Self
    where
        Func: FnMut(EntityView, &mut T, &mut T) + 'static,
    {
        let mut type_hooks: sys::ecs_type_hooks_t = self.get_hooks();

        ecs_assert!(
            type_hooks.on_replace.is_none(),
            FlecsErrorCode::InvalidOperation,
            "on_replace hook already set for component {}",
            core::any::type_name::<T>()
        );

        let binding_ctx = Self::get_binding_context(&mut type_hooks);
        let boxed_func = Box::new(func);
        let static_ref = Box::leak(boxed_func);
        binding_ctx.on_replace = Some(static_ref as *mut _ as *mut c_void);
        binding_ctx.free_on_replace = Some(Self::on_replace_drop::<Func>);
        type_hooks.on_replace = Some(Self::run_replace::<Func>);
        unsafe { sys::ecs_set_hooks_id(self.world.world_ptr_mut(), *self.id, &type_hooks) };
        self
    }

    /// Function to free the on add hook.
    #[extern_abi]
    unsafe fn on_add_drop<Func>(func: *mut c_void)
    where
        Func: FnMut(EntityView, &mut T) + 'static,
    {
        let ptr_func: *mut Func = func as *mut Func;
        unsafe {
            ptr::drop_in_place(ptr_func);
        }
    }

    /// Function to free the on remove hook.
    #[extern_abi]
    unsafe fn on_remove_drop<Func>(func: *mut c_void)
    where
        Func: FnMut(EntityView, &mut T) + 'static,
    {
        let ptr_func: *mut Func = func as *mut Func;
        unsafe {
            ptr::drop_in_place(ptr_func);
        }
    }

    /// Function to free the on set hook.
    #[extern_abi]
    unsafe fn on_set_drop<Func>(func: *mut c_void)
    where
        Func: FnMut(EntityView, &mut T) + 'static,
    {
        let ptr_func: *mut Func = func as *mut Func;
        unsafe {
            ptr::drop_in_place(ptr_func);
        }
    }

    /// Function to free the on replace hook.
    #[extern_abi]
    unsafe fn on_replace_drop<Func>(func: *mut c_void)
    where
        Func: FnMut(EntityView, &mut T, &mut T) + 'static,
    {
        let ptr_func: *mut Func = func as *mut Func;
        unsafe {
            ptr::drop_in_place(ptr_func);
        }
    }

    /// Function to run the on add hook.
    #[extern_abi]
    unsafe fn run_add<Func>(iter: *mut sys::ecs_iter_t)
    where
        Func: FnMut(EntityView, &mut T) + 'static,
    {
        unsafe {
            let iter = &*iter;
            let ctx: *mut ComponentBindingCtx = iter.callback_ctx as *mut _;
            let on_add = (*ctx).on_add.unwrap();
            let on_add = on_add as *mut Func;
            let on_add = &mut *on_add;
            let world = WorldRef::from_ptr(iter.world);
            let entity = EntityView::new_from(world, *iter.entities);
            let component = if (iter.ref_fields | iter.up_fields) == 0 {
                flecs_field::<T>(iter, 0)
            } else {
                flecs_field_at::<T>(iter, 0, 0)
            };
            on_add(entity, &mut *component);
        }
    }

    /// Function to run the on set hook.
    #[extern_abi]
    unsafe fn run_set<Func>(iter: *mut sys::ecs_iter_t)
    where
        Func: FnMut(EntityView, &mut T) + 'static,
    {
        let iter = unsafe { &*iter };
        let ctx: *mut ComponentBindingCtx = iter.callback_ctx as *mut _;
        let on_set = unsafe { (*ctx).on_set.unwrap() };
        let on_set = on_set as *mut Func;
        let on_set = unsafe { &mut *on_set };
        let world = unsafe { WorldRef::from_ptr(iter.world) };
        let entity = EntityView::new_from(world, unsafe { *iter.entities });
        let component = if (iter.ref_fields | iter.up_fields) == 0 {
            flecs_field::<T>(iter, 0)
        } else {
            unsafe { flecs_field_at::<T>(iter, 0, 0) }
        };
        on_set(entity, unsafe { &mut *component });
    }

    /// Function to run the on replace hook.
    #[extern_abi]
    unsafe fn run_replace<Func>(iter: *mut sys::ecs_iter_t)
    where
        Func: FnMut(EntityView, &mut T, &mut T) + 'static,
    {
        let iter = unsafe { &*iter };
        let ctx: *mut ComponentBindingCtx = iter.callback_ctx as *mut _;
        let on_replace = unsafe { (*ctx).on_replace.unwrap() };
        let on_replace = on_replace as *mut Func;
        let on_replace = unsafe { &mut *on_replace };
        let world = unsafe { WorldRef::from_ptr(iter.world) };
        let entity = EntityView::new_from(world, unsafe { *iter.entities });
        let (prev, next) = if (iter.ref_fields | iter.up_fields) == 0 {
            (flecs_field::<T>(iter, 0), flecs_field::<T>(iter, 1))
        } else {
            unsafe {
                (
                    flecs_field_at::<T>(iter, 0, 0),
                    flecs_field_at::<T>(iter, 1, 0),
                )
            }
        };
        on_replace(entity, unsafe { &mut *prev }, unsafe { &mut *next });
    }

    /// Function to run the on remove hook.
    #[extern_abi]
    unsafe fn run_remove<Func>(iter: *mut sys::ecs_iter_t)
    where
        Func: FnMut(EntityView, &mut T) + 'static,
    {
        unsafe {
            let iter = &*iter;
            let ctx: *mut ComponentBindingCtx = iter.callback_ctx as *mut _;
            let on_remove = (*ctx).on_remove.unwrap();
            let on_remove = on_remove as *mut Func;
            let on_remove = &mut *on_remove;
            let world = WorldRef::from_ptr(iter.world);
            let entity = EntityView::new_from(world, *iter.entities);
            let component = if (iter.ref_fields | iter.up_fields) == 0 {
                flecs_field::<T>(iter, 0)
            } else {
                flecs_field_at::<T>(iter, 0, 0)
            };
            on_remove(entity, &mut *component);
        }
    }
}

mod eq_operations {
    use super::*;

    impl<'a, T: ComponentId> PartialEq<Component<'a, T>> for u64 {
        #[inline]
        fn eq(&self, other: &Component<'a, T>) -> bool {
            *self == other.base.entity.id
        }
    }

    impl<T: ComponentId> PartialEq<u64> for Component<'_, T> {
        #[inline]
        fn eq(&self, other: &u64) -> bool {
            self.base.entity.id == *other
        }
    }

    impl<T: ComponentId> PartialEq<Entity> for Component<'_, T> {
        #[inline]
        fn eq(&self, other: &Entity) -> bool {
            self.base.entity.id == *other
        }
    }

    impl<T: ComponentId> PartialEq<Id> for Component<'_, T> {
        #[inline]
        fn eq(&self, other: &Id) -> bool {
            self.base.entity.id == *other
        }
    }

    impl<'a, T: ComponentId> PartialEq<EntityView<'a>> for Component<'a, T> {
        #[inline]
        fn eq(&self, other: &EntityView<'a>) -> bool {
            self.base.entity == *other
        }
    }

    impl<'a, T: ComponentId> PartialEq<IdView<'a>> for Component<'a, T> {
        #[inline]
        fn eq(&self, other: &IdView<'a>) -> bool {
            self.base.entity == other.id
        }
    }

    impl<'a, T: ComponentId> PartialEq<UntypedComponent<'a>> for Component<'a, T> {
        #[inline]
        fn eq(&self, other: &UntypedComponent<'a>) -> bool {
            self.base.entity == other.entity
        }
    }

    impl<T: ComponentId> PartialEq for Component<'_, T> {
        #[inline]
        fn eq(&self, other: &Self) -> bool {
            self.base.entity == other.base.entity
        }
    }

    impl<T: ComponentId> Eq for Component<'_, T> {}

    impl<'a, T: ComponentId> PartialOrd<Component<'a, T>> for u64 {
        #[inline]
        fn partial_cmp(&self, other: &Component<'a, T>) -> Option<core::cmp::Ordering> {
            self.partial_cmp(&other.base.entity.id)
        }
    }
}

mod ord_operations {
    use super::*;
    impl<T: ComponentId> PartialOrd<u64> for Component<'_, T> {
        #[inline]
        fn partial_cmp(&self, other: &u64) -> Option<core::cmp::Ordering> {
            self.base.entity.id.partial_cmp(other)
        }
    }

    impl<T: ComponentId> PartialOrd<Entity> for Component<'_, T> {
        #[inline]
        fn partial_cmp(&self, other: &Entity) -> Option<core::cmp::Ordering> {
            self.base.entity.id.partial_cmp(other)
        }
    }

    impl<T: ComponentId> PartialOrd<Id> for Component<'_, T> {
        #[inline]
        fn partial_cmp(&self, other: &Id) -> Option<core::cmp::Ordering> {
            self.base.entity.id.partial_cmp(other)
        }
    }

    impl<'a, T: ComponentId> PartialOrd<EntityView<'a>> for Component<'a, T> {
        #[inline]
        fn partial_cmp(&self, other: &EntityView<'a>) -> Option<core::cmp::Ordering> {
            self.base.entity.partial_cmp(other)
        }
    }

    impl<'a, T: ComponentId> PartialOrd<IdView<'a>> for Component<'a, T> {
        #[inline]
        fn partial_cmp(&self, other: &IdView<'a>) -> Option<core::cmp::Ordering> {
            self.base.entity.partial_cmp(&other.id)
        }
    }

    impl<'a, T: ComponentId> PartialOrd<UntypedComponent<'a>> for Component<'a, T> {
        #[inline]
        fn partial_cmp(&self, other: &UntypedComponent<'a>) -> Option<core::cmp::Ordering> {
            self.base.entity.partial_cmp(&other.entity)
        }
    }

    impl<T: ComponentId> PartialOrd for Component<'_, T> {
        #[inline]
        fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
            Some(self.cmp(other))
        }
    }

    impl<T: ComponentId> Ord for Component<'_, T> {
        #[inline]
        fn cmp(&self, other: &Self) -> core::cmp::Ordering {
            self.base.entity.cmp(&other.base.entity)
        }
    }
}