summaryrefslogtreecommitdiff
path: root/ecs/src/entity.rs
blob: 18f229a60dcfcc06938cefe607d0674bc86163da (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
use std::sync::atomic::{AtomicU64, Ordering};

use linkme::distributed_slice;

use crate::World;

static NEXT_UID: AtomicU64 = AtomicU64::new(0);

/// Unique entity ID.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Uid
{
    inner: u64,
}

impl Uid
{
    pub fn new(uid: u64) -> Self
    {
        debug_assert!(
            uid < NEXT_UID.load(Ordering::Relaxed),
            "Invalid entity UID {uid}"
        );

        Self { inner: uid }
    }

    pub fn new_unique() -> Self
    {
        Self {
            inner: NEXT_UID.fetch_add(1, Ordering::Relaxed),
        }
    }
}

#[macro_export]
macro_rules! static_entity {
    ($visibility: vis $ident: ident, $components: expr) => {
        $visibility static $ident: ::std::sync::LazyLock<$crate::entity::Uid> =
            ::std::sync::LazyLock::new(|| $crate::entity::Uid::new_unique());

        $crate::private::paste::paste! {
            mod [<__ecs_ $ident:lower _static_entity_priv>] {
                use super::*;

                #[$crate::private::linkme::distributed_slice(
                    $crate::entity::CREATE_STATIC_ENTITIES
                )]
                #[linkme(crate=$crate::private::linkme)]
                static CREATE_STATIC_ENTITY: fn(&$crate::World) = |world| {
                    world.create_entity_with_uid($components, *$ident);
                };
            }
        }
    }
}

#[distributed_slice]
#[doc(hidden)]
pub static CREATE_STATIC_ENTITIES: [fn(&World)];