summaryrefslogtreecommitdiff
path: root/ecs/src/lib.rs
blob: 9d79b91519019cf18fb8cc29562af606541d2ff5 (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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
#![deny(clippy::all, clippy::pedantic)]

use std::any::{type_name, Any, TypeId};
use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::marker::PhantomData;
use std::mem::ManuallyDrop;
use std::ops::RangeBounds;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Weak};
use std::vec::Drain;

use crate::actions::Action;
use crate::component::{Component, Sequence as ComponentSequence};
use crate::event::{Event, Id as EventId, Ids, Sequence as EventSequence};
use crate::lock::{Lock, ReadGuard};
use crate::system::{
    NoInitParamFlag as NoInitSystemParamFlag,
    Param as SystemParam,
    System,
    TypeErased as TypeErasedSystem,
};
use crate::tuple::FilterExclude as TupleFilterExclude;
use crate::type_name::TypeName;

pub mod actions;
pub mod component;
pub mod event;
pub mod lock;
pub mod system;
pub mod tuple;
pub mod type_name;

pub use ecs_macros::Component;

#[derive(Debug, Default)]
struct Entity
{
    components: Vec<ManuallyDrop<EntityComponent>>,
}

#[derive(Debug)]
struct EntityComponent
{
    id: TypeId,
    component: Lock<Box<dyn Component>>,
    drop_last: bool,
}

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

impl World
{
    #[must_use]
    pub fn new() -> Self
    {
        Self::default()
    }

    /// 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)
    where
        Comps: ComponentSequence,
    {
        self.data
            .component_storage
            .write_nonblock()
            .expect("Failed to acquire read-write component storage lock")
            .entities
            .push(Entity {
                components: components
                    .into_vec()
                    .into_iter()
                    .map(|component| {
                        let drop_last = component.drop_last();

                        ManuallyDrop::new(EntityComponent {
                            id: (*component).type_id(),
                            component: Lock::new(component),
                            drop_last,
                        })
                    })
                    .collect(),
            });
    }

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

        self.data
            .events
            .entry(event.id())
            .or_default()
            .push(self.systems.len() - 1);
    }

    /// 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(&self, event: &impl Event)
    {
        self.emit_event_by_id(event.id());
    }

    pub fn query<Comps>(&self) -> Query<Comps>
    where
        Comps: ComponentSequence,
    {
        Query::new(&self.data.component_storage)
    }

    /// Peforms the actions that have been queued up using [`Actions`].
    ///
    /// # Panics
    /// Will panic if a mutable internal lock cannot be acquired.
    pub fn perform_queued_actions(&self)
    {
        for action in self
            .data
            .action_queue
            .write_nonblock()
            .expect("Failed to aquire read-write action queue lock")
            .drain(..)
        {
            match action {
                Action::Spawn(components) => {
                    self.data
                        .component_storage
                        .write_nonblock()
                        .expect("Failed to acquire read-write component storage lock")
                        .entities
                        .push(Entity {
                            components: components
                                .into_iter()
                                .map(|component| {
                                    let drop_last = component.drop_last();

                                    ManuallyDrop::new(EntityComponent {
                                        id: (*component).type_id(),
                                        component: Lock::new(component),
                                        drop_last,
                                    })
                                })
                                .collect(),
                        });
                }
                Action::Stop => {
                    self.stop.store(true, Ordering::Relaxed);
                }
            }
        }
    }

    /// A event loop which runs until a stop is issued with [`Flags::stop`].
    ///
    /// # Panics
    /// Will panic if a internal lock cannot be acquired.
    pub fn event_loop<EventSeq: EventSequence>(&self)
    {
        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;
            }
        }
    }

    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 data lives long enough
            unsafe {
                system.run(&self.data);
            }
        }
    }
}

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

#[derive(Debug, Default)]
struct ActionQueue
{
    queue: Vec<Action>,
}

impl ActionQueue
{
    fn push(&mut self, action: Action)
    {
        self.queue.push(action);
    }

    fn drain(&mut self, range: impl RangeBounds<usize>) -> Drain<Action>
    {
        self.queue.drain(range)
    }
}

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

/// A entity query.
#[derive(Debug)]
pub struct Query<'world, Comps>
where
    Comps: ComponentSequence,
{
    component_storage: ReadGuard<'world, ComponentStorage>,
    component_storage_lock: Weak<Lock<ComponentStorage>>,
    comps_pd: PhantomData<Comps>,
}

impl<'world, Comps> Query<'world, Comps>
where
    Comps: ComponentSequence,
{
    #[must_use]
    pub fn iter<'this>(&'this self) -> QueryComponentIter<'world, Comps>
    where
        'this: 'world,
    {
        QueryComponentIter {
            component_storage: &self.component_storage,
            current_entity_index: 0,
            component_type_ids: Comps::type_ids(),
            comps_pd: PhantomData,
        }
    }

    /// Returns a weak reference query to the same components.
    #[must_use]
    pub fn to_weak_ref(&self) -> WeakRefQuery<Comps>
    {
        WeakRefQuery {
            component_storage: self.component_storage_lock.clone(),
            comps_pd: PhantomData,
        }
    }

    fn new(component_storage: &'world Arc<Lock<ComponentStorage>>) -> Self
    {
        Self {
            component_storage: component_storage
                .read_nonblock()
                .expect("Failed to acquire read-only component storage lock"),
            component_storage_lock: Arc::downgrade(component_storage),
            comps_pd: PhantomData,
        }
    }
}

impl<'world, Comps> IntoIterator for &'world Query<'world, Comps>
where
    Comps: ComponentSequence,
{
    type IntoIter = QueryComponentIter<'world, Comps>;
    type Item = Comps::Refs<'world>;

    fn into_iter(self) -> Self::IntoIter
    {
        self.iter()
    }
}

unsafe impl<'world, Comps> SystemParam<'world> for Query<'world, Comps>
where
    Comps: ComponentSequence,
{
    type Flags = NoInitSystemParamFlag;
    type Input = TupleFilterExclude;

    fn initialize<SystemImpl>(
        _system: &mut impl System<'world, SystemImpl>,
        _input: Self::Input,
    )
    {
    }

    fn new<SystemImpl>(
        _system: &'world impl System<'world, SystemImpl>,
        world_data: &'world WorldData,
    ) -> Self
    {
        Self::new(&world_data.component_storage)
    }

    fn is_compatible<Other: SystemParam<'world>>() -> bool
    {
        let other_comparable = Other::get_comparable();

        let Some(other_query_component_ids) =
            other_comparable.downcast_ref::<QueryComponentIds>()
        else {
            return true;
        };

        !other_query_component_ids.contains_component_in::<Comps>()
    }

    fn get_comparable() -> Box<dyn Any>
    {
        Box::new(QueryComponentIds {
            component_type_ids: Comps::type_ids(),
        })
    }
}

/// A entity query containing a weak reference to the world.
#[derive(Debug)]
pub struct WeakRefQuery<Comps>
where
    Comps: ComponentSequence,
{
    component_storage: Weak<Lock<ComponentStorage>>,
    comps_pd: PhantomData<Comps>,
}

impl<Comps> WeakRefQuery<Comps>
where
    Comps: ComponentSequence,
{
    /// Returns a struct which can be used to retrieve a [`Query`].
    ///
    /// Returns [`None`] if the [`World`] has been dropped.
    #[must_use]
    pub fn access(&self) -> Option<RefQuery<'_, Comps>>
    {
        Some(RefQuery {
            component_storage: self.component_storage.upgrade()?,
            _pd: PhantomData,
        })
    }
}

impl<Comps> Clone for WeakRefQuery<Comps>
where
    Comps: ComponentSequence,
{
    fn clone(&self) -> Self
    {
        Self {
            component_storage: self.component_storage.clone(),
            comps_pd: PhantomData,
        }
    }
}

/// Intermediate between [`Query`] and [`WeakRefQuery`]. Contains a strong reference to
/// the world which is not allowed direct access to.
#[derive(Debug, Clone)]
pub struct RefQuery<'weak_ref, Comps>
where
    Comps: ComponentSequence,
{
    component_storage: Arc<Lock<ComponentStorage>>,
    _pd: PhantomData<&'weak_ref Comps>,
}

impl<'weak_ref, Comps> RefQuery<'weak_ref, Comps>
where
    Comps: ComponentSequence,
{
    #[must_use]
    pub fn to_query(&self) -> Query<'_, Comps>
    {
        Query::new(&self.component_storage)
    }
}

#[derive(Debug)]
struct QueryComponentIds
{
    component_type_ids: Vec<TypeId>,
}

impl QueryComponentIds
{
    fn contains_component_in<OtherComps>(&self) -> bool
    where
        OtherComps: ComponentSequence,
    {
        let other_component_type_ids = OtherComps::type_ids()
            .into_iter()
            .collect::<HashSet<TypeId>>();

        // TODO: Make this a bit smarter. Queries with a same component can be compatible
        // if one of the queries have a component the other one does not have
        self.component_type_ids
            .iter()
            .any(|component_type_id| other_component_type_ids.contains(component_type_id))
    }
}

pub struct QueryComponentIter<'world, Comps>
{
    component_storage: &'world ComponentStorage,
    current_entity_index: usize,
    component_type_ids: Vec<TypeId>,
    comps_pd: PhantomData<Comps>,
}

impl<'world, Comps> Iterator for QueryComponentIter<'world, Comps>
where
    Comps: ComponentSequence + 'world,
{
    type Item = Comps::Refs<'world>;

    fn next(&mut self) -> Option<Self::Item>
    {
        let (matching_entity_index, matching_entity) =
            self.component_storage.find_entity_with_components(
                self.current_entity_index,
                &self.component_type_ids,
            )?;

        self.current_entity_index = matching_entity_index + 1;

        Some(Comps::from_components(
            matching_entity
                .components
                .iter()
                .map(|component| &component.component),
        ))
    }
}

#[derive(Debug, Default)]
pub struct ComponentStorage
{
    entities: Vec<Entity>,
}

impl ComponentStorage
{
    fn find_entity_with_components(
        &self,
        start_index: usize,
        component_type_ids: &[TypeId],
    ) -> Option<(usize, &Entity)>
    {
        // TODO: This is a really dumb and slow way to do this. Refactor the world
        // to store components in archetypes
        self.entities.iter().enumerate().skip(start_index).find(
            move |(_index, entity)| {
                let entity_components = entity
                    .components
                    .iter()
                    .map(|component| component.id)
                    .collect::<HashSet<_>>();

                if component_type_ids.iter().all(|component_type_id| {
                    entity_components.contains(component_type_id)
                }) {
                    return true;
                }

                false
            },
        )
    }
}

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

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

        for entity in &mut self.entities {
            for component in &mut entity.components {
                if component.drop_last {
                    #[cfg(feature = "debug")]
                    tracing::debug!(
                        "Component {} pushed to dropping last queue",
                        component.component.read_nonblock().unwrap().type_name()
                    );

                    components_to_drop_last.push(component);
                    continue;
                }

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

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

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

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