summaryrefslogtreecommitdiff
path: root/ecs/src/lib.rs
blob: 6725d81c10fc28db3c04b8849d5961f8609812d9 (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
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
#![deny(clippy::all, clippy::pedantic)]

use std::any::{type_name, TypeId};
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::Debug;
use std::mem::ManuallyDrop;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use crate::actions::Action;
use crate::component::storage::Storage as ComponentStorage;
use crate::component::{Component, Id as ComponentId, Sequence as ComponentSequence};
use crate::entity::{Uid as EntityUid, CREATE_STATIC_ENTITIES};
use crate::event::component::{
    create_added_id as create_component_added_event_id,
    create_removed_id as create_component_removed_event_id,
    TypeTransformComponentsToAddedEvents,
};
use crate::event::start::Start as StartEvent;
use crate::event::{Event, Id as EventId, Ids, Sequence as EventSequence};
use crate::extension::{Collector as ExtensionCollector, Extension};
use crate::lock::{Lock, WriteGuard};
use crate::query::options::Options as QueryOptions;
use crate::sole::Sole;
use crate::stats::Stats;
use crate::system::{System, TypeErased as TypeErasedSystem};
use crate::tuple::Reduce as TupleReduce;
use crate::type_name::TypeName;

pub mod actions;
pub mod component;
pub mod entity;
pub mod event;
pub mod extension;
pub mod lock;
pub mod query;
pub mod relationship;
pub mod sole;
pub mod stats;
pub mod system;
pub mod tuple;
pub mod type_name;

#[doc(hidden)]
pub mod private;

mod archetype;
mod util;

pub use ecs_macros::{Component, Sole};

pub use crate::query::Query;

#[derive(Debug, Default)]
pub struct World
{
    systems: Vec<TypeErasedSystem>,
    data: WorldData,
    stop: AtomicBool,
}

impl World
{
    #[must_use]
    pub fn new() -> Self
    {
        let mut world = Self::default();

        world
            .add_sole(Stats::default())
            .expect("World already has stats sole");

        world
    }

    /// Creates a new entity with the given components.
    ///
    /// # Panics
    /// Will panic if mutable internal lock cannot be acquired.
    pub fn create_entity<Comps>(&mut self, components: Comps) -> EntityUid
    where
        Comps: ComponentSequence + TupleReduce<TypeTransformComponentsToAddedEvents>,
        Comps::Out: EventSequence,
    {
        let entity_uid = EntityUid::new_unique();

        self.create_entity_with_uid(components, entity_uid);

        entity_uid
    }

    #[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
    pub fn create_entity_with_uid<Comps>(&self, components: Comps, entity_uid: EntityUid)
    where
        Comps: ComponentSequence + TupleReduce<TypeTransformComponentsToAddedEvents>,
        Comps::Out: EventSequence,
    {
        #[allow(unused_variables)]
        if let Err(err) = self
            .data
            .component_storage
            .write_nonblock()
            .expect("Failed to acquire read-write component storage lock")
            .push_entity(entity_uid, components.into_vec())
        {
            #[cfg(feature = "debug")]
            tracing::error!("Failed to create entity: {err}");

            return;
        };

        for component_added_event_id in <Comps::Out as EventSequence>::ids().iter() {
            self.emit_event_by_id(*component_added_event_id);
        }
    }

    /// Adds a globally shared singleton value.
    ///
    /// # Errors
    /// Returns `Err` if this [`Sole`] has already been added.
    pub fn add_sole<SoleT>(&mut self, sole: SoleT) -> Result<(), SoleAlreadyExistsError>
    where
        SoleT: Sole,
    {
        self.data.sole_storage.insert(sole)
    }

    pub fn register_system<'this, EventT, SystemImpl>(
        &'this mut self,
        event: EventT,
        system: impl System<'this, SystemImpl>,
    ) where
        EventT: Event,
    {
        self.systems.push(system.into_type_erased());

        self.data
            .events
            .entry(EventT::id())
            .or_default()
            .push(self.systems.len() - 1);

        drop(event);
    }

    /// Adds a extensions.
    ///
    /// # Panics
    /// Will panic if mutable internal lock cannot be acquired.
    pub fn add_extension(&mut self, extension: impl Extension)
    {
        let extension_collector = ExtensionCollector::new(self);

        extension.collect(extension_collector);
    }

    /// Emits a event, running all systems listening to the event for each compatible
    /// entity.
    ///
    /// # Panics
    /// Will panic if a system has dissapeared.
    pub fn emit<EventT>(&self, event: EventT)
    where
        EventT: Event,
    {
        self.emit_event_by_id(EventT::id());

        drop(event);
    }

    pub fn query<Comps, OptionsT>(&self) -> Query<Comps, OptionsT>
    where
        Comps: ComponentSequence,
        OptionsT: QueryOptions,
    {
        Query::new(self)
    }

    /// Peforms the actions that have been queued up using [`Actions`].
    ///
    /// # Panics
    /// Will panic if a mutable internal lock cannot be acquired.
    #[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
    pub fn perform_queued_actions(&self)
    {
        let mut active_action_queue = match *self.data.action_queue.active_queue.borrow()
        {
            ActiveActionQueue::A => &self.data.action_queue.queue_a,
            ActiveActionQueue::B => &self.data.action_queue.queue_b,
        }
        .write_nonblock()
        .unwrap_or_else(|err| {
            panic!(
                "Failed to take read-write action queue lock {:?}: {err}",
                self.data.action_queue.active_queue
            );
        });

        let mut has_swapped_active_queue = false;

        for action in active_action_queue.drain(..) {
            match action {
                Action::Spawn(components) => {
                    let mut component_storage_lock = self.lock_component_storage_rw();

                    let component_ids = components
                        .iter()
                        .map(|component| component.id())
                        .collect::<Vec<_>>();

                    #[allow(unused_variables)]
                    if let Err(err) = component_storage_lock
                        .push_entity(EntityUid::new_unique(), components)
                    {
                        #[cfg(feature = "debug")]
                        tracing::error!("Failed to create entity: {err}");

                        continue;
                    }

                    drop(component_storage_lock);

                    if !has_swapped_active_queue {
                        self.swap_event_queue(&mut has_swapped_active_queue);
                    }

                    for component_id in component_ids {
                        self.emit_event_by_id(create_component_added_event_id(
                            component_id,
                        ));
                    }
                }
                Action::AddComponents(entity_uid, components) => {
                    let mut component_storage_lock = self.lock_component_storage_rw();

                    let component_ids = components
                        .iter()
                        .map(|component| component.id())
                        .collect::<Vec<_>>();

                    component_storage_lock
                        .add_components_to_entity(entity_uid, components);

                    drop(component_storage_lock);

                    if !has_swapped_active_queue {
                        self.swap_event_queue(&mut has_swapped_active_queue);
                    }

                    for component_id in component_ids {
                        self.emit_event_by_id(create_component_added_event_id(
                            component_id,
                        ));
                    }
                }
                Action::RemoveComponents(entity_uid, components_metadata) => {
                    let mut component_storage_lock = self.lock_component_storage_rw();

                    component_storage_lock.remove_components_from_entity(
                        entity_uid,
                        components_metadata
                            .iter()
                            .map(|component_metadata| component_metadata.id),
                    );

                    drop(component_storage_lock);

                    if !has_swapped_active_queue {
                        self.swap_event_queue(&mut has_swapped_active_queue);
                    }

                    for component_metadata in components_metadata {
                        self.emit_event_by_id(create_component_removed_event_id(
                            component_metadata.id,
                        ));
                    }
                }
                Action::Stop => {
                    self.stop.store(true, Ordering::Relaxed);
                }
            }
        }
    }

    /// A event loop which runs until a stop is issued with [`Flags::stop`]. Before the
    /// loop begins, [`StartEvent`] is emitted.
    ///
    /// # Panics
    /// Will panic if a internal lock cannot be acquired.
    pub fn event_loop<EventSeq: EventSequence>(&self)
    {
        for create_static_entity in CREATE_STATIC_ENTITIES {
            create_static_entity(self);
        }

        self.emit(StartEvent);

        let event_seq = EventSeq::ids();

        loop {
            for event_id in event_seq.iter() {
                self.emit_event_by_id(*event_id);
            }

            self.perform_queued_actions();

            if self.stop.load(Ordering::Relaxed) {
                break;
            }

            let mut stats_lock = self
                .data
                .sole_storage
                .get::<Stats>()
                .expect("No stats sole found")
                .write_nonblock()
                .expect("Failed to aquire read-write stats sole lock");

            let stats = stats_lock
                .downcast_mut::<Stats>()
                .expect("Casting stats sole to Stats type failed");

            stats.current_tick += 1;
        }
    }

    fn emit_event_by_id(&self, event_id: EventId)
    {
        let Some(system_indices) = self.data.events.get(&event_id) else {
            return;
        };

        for system_index in system_indices {
            let system = self.systems.get(*system_index).unwrap();

            // SAFETY: The world lives long enough
            unsafe {
                system.run(self);
            }
        }
    }

    fn swap_event_queue(&self, has_swapped_active_queue: &mut bool)
    {
        let mut active_queue = self.data.action_queue.active_queue.borrow_mut();

        *active_queue = match *active_queue {
            ActiveActionQueue::A => ActiveActionQueue::B,
            ActiveActionQueue::B => ActiveActionQueue::A,
        };

        *has_swapped_active_queue = true;
    }

    fn lock_component_storage_rw(&self) -> WriteGuard<'_, ComponentStorage>
    {
        self.data
            .component_storage
            .write_nonblock()
            .expect("Failed to acquire read-write component storage lock")
    }
}

#[derive(Debug, Default)]
pub struct WorldData
{
    events: HashMap<EventId, Vec<usize>>,
    component_storage: Arc<Lock<ComponentStorage>>,
    sole_storage: SoleStorage,
    action_queue: Arc<ActionQueue>,
}

#[derive(Debug)]
#[non_exhaustive]
pub struct EntityComponent
{
    pub id: ComponentId,
    pub name: &'static str,
    pub component: Lock<Box<dyn Component>>,
}

impl From<Box<dyn Component>> for EntityComponent
{
    fn from(component: Box<dyn Component>) -> Self
    {
        Self {
            id: component.id(),
            name: component.type_name(),
            component: Lock::new(component),
        }
    }
}

#[derive(Debug, Default, Clone, Copy)]
enum ActiveActionQueue
{
    #[default]
    A,
    B,
}

#[derive(Debug, Default)]
struct ActionQueue
{
    queue_a: Lock<Vec<Action>>,
    queue_b: Lock<Vec<Action>>,
    active_queue: RefCell<ActiveActionQueue>,
}

impl ActionQueue
{
    fn push(&self, action: Action)
    {
        match *self.active_queue.borrow() {
            ActiveActionQueue::A => self
                .queue_a
                .write_nonblock()
                .expect("Failed to aquire read-write action queue A lock")
                .push(action),
            ActiveActionQueue::B => self
                .queue_b
                .write_nonblock()
                .expect("Failed to aquire read-write action queue A lock")
                .push(action),
        }
    }
}

impl TypeName for ActionQueue
{
    fn type_name(&self) -> &'static str
    {
        type_name::<Self>()
    }
}

#[derive(Debug, thiserror::Error)]
#[error("Sole {0} already exists")]
pub struct SoleAlreadyExistsError(pub &'static str);

#[derive(Debug)]
struct StoredSole
{
    sole: Arc<Lock<Box<dyn Sole>>>,
    drop_last: bool,
}

#[derive(Debug, Default)]
struct SoleStorage
{
    storage: HashMap<TypeId, ManuallyDrop<StoredSole>>,
}

impl SoleStorage
{
    fn get<SoleT: Sole>(&self) -> Option<&Arc<Lock<Box<dyn Sole>>>>
    {
        self.storage
            .get(&TypeId::of::<SoleT>())
            .map(|sole| &sole.sole)
    }

    fn insert<SoleT: Sole>(&mut self, sole: SoleT) -> Result<(), SoleAlreadyExistsError>
    {
        let sole_type_id = TypeId::of::<SoleT>();

        if self.storage.contains_key(&sole_type_id) {
            return Err(SoleAlreadyExistsError(type_name::<SoleT>()));
        }

        let drop_last = sole.drop_last();

        // TODO: Reconsider this maybe?
        #[allow(clippy::arc_with_non_send_sync)]
        self.storage.insert(
            sole_type_id,
            ManuallyDrop::new(StoredSole {
                sole: Arc::new(Lock::new(Box::new(sole))),
                drop_last,
            }),
        );

        Ok(())
    }
}

impl Drop for SoleStorage
{
    fn drop(&mut self)
    {
        let mut soles_to_drop_last = Vec::new();

        for sole in self.storage.values_mut() {
            if sole.drop_last {
                #[cfg(feature = "debug")]
                tracing::debug!(
                    "Sole {} pushed to dropping last queue",
                    sole.sole.read_nonblock().unwrap().type_name()
                );

                soles_to_drop_last.push(sole);
                continue;
            }

            #[cfg(feature = "debug")]
            tracing::debug!(
                "Dropping sole {}",
                sole.sole.read_nonblock().unwrap().type_name()
            );

            unsafe {
                ManuallyDrop::drop(sole);
            }
        }

        for sole in &mut soles_to_drop_last {
            #[cfg(feature = "debug")]
            tracing::debug!(
                "Dropping sole {} last",
                sole.sole.read_nonblock().unwrap().type_name()
            );

            unsafe {
                ManuallyDrop::drop(sole);
            }
        }
    }
}