Skip to main content

sim_logic/ecs/
identity.rs

1//! Opaque runtime identities.
2
3use std::{
4    error::Error,
5    fmt,
6    sync::atomic::{AtomicU64, Ordering},
7};
8
9use bevy_ecs::{component::Component, entity::Entity, prelude::Resource, query::QueryData};
10
11static NEXT_APPLICATION_ID: AtomicU64 = AtomicU64::new(1);
12
13/// Failure to issue another never-reused runtime identity.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct IdentityExhausted;
16
17impl fmt::Display for IdentityExhausted {
18    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
19        formatter.write_str("Sim;Logic runtime identity space is exhausted")
20    }
21}
22
23impl Error for IdentityExhausted {}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub(crate) struct ApplicationId(u64);
27
28impl ApplicationId {
29    pub(crate) fn issue() -> Result<Self, IdentityExhausted> {
30        NEXT_APPLICATION_ID
31            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
32                current.checked_add(1)
33            })
34            .map(Self)
35            .map_err(|_| IdentityExhausted)
36    }
37
38    #[cfg(test)]
39    pub(crate) const fn from_raw(value: u64) -> Self {
40        Self(value)
41    }
42}
43
44/// Identifies one prepared ECS world within one application instance.
45///
46/// Generations are issued by the runtime and never reused. A generation may be
47/// absent from the active application when preparation of its candidate fails.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
49pub struct WorldGeneration {
50    application: ApplicationId,
51    sequence: u64,
52}
53
54impl WorldGeneration {
55    pub(crate) const fn new(application: ApplicationId, sequence: u64) -> Self {
56        Self {
57            application,
58            sequence,
59        }
60    }
61
62    #[cfg(test)]
63    pub(crate) const fn belongs_to(self, application: ApplicationId) -> bool {
64        self.application.0 == application.0
65    }
66}
67
68/// Identifies one registered no-payload World factory.
69///
70/// The handle is meaningful only to the application that issued it. Its
71/// internal registry slot and registration generation are intentionally
72/// inaccessible.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74pub struct WorldFactoryId {
75    application: ApplicationId,
76    slot: u32,
77    registration_generation: u32,
78}
79
80impl WorldFactoryId {
81    pub(crate) const fn new(
82        application: ApplicationId,
83        slot: u32,
84        registration_generation: u32,
85    ) -> Self {
86        Self {
87            application,
88            slot,
89            registration_generation,
90        }
91    }
92
93    pub(crate) const fn application(self) -> ApplicationId {
94        self.application
95    }
96
97    pub(crate) const fn slot(self) -> u32 {
98        self.slot
99    }
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
103pub(crate) enum IntentKind {
104    Input,
105    Direct,
106}
107
108/// A runtime-issued token identifying one causal transition occurrence.
109///
110/// Input-derived tokens may be used only while their input edge is being
111/// delivered. Direct tokens are valid only during their issuance frame. Tokens
112/// are runtime handles and are not stable or serializable identifiers.
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
114pub struct TransitionIntentToken {
115    application: ApplicationId,
116    origin: WorldGeneration,
117    issued_frame: u64,
118    occurrence: u64,
119    kind: IntentKind,
120}
121
122impl TransitionIntentToken {
123    pub(crate) const fn input(
124        application: ApplicationId,
125        origin: WorldGeneration,
126        issued_frame: u64,
127        occurrence: u64,
128    ) -> Self {
129        Self {
130            application,
131            origin,
132            issued_frame,
133            occurrence,
134            kind: IntentKind::Input,
135        }
136    }
137
138    pub(crate) const fn direct(
139        application: ApplicationId,
140        origin: WorldGeneration,
141        issued_frame: u64,
142        occurrence: u64,
143    ) -> Self {
144        Self {
145            application,
146            origin,
147            issued_frame,
148            occurrence,
149            kind: IntentKind::Direct,
150        }
151    }
152
153    pub(crate) const fn application(self) -> ApplicationId {
154        self.application
155    }
156
157    pub(crate) const fn origin(self) -> WorldGeneration {
158        self.origin
159    }
160
161    pub(crate) const fn issued_frame(self) -> u64 {
162        self.issued_frame
163    }
164
165    pub(crate) const fn kind(self) -> IntentKind {
166        self.kind
167    }
168}
169
170/// An entity identity scoped to one application and World generation.
171///
172/// Sim;Logic returns this opaque handle for managed entities and keeps its ECS
173/// storage private. Structural APIs accept the handle instead of a raw Bevy
174/// Entity so a stale identity cannot accidentally address an entity in a
175/// replacement World.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
177pub struct LogicEntity {
178    application: ApplicationId,
179    generation: WorldGeneration,
180    entity: Entity,
181}
182
183/// Private ECS storage for the World generation of a managed entity.
184///
185/// The raw Bevy entity is supplied by the query row when reconstructing the
186/// public handle. Keeping this component private prevents ordinary systems
187/// from replacing runtime provenance.
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Component)]
189pub(crate) struct ManagedEntity(WorldGeneration);
190
191#[derive(Debug, Clone, Copy, Resource)]
192pub(crate) struct WorldIdentityState {
193    application: ApplicationId,
194    generation: WorldGeneration,
195}
196
197impl WorldIdentityState {
198    pub(crate) const fn new(application: ApplicationId, generation: WorldGeneration) -> Self {
199        Self {
200            application,
201            generation,
202        }
203    }
204
205    pub(crate) fn owns(self, entity: LogicEntity) -> bool {
206        entity.application.0 == self.application.0 && entity.generation == self.generation
207    }
208
209    pub(crate) const fn generation(self) -> WorldGeneration {
210        self.generation
211    }
212}
213
214impl ManagedEntity {
215    pub(crate) const fn for_generation(generation: WorldGeneration) -> Self {
216        Self(generation)
217    }
218
219    #[cfg(test)]
220    pub(crate) const fn new(entity: LogicEntity) -> Self {
221        Self(entity.world_generation())
222    }
223
224    pub(crate) const fn handle(self, entity: Entity) -> LogicEntity {
225        LogicEntity::new(self.0.application, self.0, entity)
226    }
227}
228
229/// Read-only query data that yields an entity's managed Sim;Logic identity.
230///
231/// Use this inside a managed [`crate::query::Query`], for example
232/// `Query<(LogicEntityRef, &Health)>`. The private immutable field prevents a
233/// System from rewriting provenance. Managed point lookup accepts the
234/// resulting handle and does not expose raw Bevy entity lookup.
235#[derive(QueryData)]
236pub struct LogicEntityRef {
237    entity: Entity,
238    identity: &'static ManagedEntity,
239}
240
241impl LogicEntityRefItem<'_, '_> {
242    /// Copies the opaque managed handle carried by this query item.
243    pub const fn handle(&self) -> LogicEntity {
244        self.identity.handle(self.entity)
245    }
246}
247
248impl LogicEntity {
249    pub(crate) const fn new(
250        application: ApplicationId,
251        generation: WorldGeneration,
252        entity: Entity,
253    ) -> Self {
254        Self {
255            application,
256            generation,
257            entity,
258        }
259    }
260
261    /// Returns the World generation that owns this entity.
262    pub const fn world_generation(self) -> WorldGeneration {
263        self.generation
264    }
265
266    pub(crate) const fn application(self) -> ApplicationId {
267        self.application
268    }
269
270    pub(crate) const fn entity(self) -> Entity {
271        self.entity
272    }
273
274    pub(crate) const fn stable_bits(self) -> u64 {
275        self.entity.to_bits()
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282
283    #[test]
284    fn generations_keep_application_provenance() {
285        let first = WorldGeneration::new(ApplicationId::from_raw(1), 7);
286        let second = WorldGeneration::new(ApplicationId::from_raw(2), 7);
287
288        assert_ne!(first, second);
289        assert!(first.belongs_to(ApplicationId::from_raw(1)));
290        assert!(!first.belongs_to(ApplicationId::from_raw(2)));
291    }
292
293    #[test]
294    fn managed_storage_reconstructs_the_exact_raw_entity_without_storing_it() {
295        let application = ApplicationId::from_raw(9);
296        let generation = WorldGeneration::new(application, 17);
297        let raw = Entity::from_bits(0x0000_0007_0000_002a);
298        let managed = ManagedEntity::for_generation(generation);
299
300        assert_eq!(
301            managed.handle(raw),
302            LogicEntity::new(application, generation, raw)
303        );
304        assert_eq!(
305            std::mem::size_of::<ManagedEntity>(),
306            std::mem::size_of::<WorldGeneration>()
307        );
308        assert!(std::mem::size_of::<ManagedEntity>() < std::mem::size_of::<LogicEntity>());
309    }
310}