froql 0.1.0

an in memory query dsl
Documentation
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
#![deny(missing_docs)]
//! contains the `World` type and its methods
//! This module intended for direct use by the library user.

use std::{
    any::{TypeId, type_name},
    cell::{Ref, RefCell, RefMut},
    fmt::{self, Debug},
};

use crate::{
    bookkeeping::{Bookkeeping, EnsureComponentResult},
    component::{Component, ComponentId, RELATION},
    entity_store::{Entity, EntityId},
    entity_view_deferred::{DeferredOperation, EntityViewDeferred},
    entity_view_mut::EntityViewMut,
    relation::Relation,
    util::short_type_name,
};

/// The `World` is the central datastructure in froql that holds all state.
pub struct World {
    /// internal state management
    /// Bookkeeping is public because some queries need to interact with it.
    #[doc(hidden)]
    pub bookkeeping: Bookkeeping,
    pub(crate) deferred_queue: RefCell<DeferredQueue>,
    // TODO move into query or something
    singleton: Entity,
}

/// This is a queue of operations that will be executed during `world.process()`
pub(crate) struct DeferredQueue {
    pub operations: Vec<DeferredOperation>,
}

impl World {
    /// Creates a new `World`
    ///
    /// Don't forget to register your Components and Relationships
    /// with `register_component::<T>()` and `register_relation::<T>()`.
    pub fn new() -> Self {
        let mut bookkeeping = Bookkeeping::new();
        let singleton = bookkeeping.create();
        World {
            bookkeeping,
            deferred_queue: RefCell::new(DeferredQueue {
                operations: Vec::new(),
            }),
            singleton,
        }
    }

    /// Used internally to register both components and relations
    /// because Relations are a special kind of component
    /// and Components are meant to be wrapped in `RefCell`
    fn register_component_inner<T: 'static>(
        &mut self,
        flags: u32,
        short_name: &str,
    ) -> ComponentId {
        let tid = TypeId::of::<T>();
        if let Some(cid) = self.bookkeeping.get_component_id(tid) {
            return cid;
        }
        let mut cid = ComponentId::from_usize(self.bookkeeping.components.len());
        cid = cid.set_flags(flags);
        self.bookkeeping
            .components
            .push(Component::new::<T>(cid, short_name));
        self.bookkeeping.component_map.insert(tid, cid);
        let tname = type_name::<T>().to_string();
        let old = self.bookkeeping.component_name_map.insert(tname, tid);
        assert_eq!(None, old, "Typename was already registered.");
        return cid;
    }

    /// Counterpart of register_component_inner for hotreloading purposes
    unsafe fn reload_component_inner<T: 'static>(
        &mut self,
        cid: ComponentId,
    ) -> Result<(), ReregisterError> {
        let component = &mut self.bookkeeping.components[cid.as_index()];
        unsafe {
            component.update_type::<T>()?;
        }
        for aid in component.get_archetypes() {
            let arch = &mut self.bookkeeping.archetypes[aid.as_index()];
            let col = arch.find_column_mut(cid);
            unsafe {
                col.change_drop_function(component.drop_fn.clone());
            }
        }
        Ok(())
    }

    /// Registers a debug formatter for ComponentTypes that implement the Debug trait
    pub fn register_debug<T: 'static + Debug>(&mut self) {
        let cid = self.register_component::<T>();
        assert!(
            !cid.is_relation(),
            "Relations don't contain values and therefore can't be formatted with the Debug trait."
        );
        let debug_fn_wrapped = |ptr: *const u8, formatter: &mut fmt::Formatter<'_>| {
            let debug_fn = <T as Debug>::fmt;
            let ptr = ptr as *const RefCell<T>;
            // SAFETY: we know its a component (not a relation) of the right type here
            let val: &RefCell<T> = unsafe { &*ptr };
            debug_fn(&val.borrow(), formatter)
        };
        self.bookkeeping.components[cid.as_index()].debug_fn = Some(debug_fn_wrapped);
    }

    /// Convenience method for getting a Component of the singleton entity.
    ///
    /// The singleton entity is meant to be used for things that only exist once.
    pub fn singleton<T: 'static>(&self) -> Ref<T> {
        self.get_component::<T>(self.singleton)
    }

    /// Convenience method for getting a mutable ref to a Component of the singleton entity.
    ///
    /// The singleton entity is meant to be used for things that only exist once.
    pub fn singleton_mut<T: 'static>(&self) -> RefMut<T> {
        self.get_component_mut::<T>(self.singleton)
    }

    /// Convenience method for setting a Component of the singleton entity.
    ///
    /// The singleton entity is meant to be used for things that only exist once.
    pub fn singleton_add<T: 'static>(&mut self, val: T) {
        self.add_component(self.singleton, val)
    }

    /// Returns if singleton has the component of type T.
    ///
    /// The singleton entity is meant to be used for things that only exist once.
    pub fn singleton_has<T: 'static>(&self) -> bool {
        self.has_component::<T>(self.singleton)
    }

    /// Convenience method for removing a Component of the singleton entity.
    ///
    /// The singleton entity is meant to be used for things that only exist once.
    pub fn singleton_remove<T: 'static>(&mut self) {
        self.remove_component::<T>(self.singleton)
    }

    /// Registers component type for later use.
    pub fn register_component<T: 'static>(&mut self) -> ComponentId {
        self.register_component_inner::<RefCell<T>>(0, short_type_name::<T>())
    }

    /// This allows reusing the same world in hotreloading scenarios.
    /// This is not only unsafe, its straight up undefined behavior.
    /// Very useful for development purposes though.
    ///
    /// DO NOT ship code that calls this method in production.
    /// Use feature flags to accomplish this.
    ///
    /// # SAFETY
    /// This finds the type by using its typename.
    /// If you have two components/relations with the exact same name you are in trouble.
    ///
    /// If a types layout changed you get an error. But not all changes to a struct result
    /// in a change to its layout.
    pub unsafe fn re_register_component<T: 'static>(&mut self) -> Result<(), ReregisterError> {
        let tid = TypeId::of::<RefCell<T>>();
        let name = type_name::<RefCell<T>>();
        let old_tid = self
            .bookkeeping
            .component_name_map
            .get(name)
            .expect("Type {name} was not registered as component.");
        let cid = self.bookkeeping.component_map.remove(old_tid).unwrap();
        self.bookkeeping.component_map.insert(tid, cid);
        self.bookkeeping
            .component_name_map
            .insert(name.to_string(), tid);
        unsafe { self.reload_component_inner::<RefCell<T>>(cid) }
    }

    /// This allows reusing the same world in hotreloading scenarios.
    /// This is not only unsafe, its straight up undefined behavior.
    /// Very useful for development purposes though.
    ///
    /// DO NOT ship code that calls this method in production.
    /// Use feature flags to accomplish this.
    ///
    /// # SAFETY
    /// This finds the type by using its typename.
    /// If you have two components/relations with the exact same name you are in trouble.
    ///
    /// If a types layout changed you get an error. But not all changes to a struct result
    /// in a change to its layout.
    pub unsafe fn re_register_relation<T: 'static>(&mut self) -> Result<(), ReregisterError> {
        let tid = TypeId::of::<Relation<T>>();
        let name = type_name::<Relation<T>>();
        let old_tid = self
            .bookkeeping
            .component_name_map
            .get(name)
            .expect("Type {name} was not registered as component.");
        let cid = self.bookkeeping.component_map.remove(old_tid).unwrap();
        self.bookkeeping.component_map.insert(tid, cid);
        self.bookkeeping
            .component_name_map
            .insert(name.to_string(), tid);
        unsafe { self.reload_component_inner::<Relation<T>>(cid) }
    }

    /// mostly there for use in query
    #[doc(hidden)]
    pub fn get_component_id<T: 'static>(&self) -> ComponentId {
        let tid = TypeId::of::<RefCell<T>>();
        self.bookkeeping
            .get_component_id(tid)
            .unwrap_or_else(|| panic!("ComponentType '{}' is not registered.", type_name::<T>()))
    }

    /// Creates an Entity and returns it.
    ///
    /// This Entity is not wrapped in a view, so it doesn't carry a lifetime.
    pub fn create_entity(&mut self) -> Entity {
        self.bookkeeping.create()
    }

    /// Turns an `EntityId` into an `Entity`.
    /// If the `Entity` was not alive before it will be made alive.
    ///
    /// This is useful when building deserialization.
    pub fn ensure_alive(&mut self, id: EntityId) -> Entity {
        self.bookkeeping.ensure_alive(id)
    }

    /// Creates an Entity and immediately wraps it in a `EntityViewMut`.
    /// Useful for convenience.
    ///
    /// The wrapped Entity can be accessed as `.entity` member on the view.
    pub fn create(&mut self) -> EntityViewMut {
        EntityViewMut {
            entity: self.bookkeeping.create(),
            world: self,
        }
    }

    /// Wraps an existing Entity in an `EntityViewMut`.
    pub fn view_mut(&mut self, e: Entity) -> EntityViewMut {
        EntityViewMut {
            entity: e,
            world: self,
        }
    }

    /// Creates an Entity and immediately wraps it in a `EntityViewDeferred`.
    /// Useful when you only have shared reference to `World`.
    ///
    /// The wrapped Entity can be accessed as `.entity` member on the view.
    ///
    /// Don't
    pub fn create_deferred(&self) -> EntityViewDeferred {
        EntityViewDeferred {
            entity: self.bookkeeping.create_deferred(),
            world: self,
        }
    }

    /// Checks if the `Entity` is alive by using its generation.
    pub fn is_alive(&self, e: Entity) -> bool {
        self.bookkeeping.is_alive(e)
    }

    /// Adds a component to the entity.
    ///
    /// Panics if `Entity` is not alive.
    /// Panics if Component type is not registered.
    pub fn add_component<T: 'static>(&mut self, e: Entity, mut val: T) {
        let cid = if cfg!(feature = "manual_registration") {
            self.get_component_id::<T>()
        } else {
            self.register_component::<T>()
        };

        match self.bookkeeping.ensure_component(e, cid) {
            EnsureComponentResult::NewComponent(ptr) => {
                let val = RefCell::new(val);
                let dst = ptr as *mut RefCell<T>;
                unsafe {
                    std::ptr::write(dst, val);
                }
            }
            EnsureComponentResult::OldComponent(ptr) => {
                let ptr = ptr as *const RefCell<T>;
                let mut old = unsafe { &*ptr }.borrow_mut();
                // this drops the old component too, how neat
                std::mem::swap::<T>(&mut val, &mut old);
            }
        }
    }

    /// Returns an immutable Ref to the component.
    ///
    /// Panics if `Entity` is not alive or does not have the component.
    /// Panics if component type is not registered.
    pub fn get_component<T: 'static>(&self, e: Entity) -> Ref<T> {
        let cid = self.get_component_id::<T>();
        let ptr = self.bookkeeping.get_component(e, cid) as *const RefCell<T>;
        let cell = unsafe { &*ptr };
        cell.borrow()
    }

    /// Returns a immutable Ref to the component of the Entity with the given `EntityId`.
    ///
    /// Useful if you don't have a generation for whatever reason.
    ///
    /// Panics if `Entity` is not alive or does not have the component.
    pub fn get_component_by_entityid<T: 'static>(&self, id: EntityId) -> Ref<T> {
        let cid = self.get_component_id::<T>();
        let ptr = self
            .bookkeeping
            .get_component_opt_unchecked(id, cid)
            .unwrap() as *const RefCell<T>;
        let cell = unsafe { &*ptr };
        cell.borrow()
    }

    /// Returns a mutable RefMut to the component.
    ///
    /// Panics if `Entity` is not alive or does not have the component.
    /// Panics if component type is not registered.
    pub fn get_component_mut<T: 'static>(&self, e: Entity) -> RefMut<T> {
        let cid = self.get_component_id::<T>();
        let ptr = self.bookkeeping.get_component(e, cid) as *const RefCell<T>;
        let cell = unsafe { &*ptr };
        cell.borrow_mut()
    }

    /// Returns true, if the Entity has the component.
    ///
    /// Panics if component type is not registered.
    pub fn has_component<T: 'static>(&self, e: Entity) -> bool {
        let cid = self.get_component_id::<T>();
        self.bookkeeping.has_component(e, cid)
    }

    /// Removes component of type `T` from Entity.
    /// This operation is idempotent.
    ///
    /// Panics if component type is not registered.
    pub fn remove_component<T: 'static>(&mut self, e: Entity) {
        let cid = if cfg!(feature = "manual_registration") {
            self.get_component_id::<T>()
        } else {
            self.register_component::<T>()
        };
        self.bookkeeping.remove_component(e, cid);
    }

    /// Makes entity not alive.
    /// All components of the entity are dropped (and their drop functions executed).
    pub fn destroy(&mut self, e: Entity) {
        self.bookkeeping.destroy(e);
    }

    /// Executes all queued deferred operations.
    pub fn process(&mut self) {
        self.bookkeeping.realize_deferred();

        let mut tmp = Vec::new();
        let queue = self.deferred_queue.get_mut();
        let ops = &mut queue.operations;
        std::mem::swap(&mut tmp, ops); // too lazy to work around partial borrows here atm
        for command in tmp {
            match command {
                DeferredOperation::DestroyEntity(e) => {
                    self.destroy(e);
                }
                DeferredOperation::AddComponent(func) => {
                    func(self);
                }
                DeferredOperation::RemoveComponent(tid, e) => {
                    let cid = self.bookkeeping.get_component_id(tid).unwrap(); // TODO error msg
                    self.bookkeeping.remove_component(e, cid);
                }
                DeferredOperation::AddRelation(tid, from, to) => {
                    let Some(cid) = self.bookkeeping.get_component_id(tid) else {
                        panic!("Can't register relation in deferred context.");
                    };
                    self.bookkeeping.add_relation(cid, from, to);
                }
                DeferredOperation::RemoveRelation(tid, from, to) => {
                    let Some(cid) = self.bookkeeping.get_component_id(tid) else {
                        panic!("Can't register relation in deferred context.");
                    };
                    self.bookkeeping.remove_relation(cid, from, to);
                }
            }
        }
    }
}

// relation stuff in separate impl block
impl World {
    /// shorthand
    fn get_relation_id<T: 'static>(&self) -> ComponentId {
        let tid = TypeId::of::<Relation<T>>();
        self.bookkeeping
            .get_component_id(tid)
            .unwrap_or_else(|| panic!("RelationType '{}' is not registered.", type_name::<T>()))
    }

    /// Registers a relation type.
    ///
    /// It's recommended to use an inhibited type (enum without variants)
    /// so that you don't confuse components and relations on accident.
    pub fn register_relation<T: 'static>(&mut self) -> ComponentId {
        self.register_component_inner::<Relation<T>>(RELATION, short_type_name::<T>())
    }

    /// Registers a relation type with specific flags.
    /// Flag options are: `EXCLUSIVE`, `SYMMETRIC`, `CASCADING_DESTRUCT` and `TRANSITIVE`
    ///
    /// It's recommended to use an inhibited type (enum without variants)
    /// so that you don't confuse components and relations on accident.
    pub fn register_relation_flags<T: 'static>(&mut self, flags: u32) {
        // TODO: error if component is already registered
        self.register_component_inner::<Relation<T>>(flags | RELATION, short_type_name::<T>());
    }

    /// Adds a relationship between two entities.
    /// Registers the relationship type if it is not already.
    pub fn add_relation<T: 'static>(&mut self, from: Entity, to: Entity) {
        let origin_cid = if cfg!(feature = "manual_registration") {
            self.get_relation_id::<T>()
        } else {
            self.register_relation::<T>()
        };

        self.bookkeeping.add_relation(origin_cid, from, to);
    }

    /// Checks if there is a relation between two entities.
    /// Order matters for all relations that are not `SYMMETRIC`.
    pub fn has_relation<T: 'static>(&self, from: Entity, to: Entity) -> bool {
        let origin_cid = self.get_relation_id::<T>();
        self.bookkeeping.has_relation(origin_cid, from, to)
    }

    /// Removes relation between two entities.
    /// This operation is idempotent.
    pub fn remove_relation<T: 'static>(&mut self, from: Entity, to: Entity) {
        let cid = if cfg!(feature = "manual_registration") {
            self.get_relation_id::<T>()
        } else {
            self.register_relation::<T>()
        };

        self.bookkeeping.remove_relation(cid, from, to);
    }

    /// Returns all directly related targets
    /// DOES NOT follow transitive relations
    pub fn relation_targets<T: 'static>(
        &self,
        from: Entity,
    ) -> impl Iterator<Item = Entity> + use<'_, T> {
        let origin_cid = self.get_relation_id::<T>();
        self.bookkeeping
            .relation_partners(origin_cid, from)
            .into_iter()
            .flatten()
    }

    /// Returns all directly related origins
    /// DOES NOT follow transitive relations
    pub fn relation_origins<T: 'static>(
        &self,
        to: Entity,
    ) -> impl Iterator<Item = Entity> + use<'_, T> {
        let target_cid = self.get_relation_id::<T>().flip_target();
        self.bookkeeping
            // same logic as with target, just different parameter
            .relation_partners(target_cid, to)
            .into_iter()
            .flatten()
    }

    /// Returns all directly related pairs
    /// DOES NOT follow transitive relations
    pub fn relation_pairs<T: 'static>(&self) -> Vec<(Entity, Entity)> {
        let o_tid = TypeId::of::<Relation<T>>();
        self.bookkeeping.relation_pairs(o_tid)
    }
}

/// Error Type for `reregister_component`.
pub enum ReregisterError {
    /// The new type has a different layout than the old type.
    DifferingLayout,
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn create_and_get() {
        struct Pos(i32, i32);
        struct Name(String);

        let mut world = World::new();
        world.register_component::<Pos>();
        world.register_component::<Name>();

        let e = world.create_entity();
        world.add_component(e, Pos(4, 2));
        world.add_component(e, Name("Player".to_string()));
        let other = world.create_entity();
        world.add_component(other, Pos(5, 4));
        world.add_component(other, Name("Other".to_string()));

        let pos = world.get_component::<Pos>(e);
        let name = world.get_component::<Name>(e);
        assert_eq!(pos.0, 4);
        assert_eq!(pos.1, 2);
        assert_eq!(name.0, "Player");
        let pos = world.get_component::<Pos>(other);
        let name = world.get_component::<Name>(other);
        assert_eq!(pos.0, 5);
        assert_eq!(pos.1, 4);
        assert_eq!(name.0, "Other");
    }

    #[test]
    fn create_remove_get() {
        struct Pos(i32, i32);
        struct Name(String);

        let mut world = World::new();
        world.register_component::<Pos>();
        world.register_component::<Name>();

        let e = world.create_entity();
        world.add_component(e, Pos(4, 2));
        world.add_component(e, Name("Player".to_string()));
        assert!(world.has_component::<Pos>(e));
        assert!(world.has_component::<Name>(e));
        let other = world.create_entity();
        world.add_component(other, Pos(5, 4));
        world.add_component(other, Name("Other".to_string()));

        world.remove_component::<Pos>(e);
        world.remove_component::<Name>(e);
        assert!(!world.has_component::<Pos>(e));
        assert!(!world.has_component::<Name>(e));

        let pos = world.get_component::<Pos>(other);
        let name = world.get_component::<Name>(other);
        assert_eq!(pos.0, 5);
        assert_eq!(pos.1, 4);
        assert_eq!(name.0, "Other");
    }

    #[test]
    fn create_destroy_get() {
        struct Pos(i32, i32);
        struct Name(String);

        let mut world = World::new();
        world.register_component::<Pos>();
        world.register_component::<Name>();

        let e = world.create_entity();
        world.add_component(e, Pos(4, 2));
        world.add_component(e, Name("Player".to_string()));
        let other = world.create_entity();
        world.add_component(other, Pos(5, 4));
        world.add_component(other, Name("Other".to_string()));

        world.destroy(e);

        let pos = world.get_component::<Pos>(other);
        let name = world.get_component::<Name>(other);
        assert_eq!(pos.0, 5);
        assert_eq!(pos.1, 4);
        assert_eq!(name.0, "Other");
    }

    #[test]
    fn component_mut() {
        struct Pos(i32, i32);

        let mut world = World::new();
        world.register_component::<Pos>();

        let e = world.create_entity();
        world.add_component(e, Pos(4, 2));
        let pos = world.get_component::<Pos>(e);
        assert_eq!(pos.0, 4);
        assert_eq!(pos.1, 2);
        drop(pos); // need to release ref

        let mut pos = world.get_component_mut::<Pos>(e);
        pos.0 = 20;
        pos.1 = 30;
        drop(pos); // need to release refmut

        let pos = world.get_component::<Pos>(e);
        assert_eq!(pos.0, 20);
        assert_eq!(pos.1, 30);
    }

    #[test]
    fn zst_component() {
        struct Comp {}

        let mut world = World::new();
        world.register_component::<Comp>();
        let a = world.create_entity();
        assert!(!world.has_component::<Comp>(a));
        world.add_component(a, Comp {});
        assert!(world.has_component::<Comp>(a));

        {
            let _comp: Ref<Comp> = world.get_component::<Comp>(a);
        }

        world.remove_component::<Comp>(a);
        assert!(!world.has_component::<Comp>(a));
    }

    #[test]
    fn add_component_twice() {
        #[allow(dead_code)]
        struct Comp(i32);
        use std::sync::atomic::{AtomicBool, Ordering as O};
        static WAS_DROPPED: AtomicBool = AtomicBool::new(false);
        impl Drop for Comp {
            fn drop(&mut self) {
                println!("Dropping.");
                let _ = WAS_DROPPED.compare_exchange(false, true, O::Relaxed, O::Relaxed);
            }
        }

        let mut world = World::new();
        world.register_component::<Comp>();
        let e = world.create_entity();
        world.add_component(e, Comp(42));
        world.add_component(e, Comp(50));

        let comp = world.get_component::<Comp>(e);
        assert_eq!(comp.0, 50);
        assert!(WAS_DROPPED.load(O::Relaxed));
    }

    #[cfg(not(feature = "manual_registration"))]
    #[test]
    fn automatic_registration() {
        struct Comp {}
        enum Rel {}
        let mut world = World::new();
        let e = world.create_entity();
        world.create().add(Comp {}).relate_to::<Rel>(e);
    }

    #[cfg(feature = "manual_registration")]
    #[test]
    #[should_panic]
    fn manual_registration() {
        struct Comp {}
        let mut world = World::new();
        world.create().add(Comp {});
    }

    #[cfg(feature = "manual_registration")]
    #[test]
    #[should_panic]
    fn manual_registration_relation() {
        enum Rel {}
        let mut world = World::new();
        let e = world.create_entity();
        world.create().relate_to::<Rel>(e);
    }

    #[test]
    fn relate_to_self() {
        enum Rel {}
        let mut world = World::new();
        let e = world.create_entity();
        world.add_relation::<Rel>(e, e);
        // dbg!(EntityViewDeferred::new(&world, e));
    }
}