-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
world.rs
2354 lines (2014 loc) · 81.4 KB
/
world.rs
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::borrow::Ref;
use crate::borrow::RefMut;
use crate::entity::BlockAllocator;
use crate::entity::Entity;
use crate::entity::EntityLocation;
use crate::entity::Locations;
use crate::event::Event;
use crate::filter::ArchetypeFilterData;
use crate::filter::ChunksetFilterData;
use crate::filter::EntityFilter;
use crate::filter::Filter;
use crate::guid_entity_allocator::GuidEntityAllocator;
use crate::index::ArchetypeIndex;
use crate::index::ComponentIndex;
use crate::index::SetIndex;
use crate::iterator::SliceVecIter;
use crate::storage::ArchetypeData;
use crate::storage::ArchetypeDescription;
use crate::storage::Component;
use crate::storage::ComponentMeta;
use crate::storage::ComponentStorage;
use crate::storage::ComponentTypeId;
use crate::storage::Storage;
use crate::storage::Tag;
use crate::storage::TagMeta;
use crate::storage::TagTypeId;
use crate::storage::Tags;
use crate::{
query::Query,
query::View,
subworld::{ComponentAccess, ComponentAccessError, StorageAccessor, SubWorld},
tuple::TupleEq,
};
use parking_lot::Mutex;
use std::cell::UnsafeCell;
use std::collections::HashMap;
use std::iter::Enumerate;
use std::iter::Fuse;
use std::iter::FusedIterator;
use std::iter::Peekable;
use std::iter::Repeat;
use std::iter::Take;
use std::marker::PhantomData;
use std::ops::Deref;
use std::ptr::NonNull;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use thiserror::Error;
use tracing::{info, span, trace, Level};
static NEXT_UNIVERSE_ID: AtomicUsize = AtomicUsize::new(1);
static NEXT_WORLD_ID: AtomicUsize = AtomicUsize::new(0);
#[derive(Default, Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct UniverseId(usize);
/// The `Universe` is a factory for creating `World`s.
///
/// Entities inserted into worlds created within the same universe are guarenteed to have
/// unique `Entity` IDs, even across worlds.
#[derive(Debug)]
pub struct Universe {
id: UniverseId,
allocator: Arc<Mutex<BlockAllocator>>,
}
impl Universe {
/// Creates a new `Universe`.
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
id: UniverseId(NEXT_UNIVERSE_ID.fetch_add(1, Ordering::SeqCst)),
allocator: Arc::new(Mutex::new(BlockAllocator::new())),
}
}
/// Creates a new `World` within this `Universe`.
///
/// Entities inserted into worlds created within the same universe are guarenteed to have
/// unique `Entity` IDs, even across worlds. See also `World::new`.
pub fn create_world(&self) -> World {
let id = WorldId::next(self.id.0);
let world = World::new_in_universe(id, GuidEntityAllocator::default());
info!(universe = self.id.0, world = world.id().1, "Created world");
world
}
}
/// A queryable collection of entities.
pub trait EntityStore {
/// Checks that the provided `Component` is present on a given entity.
///
/// Returns true if it exists, otherwise false.
fn has_component<T: Component>(&self, entity: Entity) -> bool;
/// Checks that the provided `ComponentTypeId` is present on a given entity.
///
/// Returns true if it exists, otherwise false.
fn has_component_by_id(&self, entity: Entity, component: ComponentTypeId) -> bool;
/// Borrows component data for the given entity.
///
/// Returns `Some(data)` if the entity was found and contains the specified data.
/// Otherwise `None` is returned.
///
/// # Panics
///
/// This function may panic if the component was not declared as read by this system.
fn get_component<T: Component>(&self, entity: Entity) -> Option<Ref<T>>;
/// Borrows component data for the given entity. Does not perform static borrow checking.
///
/// Returns `Some(data)` if the entity was found and contains the specified data.
/// Otherwise `None` is returned.
///
/// # Safety
///
/// Accessing a component which is already being concurrently accessed elsewhere is undefined behavior.
///
/// # Panics
///
/// This function may panic if any other code is currently borrowing `T` mutable or if the component was not declared
/// as written by this system.
unsafe fn get_component_mut_unchecked<T: Component>(&self, entity: Entity)
-> Option<RefMut<T>>;
/// Mutably borrows entity data for the given entity.
///
/// Returns `Some(data)` if the entity was found and contains the specified data.
/// Otherwise `None` is returned.
///
/// # Panics
///
/// This function may panic if the component was not declared as written by this system.
#[inline]
fn get_component_mut<T: Component>(&mut self, entity: Entity) -> Option<RefMut<T>> {
// safe because the &mut self ensures exclusivity
unsafe { self.get_component_mut_unchecked(entity) }
}
/// Gets tag data for the given entity.
///
/// Returns `Some(data)` if the entity was found and contains the specified data.
/// Otherwise `None` is returned.
fn get_tag<T: Tag>(&self, entity: Entity) -> Option<&T>;
/// Determines if the given `Entity` is alive within this `World`.
fn is_alive(&self, entity: Entity) -> bool;
/// Gets the entity component storage. Validates that the world can provide access to everything needed by the view.
fn get_component_storage<V: for<'a> View<'a>>(
&self,
) -> Result<StorageAccessor, ComponentAccessError>;
}
#[derive(Default, Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct WorldId(usize, usize);
impl WorldId {
fn next(universe: usize) -> Self {
Self(universe, NEXT_WORLD_ID.fetch_add(1, Ordering::SeqCst))
}
pub fn index(self) -> usize { self.0 }
pub fn is_same_universe(self, other: WorldId) -> bool { self.0 == other.0 }
}
/// Contains queryable collections of data associated with `Entity`s.
pub struct World {
id: WorldId,
storage: UnsafeCell<Storage>,
pub entity_allocator: Arc<GuidEntityAllocator>,
entity_locations: Locations,
defrag_progress: usize,
command_buffer_size: usize,
pub(crate) allocation_buffer: Vec<Entity>,
}
unsafe impl Send for World {}
unsafe impl Sync for World {}
impl World {
pub const DEFAULT_COMMAND_BUFFER_SIZE: usize = 64;
/// Create a new `World` independent of any `Universe`.
///
/// `Entity` IDs in such a world will only be unique within that world. See also
/// `Universe::create_world`.
pub fn new() -> Self {
Self::new_in_universe(
WorldId::next(0),
GuidEntityAllocator::default()
)
}
fn new_in_universe(id: WorldId, allocator: GuidEntityAllocator) -> Self {
Self {
id,
storage: UnsafeCell::new(Storage::new(id)),
entity_allocator: Arc::new(allocator),
entity_locations: Locations::new(),
defrag_progress: 0,
command_buffer_size: Self::DEFAULT_COMMAND_BUFFER_SIZE,
allocation_buffer: Vec::with_capacity(Self::DEFAULT_COMMAND_BUFFER_SIZE),
}
}
#[inline]
pub fn command_buffer_size(&self) -> usize { self.command_buffer_size }
#[inline]
pub fn set_command_buffer_size(&mut self, command_buffer_size: usize) {
self.command_buffer_size = command_buffer_size;
}
/// Subscribes to event notifications.
///
/// A filter determines which events are of interest. Use `any()` to listen to all events.
///
/// # Examples
///
/// ```
/// # use legion_core::prelude::*;
/// # #[derive(Copy, Clone, Debug, PartialEq)]
/// # struct Position(f32);
/// # #[derive(Copy, Clone, Debug, PartialEq)]
/// # struct Model;
/// # let universe = Universe::new();
/// # let mut world = universe.create_world();
/// let (sender, receiver) = crossbeam_channel::unbounded();
/// world.subscribe(sender, component::<Position>() | tag::<Model>());
///
/// for event in receiver.try_iter() {
/// println!("{:?}", event);
/// }
/// ```
pub fn subscribe<T: EntityFilter + Sync + 'static>(
&mut self,
sender: crossbeam_channel::Sender<Event>,
filter: T,
) {
self.storage_mut().subscribe(sender, filter);
}
pub fn storage(&self) -> &Storage { unsafe { &*self.storage.get() } }
pub fn storage_mut(&mut self) -> &mut Storage { unsafe { &mut *self.storage.get() } }
/// Gets the unique ID of this world within its universe.
pub fn id(&self) -> WorldId { self.id }
pub fn get_entity_location(&self, entity: Entity) -> Option<EntityLocation> {
if self.is_alive(entity) {
self.entity_locations.get(entity)
} else {
None
}
}
/// Iterate all entities in existence. Internally this iterates archetypes instead of
/// entity allocators because the data structures contains a list of free entities instead
/// of allocated entities
pub fn iter_entities<'a>(&'a self) -> impl Iterator<Item = Entity> + 'a {
self.storage()
.archetypes()
.iter()
.flat_map(|archetype_data| archetype_data.iter_entities().map(|entity| entity))
}
/// Inserts new entities into the world. This insertion method should be preferred, as it performs
/// no movement of components for inserting multiple entities and components.
///
/// # Examples
///
/// Inserting entity tuples:
///
/// ```
/// # use legion_core::prelude::*;
/// # #[derive(Copy, Clone, Debug, PartialEq)]
/// # struct Position(f32);
/// # #[derive(Copy, Clone, Debug, PartialEq)]
/// # struct Rotation(f32);
/// # let universe = Universe::new();
/// # let mut world = universe.create_world();
/// # let model = 0u8;
/// # let color = 0u16;
/// let tags = (model, color);
/// let data = vec![
/// (Position(0.0), Rotation(0.0)),
/// (Position(1.0), Rotation(1.0)),
/// (Position(2.0), Rotation(2.0)),
/// ];
/// world.insert(tags, data);
/// ```
#[inline]
pub fn insert<T, C>(&mut self, tags: T, components: C) -> &[Entity]
where
T: TagSet + TagLayout + for<'a> Filter<ChunksetFilterData<'a>>,
C: IntoComponentSource,
{
self.insert_impl(tags, components.into())
}
pub(crate) fn insert_impl<T, C>(&mut self, mut tags: T, mut components: C) -> &[Entity]
where
T: TagSet + TagLayout + for<'a> Filter<ChunksetFilterData<'a>>,
C: ComponentSource,
{
let span = span!(Level::TRACE, "Inserting entities", world = self.id().0);
let _guard = span.enter();
// find or create archetype
let archetype_index = self.find_or_create_archetype(&mut tags, &mut components);
// find or create chunk set
let chunk_set_index = self.find_or_create_chunk(archetype_index, &mut tags);
self.allocation_buffer.clear();
self.allocation_buffer.reserve(components.len());
// insert components into chunks
while !components.is_empty() {
// get chunk component storage
let archetype =
unsafe { (&mut *self.storage.get()).archetype_unchecked_mut(archetype_index) };
let chunk_index = archetype.get_free_chunk(chunk_set_index, 1);
let chunk = unsafe {
archetype
.chunkset_unchecked_mut(chunk_set_index)
.chunk_unchecked_mut(chunk_index)
};
// insert as many components as we can into the chunk
let allocated = components.write(self.entity_allocator.create_entities(), chunk);
// record new entity locations
let start = chunk.len() - allocated;
let added = chunk.entities().iter().enumerate().skip(start);
for (i, e) in added {
let location = EntityLocation::new(
archetype_index,
chunk_set_index,
chunk_index,
ComponentIndex(i),
);
self.entity_locations.set(*e, location);
self.allocation_buffer.push(*e);
}
}
trace!(count = self.allocation_buffer.len(), "Inserted entities");
&self.allocation_buffer
}
/// Removes the given `Entity` from the `World`.
///
/// Returns `true` if the entity was deleted; else `false`.
pub fn delete(&mut self, entity: Entity) -> bool {
if !self.is_alive(entity) {
return false;
}
if self.entity_allocator.delete_entity(entity) {
let location = self.entity_locations.get(entity).unwrap();
self.delete_location(location);
trace!(world = self.id().0, ?entity, "Deleted entity");
true
} else {
false
}
}
/// Delete all entity data. This leaves subscriptions and the command buffer intact.
pub fn delete_all(&mut self) {
for archetype in self.storage_mut().archetypes_mut() {
archetype.delete_all();
}
self.entity_allocator.delete_all_entities();
}
fn delete_location(&mut self, location: EntityLocation) {
// find entity's chunk
let chunk = self.storage_mut().chunk_mut(location).unwrap();
// swap remove with last entity in chunk
if let Some(swapped) = chunk.swap_remove(location.component(), true) {
// record swapped entity's new location
self.entity_locations.set(swapped, location);
}
}
fn find_chunk_with_delta(
&mut self,
source_location: EntityLocation,
add_components: &[(ComponentTypeId, ComponentMeta)],
remove_components: &[ComponentTypeId],
add_tags: &[(TagTypeId, TagMeta, NonNull<u8>)],
remove_tags: &[TagTypeId],
) -> (ArchetypeIndex, SetIndex) {
let archetype = {
let result = {
let source_archetype = self
.storage()
.archetype(source_location.archetype())
.unwrap();
// find target chunk
let mut component_layout = DynamicComponentLayout {
existing: source_archetype.description().components(),
add: add_components,
remove: remove_components,
};
let mut tag_layout = DynamicTagLayout {
storage: self.storage(),
archetype: source_location.archetype(),
set: source_location.set(),
existing: source_archetype.description().tags(),
add: add_tags,
remove: remove_tags,
};
let archetype = self.find_archetype(&mut tag_layout, &mut component_layout);
if let Some(archetype) = archetype.as_ref() {
if let Some(chunk) = self.find_chunk_set(*archetype, &mut tag_layout) {
// fast path: chunk already exists
return (*archetype, chunk);
}
Ok(*archetype)
} else {
let mut description = ArchetypeDescription::default();
component_layout.tailor_archetype(&mut description);
tag_layout.tailor_archetype(&mut description);
Err(description)
}
};
match result {
Ok(arch) => arch,
Err(desc) => {
let (index, _) = unsafe { &mut *self.storage.get() }.alloc_archetype(desc);
index
}
}
};
// slow path: create new chunk
let source_archetype = self
.storage()
.archetype(source_location.archetype())
.unwrap();
let mut tags = source_archetype.tags().tag_set(source_location.set());
for type_id in remove_tags.iter() {
tags.remove(*type_id);
}
for (type_id, meta, ptr) in add_tags.iter() {
tags.push(*type_id, *meta, *ptr);
}
let chunk = self.create_chunk_set(archetype, &tags);
(archetype, chunk)
}
fn move_entity(
&mut self,
entity: Entity,
add_components: &[(ComponentTypeId, ComponentMeta)],
remove_components: &[ComponentTypeId],
add_tags: &[(TagTypeId, TagMeta, NonNull<u8>)],
remove_tags: &[TagTypeId],
) -> &mut ComponentStorage {
let location = self.entity_locations.get(entity).expect("entity not found");
// find or create the target chunk
let (target_arch_index, target_chunkset_index) = self.find_chunk_with_delta(
location,
add_components,
remove_components,
add_tags,
remove_tags,
);
// Safety Note:
// It is only safe for us to have 2 &mut references to storage here because
// we know we are only going to be modifying two chunks that are at different
// indexes.
// fetch entity's chunk
let current_chunk = unsafe { &mut *self.storage.get() }
.chunk_mut(location)
.unwrap();
// fetch target chunk
let archetype = unsafe { &mut *self.storage.get() }
.archetype_mut(target_arch_index)
.unwrap();
let target_chunk_index = archetype.get_free_chunk(target_chunkset_index, 1);
let target_chunk = unsafe {
archetype
.chunkset_unchecked_mut(target_chunkset_index)
.chunk_unchecked_mut(target_chunk_index)
};
// move existing data over into new chunk
if let Some(swapped) = current_chunk.move_entity(target_chunk, location.component()) {
// update location of any entity that was moved into the previous location
self.entity_locations.set(swapped, location);
}
// record the entity's new location
self.entity_locations.set(
entity,
EntityLocation::new(
target_arch_index,
target_chunkset_index,
target_chunk_index,
ComponentIndex(target_chunk.len() - 1),
),
);
target_chunk
}
/// Adds a component to an entity, or sets its value if the component is
/// already present.
///
/// # Notes
/// This function has the overhead of moving the entity to either an existing or new archetype,
/// causing a memory copy of the entity to a new location. This function should not be used
/// multiple times in successive order.
pub fn add_component<T: Component>(
&mut self,
entity: Entity,
component: T,
) -> Result<(), EntityMutationError> {
if !self.is_alive(entity) {
return Err(EntityMutationError::DoesNotExist);
}
if let Some(mut comp) = self.get_component_mut(entity) {
*comp = component;
return Ok(());
}
trace!(
world = self.id().0,
?entity,
component = std::any::type_name::<T>(),
"Adding component to entity"
);
// move the entity into a suitable chunk
let target_chunk = self.move_entity(
entity,
&[(ComponentTypeId::of::<T>(), ComponentMeta::of::<T>())],
&[],
&[],
&[],
);
// push new component into chunk
let mut writer = target_chunk.writer();
let (_, components) = writer.get();
let slice = [component];
unsafe {
let components = &mut *components.get();
components
.get_mut(ComponentTypeId::of::<T>())
.unwrap()
.writer()
.push(&slice);
}
std::mem::forget(slice);
Ok(())
}
/// Removes a component from an entity.
///
/// # Notes
/// This function has the overhead of moving the entity to either an existing or new archetype,
/// causing a memory copy of the entity to a new location. This function should not be used
/// multiple times in successive order.
///
/// `World::remove_components` should be used for adding multiple omponents to an entity at once.
pub fn remove_component<T: Component>(
&mut self,
entity: Entity,
) -> Result<(), EntityMutationError> {
if !self.is_alive(entity) {
return Err(EntityMutationError::DoesNotExist);
}
if self.get_component::<T>(entity).is_some() {
trace!(
world = self.id().0,
?entity,
component = std::any::type_name::<T>(),
"Removing component from entity"
);
// move the entity into a suitable chunk
self.move_entity(entity, &[], &[ComponentTypeId::of::<T>()], &[], &[]);
}
Ok(())
}
/// Removes
///
/// # Notes
/// This function is provided for bulk deleting components from an entity. This difference between this
/// function and `remove_component` is this allows us to remove multiple components and still only
/// perform a single move operation of the entity.
pub fn remove_components<T: ComponentTypeTupleSet>(
&mut self,
entity: Entity,
) -> Result<(), EntityMutationError> {
if !self.is_alive(entity) {
return Err(EntityMutationError::DoesNotExist);
}
let components = T::collect();
for component in components.iter() {
if !self.has_component_by_id(entity, *component) {
return Ok(());
}
}
self.move_entity(entity, &[], &components, &[], &[]);
Ok(())
}
/// Adds a tag to an entity, or sets its value if the tag is
/// already present.
pub fn add_tag<T: Tag>(&mut self, entity: Entity, tag: T) -> Result<(), EntityMutationError> {
if !self.is_alive(entity) {
return Err(EntityMutationError::DoesNotExist);
}
if self.get_tag::<T>(entity).is_some() {
self.remove_tag::<T>(entity)?;
}
trace!(
world = self.id().0,
?entity,
tag = std::any::type_name::<T>(),
"Adding tag to entity"
);
// move the entity into a suitable chunk
self.move_entity(
entity,
&[],
&[],
&[(
TagTypeId::of::<T>(),
TagMeta::of::<T>(),
NonNull::new(&tag as *const _ as *mut u8).unwrap(),
)],
&[],
);
Ok(())
}
/// Removes a tag from an entity.
pub fn remove_tag<T: Tag>(&mut self, entity: Entity) -> Result<(), EntityMutationError> {
if !self.is_alive(entity) {
return Err(EntityMutationError::DoesNotExist);
}
if self.get_tag::<T>(entity).is_some() {
trace!(
world = self.id().0,
?entity,
tag = std::any::type_name::<T>(),
"Removing tag from entity"
);
// move the entity into a suitable chunk
self.move_entity(entity, &[], &[], &[], &[TagTypeId::of::<T>()]);
}
Ok(())
}
fn get_component_storage(&self, entity: Entity) -> Option<&ComponentStorage> {
let location = self.entity_locations.get(entity)?;
self.storage().chunk(location)
}
/// Returns the entity's component types, if the entity exists.
pub fn entity_component_types(
&self,
entity: Entity,
) -> Option<&[(ComponentTypeId, ComponentMeta)]> {
if !self.is_alive(entity) {
return None;
}
let location = self.entity_locations.get(entity);
let archetype = location
.map(|location| self.storage().archetype(location.archetype()))
.unwrap_or(None);
archetype.map(|archetype| archetype.description().components())
}
/// Returns the entity's tag types, if the entity exists.
pub fn entity_tag_types(&self, entity: Entity) -> Option<&[(TagTypeId, TagMeta)]> {
if !self.is_alive(entity) {
return None;
}
let location = self.entity_locations.get(entity);
let archetype = location
.map(|location| self.storage().archetype(location.archetype()))
.unwrap_or(None);
archetype.map(|archetype| archetype.description().tags())
}
/// Iteratively defragments the world's internal memory.
///
/// This compacts entities into fewer more continuous chunks.
///
/// `budget` describes the maximum number of entities that can be moved
/// in one call. Subsequent calls to `defrag` will resume progress from the
/// previous call.
pub fn defrag(&mut self, budget: Option<usize>) {
let span = span!(
Level::INFO,
"Defragmenting",
world = self.id().0,
start_archetype = self.defrag_progress
);
let _guard = span.enter();
let archetypes = unsafe { &mut *self.storage.get() }.archetypes_mut();
let mut budget = budget.unwrap_or(std::usize::MAX);
let start = self.defrag_progress;
while self.defrag_progress < archetypes.len() {
// defragment the next archetype
let complete =
(&mut archetypes[self.defrag_progress]).defrag(&mut budget, |e, location| {
self.entity_locations.set(e, location);
});
if complete {
// increment the index, looping it once we get to the end
self.defrag_progress = (self.defrag_progress + 1) % archetypes.len();
}
// stop once we run out of budget or reach back to where we started
if budget == 0 || self.defrag_progress == start {
break;
}
}
}
/// Move entities from a world to this world, copying all appropriate archetypes,
/// tags entities and components into this world.
pub fn move_from(&mut self, world: World) {
let span =
span!(Level::INFO, "Merging worlds", source = world.id().0, destination = ?self.id());
let _guard = span.enter();
self.entity_allocator
.merge(Arc::try_unwrap(world.entity_allocator).unwrap());
for archetype in unsafe { &mut *world.storage.get() }.drain(..) {
let target_archetype = {
// use the description as an archetype filter
let mut desc = archetype.description().clone();
let archetype_data = ArchetypeFilterData {
component_types: self.storage().component_types(),
tag_types: self.storage().tag_types(),
};
let matches = desc
.matches(archetype_data)
.matching_indices()
.next()
.map(ArchetypeIndex);
if let Some(arch_index) = matches {
// similar archetype already exists, merge
self.storage_mut()
.archetype_mut(arch_index)
.unwrap()
.move_from(archetype);
arch_index
} else {
// archetype does not already exist, append
self.storage_mut().push(archetype);
ArchetypeIndex(self.storage_mut().archetypes().len() - 1)
}
};
// update entity locations
let archetype = &unsafe { &*self.storage.get() }.archetypes()[target_archetype];
for (entity, location) in archetype.iter_entity_locations(target_archetype) {
self.entity_locations.set(entity, location);
}
}
}
/// This will *copy* the data from `src_world` into this world. The logic to do the copy is
/// delegated to the `clone_impl` provided by the user. In addition to simple copying, it's also
/// possible to transform from one type to another. This is useful for cases where you want to
/// read from serializable data (like a physics shape definition) and construct something that
/// isn't serializable (like a handle to a physics body)
///
/// By default, all entities in the new world will be assigned a new Entity. `result_mappings`
/// (if not None) will be populated with the old/new Entities, which allows for mapping data
/// between the old and new world.
///
/// If you want to replace existing entities (for example to hot-reload data from a file,)
/// populate `replace_mappings`. For every entry in this map, the key must exist in the source
/// world and the value must exist in the destination world. All entities in the destination
/// world referenced by this map will be deleted, and the entities copied over will be assigned
/// the same entity. If these constraints are not met, this function will panic.
pub fn clone_from<
's,
CloneImplT: CloneImpl,
CloneImplResultT: CloneImplResult,
EntityReplacePolicyT: EntityReplacePolicy<'s>,
>(
&mut self,
src_world: &World,
clone_impl: &CloneImplT,
clone_impl_result: &mut CloneImplResultT,
entity_replace_policy: &'s EntityReplacePolicyT,
) {
let span = span!(Level::INFO, "CloneMerging worlds", source = src_world.id().0, destination = ?self.id());
let _guard = span.enter();
let src_storage = unsafe { &(*src_world.storage.get()) };
let dst_storage = unsafe { &mut (*self.storage.get()) };
// First check that all the src entities exist in the source world. We're assuming the
// source data will be available later to replace the data we're about to delete
for k in entity_replace_policy.src_entities() {
if !src_world.entity_allocator.is_alive(k) {
panic!("clone_from assumes all replace_mapping keys exist in the source world");
}
}
// Delete all the data associated with dst_entities. This leaves the
// associated entities in a dangling state, but we'll fix this later when we copy the
// data over
for entity_to_replace in entity_replace_policy.dst_entities() {
if self.entity_allocator.is_alive(entity_to_replace) {
let location = self
.entity_locations
.get(entity_to_replace)
.expect("Failed to get location of live entity");
self.delete_location(location);
} else {
panic!(
"clone_from assumes all replace_mapping values exist in the destination world"
);
}
}
// Iterate all archetypes in the src world
for src_archetype in src_storage.archetypes() {
let archetype_data = ArchetypeFilterData {
component_types: self.storage().component_types(),
tag_types: self.storage().tag_types(),
};
let dst_archetype_index = World::find_or_create_archetype_for_clone_move(
clone_impl,
src_archetype.description(),
archetype_data,
dst_storage,
);
// Do the clone_from for this archetype
dst_storage
.archetype_mut(dst_archetype_index)
.unwrap()
.clone_from(
&src_world,
src_archetype,
dst_archetype_index,
&self.entity_allocator,
&mut self.entity_locations,
clone_impl,
clone_impl_result,
entity_replace_policy,
);
}
}
/// This will *copy* the `src_entity` from `src_world` into this world. The logic to do the copy
/// is delegated to the `clone_impl` provided by the user. In addition to simple copying, it's
/// also possible to transform from one type to another. This is useful for cases where you want
/// to read from serializable data (like a physics shape definition) and construct something
/// that isn't serializable (like a handle to a physics body)
///
/// By default, the entity in the new world will be assigned a new Entity. The return value
/// indicates the Entity in the new world, which allows for mapping data the old and new world.
///
/// If you want to replace an existing entity (for example to hot-reload data from a file,)
/// populate `replace_mapping`. This entity must exist in the destination world. The entity in
/// the destination world will be deleted, and the entity copied over will be assigned
/// the same entity. If these constraints are not met, this function will panic.
pub fn clone_from_single<C: CloneImpl>(
&mut self,
src_world: &World,
src_entity: Entity,
clone_impl: &C,
replace_mapping: Option<Entity>,
) -> Entity {
let span = span!(Level::INFO, "CloneMergingSingle worlds", source = src_world.id().0, destination = ?self.id());
let _guard = span.enter();
let src_storage = unsafe { &(*src_world.storage.get()) };
let dst_storage = unsafe { &mut (*self.storage.get()) };
if !src_world.entity_allocator.is_alive(src_entity) {
panic!("src_entity not alive");
}
// Erase all entities that are referred to by value. The code following will update the location
// of all these entities to point to new, valid locations
if let Some(replace_mapping) = replace_mapping {
if self.entity_allocator.is_alive(replace_mapping) {
let location = self
.entity_locations
.get(replace_mapping)
.expect("Failed to get location of live entity");
self.delete_location(location);
} else {
panic!("clone_from_single assumes entity_mapping exists in the destination world");
}
}
let src_location = src_world.entity_locations.get(src_entity).unwrap();
let src_archetype = &src_storage.archetypes()[src_location.archetype()];
// Iterate all archetypes in the src world
let archetype_data = ArchetypeFilterData {
component_types: self.storage().component_types(),
tag_types: self.storage().tag_types(),
};
let dst_archetype_index = World::find_or_create_archetype_for_clone_move(
clone_impl,
src_archetype.description(),
archetype_data,
dst_storage,
);
// Do the clone_from for this archetype
dst_storage
.archetype_mut(dst_archetype_index)
.unwrap()
.clone_from_single(
&src_world,
src_archetype,
&src_location,
dst_archetype_index,
&self.entity_allocator,
&mut self.entity_locations,
clone_impl,
replace_mapping,
)
}
fn find_or_create_archetype_for_clone_move<C: CloneImpl>(
clone_impl: &C,
src_archetype_description: &ArchetypeDescription,
archetype_data: ArchetypeFilterData,
dst_storage: &mut Storage,
) -> ArchetypeIndex {
// Build the archetype that we will write into. The caller of this function provides an
// impl to do the clone, optionally transforming components from one type to another
let mut dst_archetype = ArchetypeDescription::default();
for (from_type_id, _from_meta) in src_archetype_description.components() {
let (into_type_id, into_meta) = clone_impl.map_component_type(*from_type_id);
dst_archetype.register_component_raw(into_type_id, into_meta);
}
// Find or create the archetype in the destination world
let matches = dst_archetype
.matches(archetype_data)
.matching_indices()
.next();
// If it doesn't exist, allocate it
if let Some(arch_index) = matches {
ArchetypeIndex(arch_index)
} else {