summaryrefslogtreecommitdiff
path: root/ecs/src/uid.rs
diff options
context:
space:
mode:
authorHampusM <hampus@hampusmat.com>2024-11-11 00:11:22 +0100
committerHampusM <hampus@hampusmat.com>2024-11-11 00:11:22 +0100
commitdaf0bc236df25c0e9f44bc3e30839c16cda3f638 (patch)
tree7475e4e58686dd34366e641ec32f5a9374d66533 /ecs/src/uid.rs
parent17f63d9859e1c82a30c07bf110cf2b9872e2427e (diff)
refactor(ecs): use same ID for entities & components
Diffstat (limited to 'ecs/src/uid.rs')
-rw-r--r--ecs/src/uid.rs42
1 files changed, 42 insertions, 0 deletions
diff --git a/ecs/src/uid.rs b/ecs/src/uid.rs
new file mode 100644
index 0000000..56d84f9
--- /dev/null
+++ b/ecs/src/uid.rs
@@ -0,0 +1,42 @@
+use std::mem::transmute;
+use std::sync::atomic::{AtomicU32, Ordering};
+
+static NEXT: AtomicU32 = AtomicU32::new(1);
+
+// Bit 0 and 1 for the kind
+const KIND_BITS: u64 = 0x03;
+
+#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
+#[repr(u8)]
+pub enum Kind
+{
+ Entity = 2,
+ Component = 1,
+}
+
+/// Unique entity/component ID.
+#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
+pub struct Uid
+{
+ inner: u64,
+}
+
+impl Uid
+{
+ /// Returns a new unique entity/component ID.
+ pub fn new_unique(kind: Kind) -> Self
+ {
+ let id_part = NEXT.fetch_add(1, Ordering::Relaxed);
+
+ Self {
+ inner: ((id_part as u64) << 32) | kind as u64,
+ }
+ }
+
+ pub fn kind(&self) -> Kind
+ {
+ // SAFETY: The kind bits cannot be invalid since they are set using the Kind enum
+ // in the new_unique function
+ unsafe { transmute((self.inner & KIND_BITS) as u8) }
+ }
+}