-
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathmod.rs
2856 lines (2625 loc) · 107 KB
/
mod.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
//! Defines the [`World`] and APIs for accessing it directly.
mod command_queue;
mod deferred_world;
mod entity_ref;
pub mod error;
mod spawn_batch;
pub mod unsafe_world_cell;
mod world_cell;
pub use crate::change_detection::{Mut, Ref, CHECK_TICK_THRESHOLD};
pub use crate::world::command_queue::CommandQueue;
pub use deferred_world::DeferredWorld;
pub use entity_ref::{
EntityMut, EntityRef, EntityWorldMut, Entry, FilteredEntityMut, FilteredEntityRef,
OccupiedEntry, VacantEntry,
};
pub use spawn_batch::*;
pub use world_cell::*;
use crate::{
archetype::{ArchetypeComponentId, ArchetypeId, ArchetypeRow, Archetypes},
bundle::{Bundle, BundleInserter, BundleSpawner, Bundles},
change_detection::{MutUntyped, TicksMut},
component::{
Component, ComponentDescriptor, ComponentHooks, ComponentId, ComponentInfo, ComponentTicks,
Components, Tick,
},
entity::{AllocAtWithoutReplacement, Entities, Entity, EntityLocation},
event::{Event, EventId, Events, SendBatchIds},
query::{DebugCheckedUnwrap, QueryData, QueryEntityError, QueryFilter, QueryState},
removal_detection::RemovedComponentEvents,
schedule::{Schedule, ScheduleLabel, Schedules},
storage::{ResourceData, Storages},
system::{Commands, Res, Resource},
world::error::TryRunScheduleError,
};
use bevy_ptr::{OwningPtr, Ptr};
use bevy_utils::tracing::warn;
use std::{
any::TypeId,
fmt,
mem::MaybeUninit,
sync::atomic::{AtomicU32, Ordering},
};
mod identifier;
use self::unsafe_world_cell::{UnsafeEntityCell, UnsafeWorldCell};
pub use identifier::WorldId;
/// A [`World`] mutation.
///
/// Should be used with [`Commands::add`].
///
/// # Usage
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # use bevy_ecs::world::Command;
/// // Our world resource
/// #[derive(Resource, Default)]
/// struct Counter(u64);
///
/// // Our custom command
/// struct AddToCounter(u64);
///
/// impl Command for AddToCounter {
/// fn apply(self, world: &mut World) {
/// let mut counter = world.get_resource_or_insert_with(Counter::default);
/// counter.0 += self.0;
/// }
/// }
///
/// fn some_system(mut commands: Commands) {
/// commands.add(AddToCounter(42));
/// }
/// ```
pub trait Command: Send + 'static {
/// Applies this command, causing it to mutate the provided `world`.
///
/// This method is used to define what a command "does" when it is ultimately applied.
/// Because this method takes `self`, you can store data or settings on the type that implements this trait.
/// This data is set by the system or other source of the command, and then ultimately read in this method.
fn apply(self, world: &mut World);
}
/// Stores and exposes operations on [entities](Entity), [components](Component), resources,
/// and their associated metadata.
///
/// Each [`Entity`] has a set of components. Each component can have up to one instance of each
/// component type. Entity components can be created, updated, removed, and queried using a given
/// [`World`].
///
/// For complex access patterns involving [`SystemParam`](crate::system::SystemParam),
/// consider using [`SystemState`](crate::system::SystemState).
///
/// To mutate different parts of the world simultaneously,
/// use [`World::resource_scope`] or [`SystemState`](crate::system::SystemState).
///
/// ## Resources
///
/// Worlds can also store [`Resource`]s,
/// which are unique instances of a given type that don't belong to a specific Entity.
/// There are also *non send resources*, which can only be accessed on the main thread.
/// See [`Resource`] for usage.
pub struct World {
id: WorldId,
pub(crate) entities: Entities,
pub(crate) components: Components,
pub(crate) archetypes: Archetypes,
pub(crate) storages: Storages,
pub(crate) bundles: Bundles,
pub(crate) removed_components: RemovedComponentEvents,
/// Access cache used by [`WorldCell`]. Is only accessed in the `Drop` impl of `WorldCell`.
pub(crate) archetype_component_access: ArchetypeComponentAccess,
pub(crate) change_tick: AtomicU32,
pub(crate) last_change_tick: Tick,
pub(crate) last_check_tick: Tick,
pub(crate) command_queue: CommandQueue,
}
impl Default for World {
fn default() -> Self {
Self {
id: WorldId::new().expect("More `bevy` `World`s have been created than is supported"),
entities: Entities::new(),
components: Default::default(),
archetypes: Archetypes::new(),
storages: Default::default(),
bundles: Default::default(),
removed_components: Default::default(),
archetype_component_access: Default::default(),
// Default value is `1`, and `last_change_tick`s default to `0`, such that changes
// are detected on first system runs and for direct world queries.
change_tick: AtomicU32::new(1),
last_change_tick: Tick::new(0),
last_check_tick: Tick::new(0),
command_queue: CommandQueue::default(),
}
}
}
impl World {
/// Creates a new empty [`World`].
///
/// # Panics
///
/// If [`usize::MAX`] [`World`]s have been created.
/// This guarantee allows System Parameters to safely uniquely identify a [`World`],
/// since its [`WorldId`] is unique
#[inline]
pub fn new() -> World {
World::default()
}
/// Retrieves this [`World`]'s unique ID
#[inline]
pub fn id(&self) -> WorldId {
self.id
}
/// Creates a new [`UnsafeWorldCell`] view with complete read+write access.
#[inline]
pub fn as_unsafe_world_cell(&mut self) -> UnsafeWorldCell<'_> {
UnsafeWorldCell::new_mutable(self)
}
/// Creates a new [`UnsafeWorldCell`] view with only read access to everything.
#[inline]
pub fn as_unsafe_world_cell_readonly(&self) -> UnsafeWorldCell<'_> {
UnsafeWorldCell::new_readonly(self)
}
/// Retrieves this world's [`Entities`] collection.
#[inline]
pub fn entities(&self) -> &Entities {
&self.entities
}
/// Retrieves this world's [`Entities`] collection mutably.
///
/// # Safety
/// Mutable reference must not be used to put the [`Entities`] data
/// in an invalid state for this [`World`]
#[inline]
pub unsafe fn entities_mut(&mut self) -> &mut Entities {
&mut self.entities
}
/// Retrieves this world's [`Archetypes`] collection.
#[inline]
pub fn archetypes(&self) -> &Archetypes {
&self.archetypes
}
/// Retrieves this world's [`Components`] collection.
#[inline]
pub fn components(&self) -> &Components {
&self.components
}
/// Retrieves this world's [`Storages`] collection.
#[inline]
pub fn storages(&self) -> &Storages {
&self.storages
}
/// Retrieves this world's [`Bundles`] collection.
#[inline]
pub fn bundles(&self) -> &Bundles {
&self.bundles
}
/// Retrieves this world's [`RemovedComponentEvents`] collection
#[inline]
pub fn removed_components(&self) -> &RemovedComponentEvents {
&self.removed_components
}
/// Retrieves a [`WorldCell`], which safely enables multiple mutable World accesses at the same
/// time, provided those accesses do not conflict with each other.
#[inline]
pub fn cell(&mut self) -> WorldCell<'_> {
WorldCell::new(self)
}
/// Creates a new [`Commands`] instance that writes to the world's command queue
/// Use [`World::flush_commands`] to apply all queued commands
#[inline]
pub fn commands(&mut self) -> Commands {
Commands::new_from_entities(&mut self.command_queue, &self.entities)
}
/// Initializes a new [`Component`] type and returns the [`ComponentId`] created for it.
pub fn init_component<T: Component>(&mut self) -> ComponentId {
self.components.init_component::<T>(&mut self.storages)
}
/// Returns a mutable reference to the [`ComponentHooks`] for a [`Component`] type.
///
/// Will panic if `T` exists in any archetypes.
pub fn register_component_hooks<T: Component>(&mut self) -> &mut ComponentHooks {
let index = self.init_component::<T>();
assert!(!self.archetypes.archetypes.iter().any(|a| a.contains(index)), "Components hooks cannot be modified if the component already exists in an archetype, use init_component if {} may already be in use", std::any::type_name::<T>());
// SAFETY: We just created this component
unsafe { self.components.get_hooks_mut(index).debug_checked_unwrap() }
}
/// Returns a mutable reference to the [`ComponentHooks`] for a [`Component`] with the given id if it exists.
///
/// Will panic if `id` exists in any archetypes.
pub fn register_component_hooks_by_id(
&mut self,
id: ComponentId,
) -> Option<&mut ComponentHooks> {
assert!(!self.archetypes.archetypes.iter().any(|a| a.contains(id)), "Components hooks cannot be modified if the component already exists in an archetype, use init_component if the component with id {:?} may already be in use", id);
self.components.get_hooks_mut(id)
}
/// Initializes a new [`Component`] type and returns the [`ComponentId`] created for it.
///
/// This method differs from [`World::init_component`] in that it uses a [`ComponentDescriptor`]
/// to initialize the new component type instead of statically available type information. This
/// enables the dynamic initialization of new component definitions at runtime for advanced use cases.
///
/// While the option to initialize a component from a descriptor is useful in type-erased
/// contexts, the standard `World::init_component` function should always be used instead
/// when type information is available at compile time.
pub fn init_component_with_descriptor(
&mut self,
descriptor: ComponentDescriptor,
) -> ComponentId {
self.components
.init_component_with_descriptor(&mut self.storages, descriptor)
}
/// Returns the [`ComponentId`] of the given [`Component`] type `T`.
///
/// The returned `ComponentId` is specific to the `World` instance
/// it was retrieved from and should not be used with another `World` instance.
///
/// Returns [`None`] if the `Component` type has not yet been initialized within
/// the `World` using [`World::init_component`].
///
/// ```
/// use bevy_ecs::prelude::*;
///
/// let mut world = World::new();
///
/// #[derive(Component)]
/// struct ComponentA;
///
/// let component_a_id = world.init_component::<ComponentA>();
///
/// assert_eq!(component_a_id, world.component_id::<ComponentA>().unwrap())
/// ```
///
/// # See also
///
/// * [`Components::component_id()`]
/// * [`Components::get_id()`]
#[inline]
pub fn component_id<T: Component>(&self) -> Option<ComponentId> {
self.components.component_id::<T>()
}
/// Retrieves an [`EntityRef`] that exposes read-only operations for the given `entity`.
/// This will panic if the `entity` does not exist. Use [`World::get_entity`] if you want
/// to check for entity existence instead of implicitly panic-ing.
///
/// ```
/// use bevy_ecs::{component::Component, world::World};
///
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// let mut world = World::new();
/// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
/// let position = world.entity(entity).get::<Position>().unwrap();
/// assert_eq!(position.x, 0.0);
/// ```
#[inline]
#[track_caller]
pub fn entity(&self, entity: Entity) -> EntityRef {
#[inline(never)]
#[cold]
#[track_caller]
fn panic_no_entity(entity: Entity) -> ! {
panic!("Entity {entity:?} does not exist");
}
match self.get_entity(entity) {
Some(entity) => entity,
None => panic_no_entity(entity),
}
}
/// Retrieves an [`EntityWorldMut`] that exposes read and write operations for the given `entity`.
/// This will panic if the `entity` does not exist. Use [`World::get_entity_mut`] if you want
/// to check for entity existence instead of implicitly panic-ing.
///
/// ```
/// use bevy_ecs::{component::Component, world::World};
///
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// let mut world = World::new();
/// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
/// let mut entity_mut = world.entity_mut(entity);
/// let mut position = entity_mut.get_mut::<Position>().unwrap();
/// position.x = 1.0;
/// ```
#[inline]
#[track_caller]
pub fn entity_mut(&mut self, entity: Entity) -> EntityWorldMut {
#[inline(never)]
#[cold]
#[track_caller]
fn panic_no_entity(entity: Entity) -> ! {
panic!("Entity {entity:?} does not exist");
}
match self.get_entity_mut(entity) {
Some(entity) => entity,
None => panic_no_entity(entity),
}
}
/// Gets an [`EntityRef`] for multiple entities at once.
///
/// # Panics
///
/// If any entity does not exist in the world.
///
/// # Examples
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut world = World::new();
/// # let id1 = world.spawn_empty().id();
/// # let id2 = world.spawn_empty().id();
/// // Getting multiple entities.
/// let [entity1, entity2] = world.many_entities([id1, id2]);
/// ```
///
/// ```should_panic
/// # use bevy_ecs::prelude::*;
/// # let mut world = World::new();
/// # let id1 = world.spawn_empty().id();
/// # let id2 = world.spawn_empty().id();
/// // Trying to get a despawned entity will fail.
/// world.despawn(id2);
/// world.many_entities([id1, id2]);
/// ```
pub fn many_entities<const N: usize>(&mut self, entities: [Entity; N]) -> [EntityRef<'_>; N] {
#[inline(never)]
#[cold]
#[track_caller]
fn panic_no_entity(entity: Entity) -> ! {
panic!("Entity {entity:?} does not exist");
}
match self.get_many_entities(entities) {
Ok(refs) => refs,
Err(entity) => panic_no_entity(entity),
}
}
/// Gets mutable access to multiple entities at once.
///
/// # Panics
///
/// If any entities do not exist in the world,
/// or if the same entity is specified multiple times.
///
/// # Examples
///
/// Disjoint mutable access.
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut world = World::new();
/// # let id1 = world.spawn_empty().id();
/// # let id2 = world.spawn_empty().id();
/// // Disjoint mutable access.
/// let [entity1, entity2] = world.many_entities_mut([id1, id2]);
/// ```
///
/// Trying to access the same entity multiple times will fail.
///
/// ```should_panic
/// # use bevy_ecs::prelude::*;
/// # let mut world = World::new();
/// # let id = world.spawn_empty().id();
/// world.many_entities_mut([id, id]);
/// ```
pub fn many_entities_mut<const N: usize>(
&mut self,
entities: [Entity; N],
) -> [EntityMut<'_>; N] {
#[inline(never)]
#[cold]
#[track_caller]
fn panic_on_err(e: QueryEntityError) -> ! {
panic!("{e}");
}
match self.get_many_entities_mut(entities) {
Ok(borrows) => borrows,
Err(e) => panic_on_err(e),
}
}
/// Returns the components of an [`Entity`] through [`ComponentInfo`].
#[inline]
pub fn inspect_entity(&self, entity: Entity) -> Vec<&ComponentInfo> {
let entity_location = self
.entities()
.get(entity)
.unwrap_or_else(|| panic!("Entity {entity:?} does not exist"));
let archetype = self
.archetypes()
.get(entity_location.archetype_id)
.unwrap_or_else(|| {
panic!(
"Archetype {:?} does not exist",
entity_location.archetype_id
)
});
archetype
.components()
.filter_map(|id| self.components().get_info(id))
.collect()
}
/// Returns an [`EntityWorldMut`] for the given `entity` (if it exists) or spawns one if it doesn't exist.
/// This will return [`None`] if the `entity` exists with a different generation.
///
/// # Note
/// Spawning a specific `entity` value is rarely the right choice. Most apps should favor [`World::spawn`].
/// This method should generally only be used for sharing entities across apps, and only when they have a
/// scheme worked out to share an ID space (which doesn't happen by default).
#[inline]
pub fn get_or_spawn(&mut self, entity: Entity) -> Option<EntityWorldMut> {
self.flush_entities();
match self.entities.alloc_at_without_replacement(entity) {
AllocAtWithoutReplacement::Exists(location) => {
// SAFETY: `entity` exists and `location` is that entity's location
Some(unsafe { EntityWorldMut::new(self, entity, location) })
}
AllocAtWithoutReplacement::DidNotExist => {
// SAFETY: entity was just allocated
Some(unsafe { self.spawn_at_empty_internal(entity) })
}
AllocAtWithoutReplacement::ExistsWithWrongGeneration => None,
}
}
/// Retrieves an [`EntityRef`] that exposes read-only operations for the given `entity`.
/// Returns [`None`] if the `entity` does not exist.
/// Instead of unwrapping the value returned from this function, prefer [`World::entity`].
///
/// ```
/// use bevy_ecs::{component::Component, world::World};
///
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// let mut world = World::new();
/// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
/// let entity_ref = world.get_entity(entity).unwrap();
/// let position = entity_ref.get::<Position>().unwrap();
/// assert_eq!(position.x, 0.0);
/// ```
#[inline]
pub fn get_entity(&self, entity: Entity) -> Option<EntityRef> {
let location = self.entities.get(entity)?;
// SAFETY: if the Entity is invalid, the function returns early.
// Additionally, Entities::get(entity) returns the correct EntityLocation if the entity exists.
let entity_cell =
UnsafeEntityCell::new(self.as_unsafe_world_cell_readonly(), entity, location);
// SAFETY: The UnsafeEntityCell has read access to the entire world.
let entity_ref = unsafe { EntityRef::new(entity_cell) };
Some(entity_ref)
}
/// Gets an [`EntityRef`] for multiple entities at once.
///
/// # Errors
///
/// If any entity does not exist in the world.
///
/// # Examples
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut world = World::new();
/// # let id1 = world.spawn_empty().id();
/// # let id2 = world.spawn_empty().id();
/// // Getting multiple entities.
/// let [entity1, entity2] = world.get_many_entities([id1, id2]).unwrap();
///
/// // Trying to get a despawned entity will fail.
/// world.despawn(id2);
/// assert!(world.get_many_entities([id1, id2]).is_err());
/// ```
pub fn get_many_entities<const N: usize>(
&self,
entities: [Entity; N],
) -> Result<[EntityRef<'_>; N], Entity> {
let mut refs = [MaybeUninit::uninit(); N];
for (r, id) in std::iter::zip(&mut refs, entities) {
*r = MaybeUninit::new(self.get_entity(id).ok_or(id)?);
}
// SAFETY: Each item was initialized in the above loop.
let refs = refs.map(|r| unsafe { MaybeUninit::assume_init(r) });
Ok(refs)
}
/// Returns an [`Entity`] iterator of current entities.
///
/// This is useful in contexts where you only have read-only access to the [`World`].
#[inline]
pub fn iter_entities(&self) -> impl Iterator<Item = EntityRef<'_>> + '_ {
self.archetypes.iter().flat_map(|archetype| {
archetype
.entities()
.iter()
.enumerate()
.map(|(archetype_row, archetype_entity)| {
let entity = archetype_entity.id();
let location = EntityLocation {
archetype_id: archetype.id(),
archetype_row: ArchetypeRow::new(archetype_row),
table_id: archetype.table_id(),
table_row: archetype_entity.table_row(),
};
// SAFETY: entity exists and location accurately specifies the archetype where the entity is stored.
let cell = UnsafeEntityCell::new(
self.as_unsafe_world_cell_readonly(),
entity,
location,
);
// SAFETY: `&self` gives read access to the entire world.
unsafe { EntityRef::new(cell) }
})
})
}
/// Returns a mutable iterator over all entities in the `World`.
pub fn iter_entities_mut(&mut self) -> impl Iterator<Item = EntityMut<'_>> + '_ {
let world_cell = self.as_unsafe_world_cell();
world_cell.archetypes().iter().flat_map(move |archetype| {
archetype
.entities()
.iter()
.enumerate()
.map(move |(archetype_row, archetype_entity)| {
let entity = archetype_entity.id();
let location = EntityLocation {
archetype_id: archetype.id(),
archetype_row: ArchetypeRow::new(archetype_row),
table_id: archetype.table_id(),
table_row: archetype_entity.table_row(),
};
// SAFETY: entity exists and location accurately specifies the archetype where the entity is stored.
let cell = UnsafeEntityCell::new(world_cell, entity, location);
// SAFETY: We have exclusive access to the entire world. We only create one borrow for each entity,
// so none will conflict with one another.
unsafe { EntityMut::new(cell) }
})
})
}
/// Retrieves an [`EntityWorldMut`] that exposes read and write operations for the given `entity`.
/// Returns [`None`] if the `entity` does not exist.
/// Instead of unwrapping the value returned from this function, prefer [`World::entity_mut`].
///
/// ```
/// use bevy_ecs::{component::Component, world::World};
///
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// let mut world = World::new();
/// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
/// let mut entity_mut = world.get_entity_mut(entity).unwrap();
/// let mut position = entity_mut.get_mut::<Position>().unwrap();
/// position.x = 1.0;
/// ```
#[inline]
pub fn get_entity_mut(&mut self, entity: Entity) -> Option<EntityWorldMut> {
let location = self.entities.get(entity)?;
// SAFETY: `entity` exists and `location` is that entity's location
Some(unsafe { EntityWorldMut::new(self, entity, location) })
}
/// Gets mutable access to multiple entities.
///
/// # Errors
///
/// If any entities do not exist in the world,
/// or if the same entity is specified multiple times.
///
/// # Examples
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut world = World::new();
/// # let id1 = world.spawn_empty().id();
/// # let id2 = world.spawn_empty().id();
/// // Disjoint mutable access.
/// let [entity1, entity2] = world.get_many_entities_mut([id1, id2]).unwrap();
///
/// // Trying to access the same entity multiple times will fail.
/// assert!(world.get_many_entities_mut([id1, id1]).is_err());
/// ```
pub fn get_many_entities_mut<const N: usize>(
&mut self,
entities: [Entity; N],
) -> Result<[EntityMut<'_>; N], QueryEntityError> {
// Ensure each entity is unique.
for i in 0..N {
for j in 0..i {
if entities[i] == entities[j] {
return Err(QueryEntityError::AliasedMutability(entities[i]));
}
}
}
// SAFETY: Each entity is unique.
unsafe { self.get_entities_mut_unchecked(entities) }
}
/// # Safety
/// `entities` must contain no duplicate [`Entity`] IDs.
unsafe fn get_entities_mut_unchecked<const N: usize>(
&mut self,
entities: [Entity; N],
) -> Result<[EntityMut<'_>; N], QueryEntityError> {
let world_cell = self.as_unsafe_world_cell();
let mut cells = [MaybeUninit::uninit(); N];
for (cell, id) in std::iter::zip(&mut cells, entities) {
*cell = MaybeUninit::new(
world_cell
.get_entity(id)
.ok_or(QueryEntityError::NoSuchEntity(id))?,
);
}
// SAFETY: Each item was initialized in the loop above.
let cells = cells.map(|c| unsafe { MaybeUninit::assume_init(c) });
// SAFETY:
// - `world_cell` has exclusive access to the entire world.
// - The caller ensures that each entity is unique, so none
// of the borrows will conflict with one another.
let borrows = cells.map(|c| unsafe { EntityMut::new(c) });
Ok(borrows)
}
/// Spawns a new [`Entity`] and returns a corresponding [`EntityWorldMut`], which can be used
/// to add components to the entity or retrieve its id.
///
/// ```
/// use bevy_ecs::{component::Component, world::World};
///
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
/// #[derive(Component)]
/// struct Label(&'static str);
/// #[derive(Component)]
/// struct Num(u32);
///
/// let mut world = World::new();
/// let entity = world.spawn_empty()
/// .insert(Position { x: 0.0, y: 0.0 }) // add a single component
/// .insert((Num(1), Label("hello"))) // add a bundle of components
/// .id();
///
/// let position = world.entity(entity).get::<Position>().unwrap();
/// assert_eq!(position.x, 0.0);
/// ```
pub fn spawn_empty(&mut self) -> EntityWorldMut {
self.flush_entities();
let entity = self.entities.alloc();
// SAFETY: entity was just allocated
unsafe { self.spawn_at_empty_internal(entity) }
}
/// Spawns a new [`Entity`] with a given [`Bundle`] of [components](`Component`) and returns
/// a corresponding [`EntityWorldMut`], which can be used to add components to the entity or
/// retrieve its id.
///
/// ```
/// use bevy_ecs::{bundle::Bundle, component::Component, world::World};
///
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// #[derive(Component)]
/// struct Velocity {
/// x: f32,
/// y: f32,
/// };
///
/// #[derive(Component)]
/// struct Name(&'static str);
///
/// #[derive(Bundle)]
/// struct PhysicsBundle {
/// position: Position,
/// velocity: Velocity,
/// }
///
/// let mut world = World::new();
///
/// // `spawn` can accept a single component:
/// world.spawn(Position { x: 0.0, y: 0.0 });
/// // It can also accept a tuple of components:
/// world.spawn((
/// Position { x: 0.0, y: 0.0 },
/// Velocity { x: 1.0, y: 1.0 },
/// ));
/// // Or it can accept a pre-defined Bundle of components:
/// world.spawn(PhysicsBundle {
/// position: Position { x: 2.0, y: 2.0 },
/// velocity: Velocity { x: 0.0, y: 4.0 },
/// });
///
/// let entity = world
/// // Tuples can also mix Bundles and Components
/// .spawn((
/// PhysicsBundle {
/// position: Position { x: 2.0, y: 2.0 },
/// velocity: Velocity { x: 0.0, y: 4.0 },
/// },
/// Name("Elaina Proctor"),
/// ))
/// // Calling id() will return the unique identifier for the spawned entity
/// .id();
/// let position = world.entity(entity).get::<Position>().unwrap();
/// assert_eq!(position.x, 2.0);
/// ```
pub fn spawn<B: Bundle>(&mut self, bundle: B) -> EntityWorldMut {
self.flush_entities();
let change_tick = self.change_tick();
let entity = self.entities.alloc();
let entity_location = {
let mut bundle_spawner = BundleSpawner::new::<B>(self, change_tick);
// SAFETY: bundle's type matches `bundle_info`, entity is allocated but non-existent
unsafe { bundle_spawner.spawn_non_existent(entity, bundle) }
};
// SAFETY: entity and location are valid, as they were just created above
unsafe { EntityWorldMut::new(self, entity, entity_location) }
}
/// # Safety
/// must be called on an entity that was just allocated
unsafe fn spawn_at_empty_internal(&mut self, entity: Entity) -> EntityWorldMut {
let archetype = self.archetypes.empty_mut();
// PERF: consider avoiding allocating entities in the empty archetype unless needed
let table_row = self.storages.tables[archetype.table_id()].allocate(entity);
// SAFETY: no components are allocated by archetype.allocate() because the archetype is
// empty
let location = unsafe { archetype.allocate(entity, table_row) };
// SAFETY: entity index was just allocated
unsafe {
self.entities.set(entity.index(), location);
}
EntityWorldMut::new(self, entity, location)
}
/// Spawns a batch of entities with the same component [`Bundle`] type. Takes a given
/// [`Bundle`] iterator and returns a corresponding [`Entity`] iterator.
/// This is more efficient than spawning entities and adding components to them individually,
/// but it is limited to spawning entities with the same [`Bundle`] type, whereas spawning
/// individually is more flexible.
///
/// ```
/// use bevy_ecs::{component::Component, entity::Entity, world::World};
///
/// #[derive(Component)]
/// struct Str(&'static str);
/// #[derive(Component)]
/// struct Num(u32);
///
/// let mut world = World::new();
/// let entities = world.spawn_batch(vec![
/// (Str("a"), Num(0)), // the first entity
/// (Str("b"), Num(1)), // the second entity
/// ]).collect::<Vec<Entity>>();
///
/// assert_eq!(entities.len(), 2);
/// ```
pub fn spawn_batch<I>(&mut self, iter: I) -> SpawnBatchIter<'_, I::IntoIter>
where
I: IntoIterator,
I::Item: Bundle,
{
SpawnBatchIter::new(self, iter.into_iter())
}
/// Retrieves a reference to the given `entity`'s [`Component`] of the given type.
/// Returns `None` if the `entity` does not have a [`Component`] of the given type.
/// ```
/// use bevy_ecs::{component::Component, world::World};
///
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// let mut world = World::new();
/// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
/// let position = world.get::<Position>(entity).unwrap();
/// assert_eq!(position.x, 0.0);
/// ```
#[inline]
pub fn get<T: Component>(&self, entity: Entity) -> Option<&T> {
self.get_entity(entity)?.get()
}
/// Retrieves a mutable reference to the given `entity`'s [`Component`] of the given type.
/// Returns `None` if the `entity` does not have a [`Component`] of the given type.
/// ```
/// use bevy_ecs::{component::Component, world::World};
///
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// let mut world = World::new();
/// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
/// let mut position = world.get_mut::<Position>(entity).unwrap();
/// position.x = 1.0;
/// ```
#[inline]
pub fn get_mut<T: Component>(&mut self, entity: Entity) -> Option<Mut<T>> {
// SAFETY:
// - `as_unsafe_world_cell` is the only thing that is borrowing world
// - `as_unsafe_world_cell` provides mutable permission to everything
// - `&mut self` ensures no other borrows on world data
unsafe { self.as_unsafe_world_cell().get_entity(entity)?.get_mut() }
}
/// Despawns the given `entity`, if it exists. This will also remove all of the entity's
/// [`Component`]s. Returns `true` if the `entity` is successfully despawned and `false` if
/// the `entity` does not exist.
///
/// # Note
///
/// This won't clean up external references to the entity (such as parent-child relationships
/// if you're using `bevy_hierarchy`), which may leave the world in an invalid state.
///
/// ```
/// use bevy_ecs::{component::Component, world::World};
///
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// let mut world = World::new();
/// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
/// assert!(world.despawn(entity));
/// assert!(world.get_entity(entity).is_none());
/// assert!(world.get::<Position>(entity).is_none());
/// ```
#[inline]
pub fn despawn(&mut self, entity: Entity) -> bool {
if let Some(entity) = self.get_entity_mut(entity) {
entity.despawn();
true
} else {
warn!("error[B0003]: Could not despawn entity {:?} because it doesn't exist in this World. See: https://bevyengine.org/learn/errors/#b0003", entity);
false
}
}
/// Clears the internal component tracker state.
///
/// The world maintains some internal state about changed and removed components. This state
/// is used by [`RemovedComponents`] to provide access to the entities that had a specific type
/// of component removed since last tick.
///
/// The state is also used for change detection when accessing components and resources outside
/// of a system, for example via [`World::get_mut()`] or [`World::get_resource_mut()`].
///
/// By clearing this internal state, the world "forgets" about those changes, allowing a new round
/// of detection to be recorded.
///
/// When using `bevy_ecs` as part of the full Bevy engine, this method is added as a system to the
/// main app, to run during `Last`, so you don't need to call it manually. When using `bevy_ecs`
/// as a separate standalone crate however, you need to call this manually.
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # #[derive(Component, Default)]
/// # struct Transform;
/// // a whole new world
/// let mut world = World::new();
///
/// // you changed it
/// let entity = world.spawn(Transform::default()).id();
///
/// // change is detected
/// let transform = world.get_mut::<Transform>(entity).unwrap();
/// assert!(transform.is_changed());
///
/// // update the last change tick
/// world.clear_trackers();
///
/// // change is no longer detected
/// let transform = world.get_mut::<Transform>(entity).unwrap();
/// assert!(!transform.is_changed());
/// ```
///
/// [`RemovedComponents`]: crate::removal_detection::RemovedComponents
pub fn clear_trackers(&mut self) {
self.removed_components.update();
self.last_change_tick = self.increment_change_tick();
}
/// Returns [`QueryState`] for the given [`QueryData`], which is used to efficiently
/// run queries on the [`World`] by storing and reusing the [`QueryState`].
/// ```