1use crate::alter::{AlterState, QueryAlterState};
15use crate::archetype::{
16 Archetype, ArchetypeIndex, ArchetypeInfo, ComponentInfo, Row, ShareArchetype,
17};
18use crate::column::{BlobRef, Column};
19#[cfg(debug_assertions)]
20use crate::column::{ARCHETYPE_INDEX, COMPONENT_INDEX};
21use crate::editor::{EditorState, EntityEditor};
22use crate::fetch::{ColumnTick, FetchComponents};
23use crate::filter::FilterComponents;
24use crate::insert::{Bundle, InsertState};
25use crate::listener::{EventListKey, ListenerMgr};
26use crate::multi_res::ResVec;
27use crate::prelude::Mut;
28use crate::query::{QueryError, QueryState};
29use crate::single_res::TickRes;
30use crate::system::{SystemMeta, TypeInfo};
31use crate::world_ptr::Ptr;
32use core::fmt::*;
33use core::result::Result;
34use std::marker::PhantomData;
35use dashmap::mapref::entry::Entry;
36use dashmap::DashMap;
37use fixedbitset::FixedBitSet;
38use pi_append_vec::{SafeVec, SafeVecIter};
39use pi_key_alloter::new_key_type;
40use std::any::{Any, TypeId};
41use std::borrow::Cow;
42use std::collections::{hash_map::Entry as StdEntry, HashMap};
43use std::mem::{self, size_of, transmute, ManuallyDrop};
44use std::ops::Deref;
45use std::ptr;
46use std::sync::atomic::Ordering;
47use pi_null::Null;
50use pi_share::{Share, ShareUsize};
51use pi_slot::{Iter, SlotMap};
52
53new_key_type! {
54 pub struct Entity;
55}
56
57#[derive(Debug, Clone, Copy, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
58pub struct ComponentIndex(pub(crate) u32);
59impl ComponentIndex {
60 pub fn index(&self) -> usize {
61 self.0 as usize
62 }
63}
64impl From<u32> for ComponentIndex {
65 fn from(index: u32) -> Self {
66 Self(index)
67 }
68}
69impl From<usize> for ComponentIndex {
70 fn from(index: usize) -> Self {
71 Self(index as u32)
72 }
73}
74impl pi_null::Null for ComponentIndex {
75 fn null() -> Self {
76 Self(u32::null())
77 }
78 fn is_null(&self) -> bool {
79 self.0 == u32::null()
80 }
81}
82#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
83pub struct Tick(u32);
84impl Tick {
85 pub fn index(&self) -> usize {
86 self.0 as usize
87 }
88 pub fn max() -> Self {
89 Self(u32::MAX)
90 }
91}
92impl Deref for Tick {
93 type Target = u32;
94 fn deref(&self) -> &Self::Target {
95 &self.0
96 }
97}
98impl Null for Tick {
99 fn null() -> Self {
100 Self(0)
101 }
102 fn is_null(&self) -> bool {
103 self.0 == 0
104 }
105}
106impl From<u32> for Tick {
107 fn from(v: u32) -> Self {
108 Self(v)
109 }
110}
111impl From<usize> for Tick {
112 fn from(v: usize) -> Self {
113 Self(v as u32)
114 }
115}
116
117#[derive(Clone, Debug)]
118pub struct ArchetypeInit<'a>(pub &'a ShareArchetype, pub &'a World);
119#[derive(Clone, Debug)]
120pub struct ArchetypeOk<'a>(pub &'a ShareArchetype, pub ArchetypeIndex, pub &'a World);
121
122
123pub struct World {
124 pub(crate) single_res_map: HashMap<TypeId, usize>,
125 pub(crate) single_res_arr: Vec<Option<Share<dyn TickMut>>>,
126 pub(crate) multi_res_map: HashMap<TypeId, (Share<dyn Any + Send + Sync>, Share<ShareUsize>)>,
127 pub(crate) event_map: HashMap<TypeId, Share<dyn Settle>>, pub(crate) component_map: HashMap<TypeId, ComponentIndex>,
129 pub(crate) component_arr: Vec<Share<Column>>,
130 pub(crate) entities: SlotMap<Entity, EntityAddr>,
131 pub(crate) archetype_map: DashMap<u64, ShareArchetype>,
132 pub(crate) archetype_arr: SafeVec<ShareArchetype>,
133 pub(crate) archetype_arr_len: usize,
134 pub(crate) empty_archetype: ShareArchetype,
135 pub(crate) entity_editor_state: EditorState,
136 pub(crate) listener_mgr: ListenerMgr,
137 archetype_init_key: EventListKey,
138 archetype_ok_key: EventListKey,
139 tick: ShareUsize,
141 default_system_meta: SystemMeta,
142}
143impl Debug for World {
144 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
145 f.debug_struct("World")
146 .field("entitys", &self.entities)
147 .field("component_arr", &self.component_arr)
148 .field("archetype_arr", &self.archetype_arr)
149 .finish()
150 }
151}
152impl World {
153 #[inline]
154 pub fn create() -> Box<Self> {
155 Box::new(Self::new())
157 }
158
159 fn new() -> Self {
160 #[cfg(debug_assertions)]
161 match std::env::var("ECS_DEBUG") {
162 Ok(r) => {
163 let r = r.split(",").map(|r| {
164 if r == "*" {
165 std::usize::MAX
166 } else {
167 r.parse::<usize>().unwrap()
168 }
169
170 }).collect::<Vec<usize>>();
171 if r.len() == 2 {
172 ARCHETYPE_INDEX.store(r[0], Ordering::Relaxed);
173 COMPONENT_INDEX.store(r[1], Ordering::Relaxed);
174 }
175 },
176 _ => (),
177 };
178
179 let listener_mgr = ListenerMgr::default();
180 let archetype_init_key = listener_mgr.init_register_event::<ArchetypeInit>();
181 let archetype_ok_key = listener_mgr.init_register_event::<ArchetypeOk>();
182 let mut empty = Archetype::new(Default::default());
183 empty.set_index(0usize.into());
184 empty.ready.store(true, Ordering::Relaxed);
185 let empty_archetype = ShareArchetype::new(empty);
186 let archetype_map = DashMap::new();
187 archetype_map.insert(0, empty_archetype.clone());
188 let archetype_arr = SafeVec::with_capacity(1);
189 archetype_arr.insert(empty_archetype.clone());
190 Self {
191 single_res_map: Default::default(),
192 single_res_arr: Default::default(),
193 multi_res_map: Default::default(),
194 event_map: Default::default(),
195 entities: Default::default(),
196 component_map: Default::default(),
197 component_arr: Default::default(),
198 archetype_map,
199 archetype_arr,
200 archetype_arr_len: 1,
201 empty_archetype,
202 listener_mgr,
203 archetype_init_key,
204 archetype_ok_key,
205 tick: ShareUsize::new(1),
206 entity_editor_state: Default::default(),
207 default_system_meta: SystemMeta::new(TypeInfo::of::<()>()),
208 }
209 }
210 pub fn tick(&self) -> Tick {
212 self.tick.load(Ordering::Relaxed).into()
213 }
214 pub fn increment_tick(&self) -> Tick {
216 self.tick.fetch_add(1, Ordering::Relaxed).into()
217 }
218 pub fn get_entity_prototype(&self, entity: Entity) -> Option<(&Cow<'static, str>, ArchetypeIndex)> {
235 self.entities.get(entity).map(|e| {
236 let ar_index = e.archetype_index();
237 let ar = self.archetype_arr.get(ar_index.index()).unwrap();
238 (ar.name(), ar_index.into())
239 })
240 }
241 pub fn contains(&self, entity: Entity) -> bool {
243 self.entities.contains_key(entity)
244 }
245 pub fn get_component_index(&self, component_type_id: &TypeId) -> ComponentIndex {
247 self.component_map
248 .get(component_type_id)
249 .map_or(ComponentIndex::null(), |r| *r)
250 }
251 pub fn add_component_indexs(
253 &mut self,
254 components: Vec<ComponentInfo>,
255 result: &mut Vec<(ComponentIndex, bool)>,
256 result_add: bool,
257 ) {
258 for c in components {
259 result.push((self.add_component_info(c).0, result_add));
260 }
261 }
262 pub fn get_column_by_id(&self, component_type_id: &TypeId) -> Option<&Share<Column>> {
264 self.get_column(self.get_component_index(component_type_id))
265 }
266 pub fn get_column(&self, index: ComponentIndex) -> Option<&Share<Column>> {
268 self.component_arr.get(index.index())
269 }
270 pub unsafe fn get_column_unchecked(&self, index: ComponentIndex) -> &Share<Column> {
272 self.component_arr.get_unchecked(index.index())
273 }
274 pub fn add_component_info(
276 &mut self,
277 mut info: ComponentInfo,
278 ) -> (ComponentIndex, Share<Column>) {
279 let tick_info = info.tick_info;
280 let index: ComponentIndex = match self.component_map.entry(*info.type_id()) {
281 StdEntry::Occupied(entry) => *entry.get(),
282 StdEntry::Vacant(entry) => {
283 let index = self.component_arr.len().into();
284 info.index = index;
285 let c = Share::new(Column::new(info));
286 self.component_arr.push(c.clone());
287 entry.insert(index);
288 return (index, c);
289 }
290 };
291 let column = unsafe { self.component_arr.get_unchecked_mut(index.index()) };
292 let c = unsafe { Share::get_mut_unchecked(column) };
293 let t = c.info.tick_info | tick_info;
294 if t != c.info.tick_info {
295 let tick = self.tick.load(Ordering::Relaxed).into();
296 c.info.info.tick_info = tick_info;
297 c.update(&self.archetype_arr, |r, row, _| {
299 r.set_tick_unchecked(row, tick);
300 });
301 }
302 (index, column.clone())
303 }
304 pub fn init_component<T: 'static>(&mut self) -> ComponentIndex {
306 self.add_component_info(ComponentInfo::of::<T>(0)).0
307 }
308 pub(crate) fn archetype_info(&mut self, components: Vec<ComponentInfo>) -> ArchetypeInfo {
310 let vec: Vec<Share<Column>> = components
311 .into_iter()
312 .map(|c| self.add_component_info(c).1)
313 .collect();
314 ArchetypeInfo::sort(vec)
315 }
316 pub fn make_insert<B: Bundle>(&mut self) -> InsertState<B> {
318 let components = B::components(Vec::new());
319 let ar = self.find_ar(components);
320 let s = B::init_item(self, &ar);
321 InsertState::new(ar, s, Ptr::new(&mut self.default_system_meta), Ptr::new(self))
322 }
323 pub fn query<Q: FetchComponents + 'static, F: FilterComponents + 'static = ()>(
325 &mut self,
326 ) -> QueryState<Q, F> {
327 self.make_query()
328 }
329 pub fn make_query<Q: FetchComponents + 'static, F: FilterComponents + 'static = ()>(
331 &mut self,
332 ) -> QueryState<Q, F> {
333 self.default_system_meta.this_run = self.tick();
334 let meta = Ptr::new(&mut self.default_system_meta);
335 let mut state = QueryState::create(self, meta);
336 state.align();
337 state
338 }
339 pub fn make_alter<
341 Q: FetchComponents + 'static,
342 F: FilterComponents + 'static,
343 A: Bundle + 'static,
344 D: Bundle + 'static,
345 >(
346 &mut self,
347 ) -> QueryAlterState<Q, F, A, D> {
348 self.default_system_meta.this_run = self.tick();
349 let meta = Ptr::new(&mut self.default_system_meta);
350 let mut query_state = QueryState::create(self, meta);
351 let mut alter_state =
352 AlterState::make(self, A::components(Vec::new()), D::components(Vec::new()));
353 query_state.align();
354 alter_state.align(self, &query_state.archetypes);
356 QueryAlterState(query_state, alter_state, Ptr::new(self), PhantomData)
357 }
358 pub fn make_entity_editor(&mut self) -> EntityEditor {
360 EntityEditor::new(self)
361 }
362
363 pub fn unsafe_world<'a>(&self) -> ManuallyDrop<&'a mut World> {
364 unsafe { transmute(self) }
365 }
366
367 pub(crate) fn empty_archetype(&self) -> &ShareArchetype {
368 &self.empty_archetype
369 }
370 pub fn len<'a>(&'a self) -> usize {
371 self.entities.len()
372 }
373
374 pub fn entities_iter<'a>(&'a self) -> Iter<'a, Entity, EntityAddr> {
375 self.entities.iter()
376 }
377 pub fn insert_single_res<T: 'static>(&mut self, value: T) -> usize {
379 let tid = TypeId::of::<T>();
380 let (flag, index) = self._insert_single_res(tid);
381 if flag {
382 self.single_res_arr[index] = Some(Share::new(TickRes::new(value)));
383 }
384 index
393 }
394
395 fn _insert_single_res(&mut self, tid: TypeId) -> (bool, usize) {
396 let index = *self.single_res_map.entry(tid).or_insert_with(|| {
397 let index = self.single_res_arr.len();
398 self.single_res_arr.push(None);
399 index
400 });
401 (self.single_res_arr[index].is_none(), index)
402 }
403
404 pub fn or_register_single_res(&mut self, type_info: TypeInfo) -> usize {
406 *self
407 .single_res_map
408 .entry(type_info.type_id)
409 .or_insert_with(|| {
410 let index = self.single_res_arr.len();
411 self.single_res_arr.push(None);
412 index
413 })
414 }
415
416 pub fn register_single_res<T: 'static>(&mut self) -> usize {
417 self._register_single_res(TypeId::of::<T>())
418 }
419
420 pub fn _register_single_res(&mut self, tid: TypeId) -> usize {
421 *self
422 .single_res_map
423 .entry(tid)
424 .or_insert_with(|| {
425 let index = self.single_res_arr.len();
426 self.single_res_arr.push(None);
427 index
428 })
429 }
430
431 pub fn init_single_res<T: 'static + FromWorld>(&mut self) -> usize {
433 let tid = TypeId::of::<T>();
434 let (flag, index) = self._init_single_res(tid);
435 if flag {
436 let value = T::from_world(self);
437 self.single_res_arr[index] = Some(Share::new(TickRes::new(value)));
438 }
439 index
449 }
450 pub fn _init_single_res(&mut self, tid: TypeId) -> (bool, usize) {
451 let index = *self.single_res_map.entry(tid).or_insert_with(|| {
452 let index = self.single_res_arr.len();
453 self.single_res_arr.push(None);
454 index
455 });
456 (self.single_res_arr[index].is_none(), index)
457 }
458
459 #[inline]
461 pub fn index_single_res<T: 'static>(&self, index: usize) -> Option<&TickRes<T>> {
462 match self._index_single_res(index) {
469 Some(r) => r.downcast_ref(),
470 None => None,
471 }
472 }
473
474 fn _index_single_res(&self, index: usize) -> Option<&dyn Any> {
476 self.single_res_arr.get(index).map_or(None, |r| {
477 match r {
478 Some(r) => Some(r.as_any()),
479 None => None,
480 }
481 })
482 }
483 #[inline]
485 pub fn index_single_res_mut<T: 'static>(
486 &mut self,
487 index: usize,
488 ) -> Option<&mut TickRes<T>> {
489 match self._index_single_res_mut(index) {
496 Some(r) => r.downcast_mut(),
497 None => None,
498 }
499 }
500 fn _index_single_res_mut(
501 &mut self,
502 index: usize,
503 ) -> Option<&mut dyn Any> {
504 self.single_res_arr.get_mut(index).map_or(None, |r| {
505 match r {
506 Some(r) => unsafe { Some(Share::get_mut_unchecked(r).as_any_mut()) },
507 None => None,
508 }
509 })
510 }
511 pub fn get_share_single_res<T: 'static>(&self) -> Option<Share<TickRes<T>>> {
514 let tid = TypeId::of::<T>();
515 self.get_single_res_any(&tid).map(|r| Share::downcast(r.clone().into_any()).unwrap())
516 }
517
518 #[inline]
520 pub fn get_single_res<T: 'static>(&self) -> Option<&TickRes<T>> {
521 let tid = TypeId::of::<T>();
522 match self._get_single_res(&tid) {
523 Some(val) => val.downcast_ref(),
524 None => return None,
525 }
526 }
527 fn _get_single_res(&self, tid: &TypeId) -> Option<&dyn Any> {
528 match self.single_res_map.get(tid) {
529 Some(index) => self._index_single_res(*index),
530 None => return None,
531 }
532 }
533 pub fn get_single_res_mut<T: 'static>(&mut self) -> Option<&mut TickRes<T>> {
536 let tid = TypeId::of::<T>();
537 match self._get_single_res_mut(&tid) {
538 Some(index) => index.downcast_mut(),
539 None => return None,
540 }
541 }
542 fn _get_single_res_mut(&mut self, tid: &TypeId) -> Option<&mut dyn Any> {
543 match self.single_res_map.get(tid) {
544 Some(index) => self._index_single_res_mut(*index),
545 None => return None,
546 }
547 }
548 pub(crate) fn get_single_res_any(&self, tid: &TypeId) -> Option<&Share<dyn TickMut>> {
549 match self.single_res_map.get(tid) {
550 Some(index) => self.index_single_res_any(*index),
551 None => return None,
552 }
553 }
554 pub(crate) fn index_single_res_any(&self, index: usize) -> Option<&Share<dyn TickMut>> {
555 self.single_res_arr.get(index).map_or(None, |r| r.as_ref())
556 }
557
558 pub fn init_multi_res(&mut self, type_id: TypeId, vec: Share<dyn Any + Send + Sync>) -> (Share<dyn Any + Send + Sync>, Share<ShareUsize>) {
560 self.multi_res_map.entry(type_id).or_insert_with(|| (vec, Share::new(ShareUsize::new(0)))).clone()
561 }
562 pub fn get_multi_res<T>(&self) -> Option<(Share<ResVec<T>>, Share<ShareUsize>)> {
564 let tid = TypeId::of::<T>();
565 self.multi_res_map.get(&tid).map(|(r, t)| {
566 (Share::downcast(r.clone()).unwrap(), t.clone())
567 })
568 }
569
570 pub(crate) fn init_event_record(
572 &mut self,
573 type_id: TypeId,
574 event_record: Share<dyn Settle>,
575 ) -> Share<dyn Settle> {
576 let r = self
577 .event_map
578 .entry(type_id)
579 .or_insert_with(|| event_record);
580 r.clone()
581 }
582 pub(crate) fn get_event_record(&self, type_id: &TypeId) -> Option<Share<dyn Settle>> {
584 self.event_map.get(type_id).map(|r| r.clone())
585 }
586
587 pub fn get_component<T: 'static>(&self, e: Entity) -> Result<&T, QueryError> {
589 let index = self.get_component_index(&TypeId::of::<T>());
590 self.get_component_by_index(e, index)
591 }
592 pub fn get_component_mut<T: 'static>(
594 &mut self,
595 e: Entity,
596 ) -> Result<Mut<'static, T>, QueryError> {
597 let index = self.get_component_index(&TypeId::of::<T>());
598 self.get_component_mut_by_index(e, index)
599 }
600
601 pub fn get_component_by_index<T: 'static>(
603 &self,
604 e: Entity,
605 index: ComponentIndex,
606 ) -> Result<&T, QueryError> {
607 match self._get_component_by_index(e, index) {
621 Ok((c, addr)) => match c {
622 Some(c) => Ok(c.get::<T>(addr.row, e)),
623 None => Err(QueryError::MissingComponent(index, addr.archetype_index())),
624 },
625 Err(e) => Err(e),
626 }
627 }
628
629 fn _get_component_by_index<'w>(
630 &'w self,
631 e: Entity,
632 index: ComponentIndex,
633 ) -> Result<(Option<BlobRef<'_>>, &'w EntityAddr), QueryError> {
634 let addr = match self.entities.get(e) {
635 Some(v) => v,
636 None => return Err(QueryError::NoSuchEntity(e)),
637 };
638 let column = match self.get_column(index) {
639 Some(c) => c,
640 None => return Err(QueryError::NoSuchComponent(index)),
641 };
642 let column = column.blob_ref(addr.archetype_index());
643 return Ok((column, addr));
644 }
645 pub fn get_component_mut_by_index<T: 'static>(
647 &mut self,
648 e: Entity,
649 index: ComponentIndex,
650 ) -> Result<Mut<'static, T>, QueryError> {
651 let addr = match self.entities.get(e) {
652 Some(v) => v,
653 None => return Err(QueryError::NoSuchEntity(e)),
654 };
655 let column = match self.get_column(index) {
656 Some(c) => c,
657 None => return Err(QueryError::NoSuchComponent(index)),
658 };
659 let column = column.blob_ref(addr.archetype_index());
660 match column {
661 Some(c) => {
662 let t = self.tick();
663 let value: Mut<T> = Mut::new(&ColumnTick::new(c, t, t), e, addr.row);
664 Ok(unsafe { transmute(value) })
665 },
666 None => Err(QueryError::MissingComponent(index, addr.archetype_index())),
667 }
668 }
669
670 pub fn get_archetype(&self, index: ArchetypeIndex) -> Option<&ShareArchetype> {
671 self.archetype_arr.get(index.0 as usize)
672 }
673 pub(crate) unsafe fn get_archetype_unchecked(&self, index: ArchetypeIndex) -> &ShareArchetype {
674 self.archetype_arr.get_unchecked(index.0 as usize)
675 }
676 pub fn archetype_list<'a>(&'a self) -> SafeVecIter<'a, ShareArchetype> {
677 self.archetype_arr.iter()
678 }
679 pub(crate) fn find_ar(&mut self, infos: Vec<ComponentInfo>) -> ShareArchetype {
681 let info = self.archetype_info(infos);
682 self.find_archtype(info)
683 }
684 pub(crate) fn find_archtype(&self, info: ArchetypeInfo) -> ShareArchetype {
686 let (mut ar, b) = match self.archetype_map.entry(info.id) {
688 Entry::Occupied(entry) => (entry.get().clone(), false),
689 Entry::Vacant(entry) => {
690 let ar = Share::new(Archetype::new(info));
691 entry.insert(ar.clone());
692 (ar, true)
693 }
694 };
695 if b {
696 self.listener_mgr
698 .notify_event(self.archetype_init_key, ArchetypeInit(&ar, &self));
699 let ar_index = self.archtype_ok(&mut ar);
701 self.listener_mgr
703 .notify_event(self.archetype_ok_key, ArchetypeOk(&ar, ar_index, &self));
704 ar
705 } else {
706 loop {
708 if !ar.ready() {
709 std::hint::spin_loop();
710 }
711 return ar;
712 }
713 }
714 }
715 pub(crate) fn archtype_ok(&self, ar: &mut ShareArchetype) -> ArchetypeIndex {
717 let entry = self.archetype_arr.alloc_entry();
718 let index = entry.index();
719 let mut_ar = unsafe { Share::get_mut_unchecked(ar) };
720 mut_ar.set_index(index.into());
721 mut_ar.init_blobs(); ar.ready.store(true, Ordering::Relaxed);
723 entry.insert(ar.clone()); index.into()
725 }
726 pub(crate) fn insert_addr(&self, ar_index: ArchetypeIndex, row: Row) -> Entity {
729 self.entities.insert(EntityAddr::new(ar_index, row))
730 }
731 pub(crate) fn replace(&self, e: Entity, ar_index: ArchetypeIndex, row: Row) -> EntityAddr {
734 let addr = unsafe { self.entities.load_unchecked(e) };
735 mem::replace(addr, EntityAddr::new(ar_index, row))
736 }
737 pub fn contains_entity(&self, e: Entity) -> bool {
739 self.entities.get(e).is_some()
740 }
741 pub fn destroy_entity(&mut self, e: Entity) -> Result<(), QueryError> {
743 let addr = match self.entities.get(e) {
744 Some(v) => *v,
745 None => return Err(QueryError::NoSuchEntity(e)),
746 };
747 if addr.row.is_null() {
748 self.entities.remove(e).unwrap();
749 return Ok(());
750 }
751 let ar = unsafe {
752 self.archetype_arr
753 .get_unchecked(addr.archetype_index().index())
754 };
755 let e = ar.destroy(addr.row);
756 if e.is_null() {
757 return Err(QueryError::NoSuchRow(addr.row));
758 }
759 self.entities.remove(e).unwrap();
760 Ok(())
761 }
762
763 pub fn spawn_empty(&self) -> Entity {
765 self.entities
766 .insert(EntityAddr::new(0usize.into(), Row::null()))
767 }
768 pub(crate) fn replace_row(&self, e: Entity, row: Row) {
771 let addr = unsafe { self.entities.load_unchecked(e) };
772 addr.row = row;
773 }
774 pub fn mem_size(&self) -> usize {
776 let mut size = self.entities.mem_size();
777 self.component_arr.iter().for_each(|item| {
779 size += item.memsize();
780 });
781 size += (self.component_arr.capacity() - self.component_arr.len()) * size_of::<Column>();
782 size += self.archetype_arr.capacity() * size_of::<Archetype>();
783 for ar in self.archetype_arr.iter() {
784 size += ar.mem_size();
785 }
786 size += self.listener_mgr.memsize();
787 size += self.archetype_arr_len;
788 size += self.archetype_map.len();
789 size += self.component_map.len();
790 size += self.single_res_arr.len();
791 size
792 }
793 pub fn settle(&mut self) {
795 self.settle_by(&mut Vec::new(), &mut FixedBitSet::new())
796 }
797 pub fn init_ok(&mut self) {
799 }
801 pub fn settle_by(&mut self, action: &mut Vec<(Row, Row)>, set: &mut FixedBitSet) {
803 self.entities.settle(0);
805 self.archetype_arr.settle(0);
807 let len = self.archetype_arr.len();
808 if self.archetype_arr_len < len {
809 for c in self.component_arr.iter_mut() {
811 let c = unsafe { Share::get_mut_unchecked(c) };
812 c.settle();
813 }
814 self.archetype_arr_len = len;
815 }
816 for aer in self.event_map.values_mut() {
818 let er = unsafe { Share::get_mut_unchecked(aer) };
819 er.settle();
820 }
821 for ar in self.archetype_arr.iter() {
824 let archetype = unsafe { Share::get_mut_unchecked(ar) };
825 archetype.settle(self, action, set);
826 }
827 }
828}
829unsafe impl Send for World {}
830unsafe impl Sync for World {}
831impl Default for World {
832 fn default() -> Self {
833 Self::new()
834 }
835}
836
837pub trait Downcast {
838 fn into_any(self: Share<Self>) -> Share<dyn Any + Send + Sync>;
839 fn into_box_any(self: Box<Self>) -> Box<dyn Any>;
840 fn as_any(&self) -> &dyn Any;
841 fn as_any_mut(&mut self) -> &mut dyn Any;
842}
843
844pub trait TickMut: Downcast {
845 fn get_tick(&self) -> Tick;
846 fn set_tick(&mut self, tick: Tick);
847}
848
849pub trait Settle: Downcast {
850 fn settle(&mut self);
851}
852
853pub trait FromWorld {
858 fn from_world(world: &mut World) -> Self;
860}
861
862impl<T: Default> FromWorld for T {
863 default fn from_world(_world: &mut World) -> Self {
864 T::default()
865 }
866}
867
868pub trait SetFromWorld {
869 fn set_fn() -> Option<fn(&mut World, *mut u8)>;
870}
871impl<T> SetFromWorld for T {
872 default fn set_fn() -> Option<fn(&mut World, *mut u8)> {
873 None
874 }
875}
876impl<T: FromWorld> SetFromWorld for T {
877 fn set_fn() -> Option<fn(&mut World, *mut u8)> {
878 Some(|world, ptr| unsafe { ptr::write(ptr as *mut T, T::from_world(world)) })
879 }
880}
881
882
883#[derive(Debug, Default, Clone, Copy)]
884pub struct EntityAddr {
885 index: ArchetypeIndex,
886 pub(crate) row: Row,
887}
888unsafe impl Sync for EntityAddr {}
889unsafe impl Send for EntityAddr {}
890
891impl EntityAddr {
892 pub(crate) fn new(index: ArchetypeIndex, row: Row) -> Self {
894 EntityAddr {
895 index,
896 row,
897 }
898 }
899 #[inline(always)]
900 pub(crate) fn is_mark(&self) -> bool {
901 self.index.0 < 0
902 }
903 pub(crate) fn mark(&mut self) {
905 self.index = ArchetypeIndex(-self.index.0 - 1);
906 }
907 pub fn archetype_index(&self) -> ArchetypeIndex {
909 if self.index.0 >= 0 || self.index.is_null() {
910 self.index
911 } else {
912 ArchetypeIndex(-self.index.0 - 1)
913 }
914 }
915}