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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
//! [`Entity`] implementation, storage, and interation.
use std::{marker::PhantomData, rc::Rc};
use crate::prelude::*;
/// An entity index.
///
/// They are created using the `Entities` struct. They are used as indices with `Components`
/// structs.
///
/// Entities are conceptual "things" which possess attributes (Components). As an exemple, a Car
/// (Entity) has a Color (Component), a Position (Component) and a Speed (Component).
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(HasSchema, Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub struct Entity(u32, u32);
impl Entity {
/// An invalid entity, useful for placeholder entity values.
const INVALID: Entity = Entity(u32::MAX, u32::MAX);
/// Creates a new `Entity` from the provided index and generation.
///
/// > ⚠️ **Warning:** It is not generally recommended to manually create [`Entity`]s unless you
/// > know exactly what you are doing. This can be useful in certain advanced or unusual
/// > use-cases, but usually you should use [`Entities::create()`] to spawn entities.
pub fn new(index: u32, generation: u32) -> Entity {
Entity(index, generation)
}
/// Returns the index of this `Entity`.
///
/// In most cases, you do not want to use this directly.
/// However, it can be useful to create caches to improve performances.
pub fn index(&self) -> u32 {
self.0
}
/// Returns the generation of this `Entity`.
///
///
/// In most cases, you do not want to use this directly.
/// However, it can be useful to create caches to improve performances.
pub fn generation(&self) -> u32 {
self.1
}
}
impl Default for Entity {
fn default() -> Self {
Self::INVALID
}
}
/// Holds a list of alive entities.
///
/// It also holds a list of entities that were recently killed, which allows to remove components of
/// deleted entities at the end of a game frame.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, HasSchema)]
pub struct Entities {
/// Bitset containing all living entities
alive: BitSetVec,
generation: Vec<u32>,
killed: Vec<Entity>,
next_id: usize,
/// helps to know if we should directly append after next_id or if we should look through the
/// bitset.
has_deleted: bool,
}
impl std::fmt::Debug for Entities {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Entities").finish_non_exhaustive()
}
}
impl Default for Entities {
fn default() -> Self {
Self {
alive: create_bitset(),
generation: vec![0u32; BITSET_SIZE],
killed: vec![],
next_id: 0,
has_deleted: false,
}
}
}
/// A type representing a component-joining entity query.
pub trait QueryItem {
/// The type of iterator this query item creates
type Iter: Iterator;
/// Modify the iteration bitset
fn apply_bitset(&self, bitset: &mut BitSetVec);
/// Return the item that matches the query within the given bitset if there is exactly one
/// entity that matches this query item.
fn get_single_with_bitset(
self,
bitset: Rc<BitSetVec>,
) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError>;
/// Return an iterator over the provided bitset.
fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter;
}
/// An error that may occur when querying for a single entity. For example, via
/// [`Entities::get_single_with`], or more directly with
/// [`ComponentStore::get_single_with_bitset`] or
/// [`ComponentStore::get_single_mut_with_bitset`].
#[derive(Debug, PartialEq, Eq)]
pub enum QuerySingleError {
/// No entity matches the query.
NoEntities,
/// More than one entity matches the query.
MultipleEntities,
}
/// Wrapper for the [`Comp`] [`SystemParam`] used as [`QueryItem`] to iterate
/// over entities optionally retrieving components from [`ComponentStore`].
/// Entities iterated over will not be filtered by [`OptionalQueryItem`].
///
/// See [`Optional`] helper func for constructing `OptionalQueryItem` and usage.
pub struct OptionalQueryItem<'a, T: HasSchema, S>(pub &'a S, pub PhantomData<&'a T>);
/// Wrapper for the [`CompMut`] [`SystemParam`] used as [`QueryItem`] to iterate
/// over entities optionally and mutably retrieving components from [`ComponentStore`].
/// Entities iterated over will not be filtered by [`OptionalQueryItemMut`].
///
/// See [`OptionalMut`] helper func for constructing `OptionalQueryItemMut` and usage
pub struct OptionalQueryItemMut<'a, T: HasSchema, S>(pub &'a mut S, pub PhantomData<&'a T>);
/// Helper func to construct a [`OptionalQueryItem`] wrapping a [`Comp`] [`SystemParam`].
/// Used to iterate over enities optionally retrieving components from [`ComponentStore`].
/// Entities iterated over will not be filtered by this `QueryItem`.
///
/// This example filters entities by `compC`, optionally retrieves `compA` as mutable, and
/// `compB` as immutable. ([`OptionalMut`] is used for mutation).
///
/// `entities.iter_with(&mut OptionalMut(&mut compA), &Optional(&compB), &compC)`
///
/// This will implement [`QueryItem`] as long as generic type implements [`std::ops::Deref`] for
/// [`ComponentStore`], such as [`Comp`] and [`CompMut`].
#[allow(non_snake_case)]
pub fn Optional<'a, T: HasSchema, C, S>(component_ref: &'a S) -> OptionalQueryItem<'a, T, S>
where
C: ComponentIterBitset<'a, T> + 'a,
S: std::ops::Deref<Target = C> + 'a,
{
OptionalQueryItem(component_ref, PhantomData)
}
/// Helper func to construct a [`OptionalQueryItemMut`] wrapping a [`CompMut`] [`SystemParam`].
/// Used to iterate over enities optionally and mutably retrieving components from [`ComponentStore`].
/// Entities iterated over will not be filtered by this `QueryItem`.
///
/// This example filters entities by `compC`, optionally retrieves `compA` as mutable, and
/// `compB` as immutable.
///
/// `entities.iter_with(&mut OptionalMut(&mut compA), &Optional(&compB), &compC)`
///
/// This will implement [`QueryItem`] as long as generic type implements [`std::ops::DerefMut`] for
/// [`ComponentStore`], such as [`CompMut`].
#[allow(non_snake_case)]
pub fn OptionalMut<'a, T: HasSchema, C, S>(
component_ref: &'a mut S,
) -> OptionalQueryItemMut<'a, T, S>
where
C: ComponentIterBitset<'a, T> + 'a,
S: std::ops::DerefMut<Target = C> + 'a,
{
OptionalQueryItemMut(component_ref, PhantomData)
}
impl<'a> QueryItem for &'a Ref<'a, UntypedComponentStore> {
type Iter = UntypedComponentBitsetIterator<'a>;
fn apply_bitset(&self, bitset: &mut BitSetVec) {
bitset.bit_and(self.bitset());
}
fn get_single_with_bitset(
self,
bitset: Rc<BitSetVec>,
) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError> {
UntypedComponentStore::get_single_with_bitset(self, bitset)
}
fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter {
UntypedComponentStore::iter_with_bitset(self, bitset)
}
}
impl<'a, 'q, T: HasSchema> QueryItem for &'a Comp<'q, T> {
type Iter = ComponentBitsetIterator<'a, T>;
fn apply_bitset(&self, bitset: &mut BitSetVec) {
bitset.bit_and(self.bitset());
}
fn get_single_with_bitset(
self,
bitset: Rc<BitSetVec>,
) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError> {
ComponentStore::get_single_with_bitset(&**self, bitset)
}
fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter {
ComponentStore::iter_with_bitset(&**self, bitset)
}
}
impl<'a, 'q, T: HasSchema> QueryItem for &'a CompMut<'q, T> {
type Iter = ComponentBitsetIterator<'a, T>;
fn apply_bitset(&self, bitset: &mut BitSetVec) {
bitset.bit_and(self.bitset());
}
fn get_single_with_bitset(
self,
bitset: Rc<BitSetVec>,
) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError> {
ComponentStore::get_single_with_bitset(&**self, bitset)
}
fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter {
ComponentStore::iter_with_bitset(&**self, bitset)
}
}
impl<'a, 'q, T: HasSchema> QueryItem for &'a mut CompMut<'q, T> {
type Iter = ComponentBitsetIteratorMut<'a, T>;
fn apply_bitset(&self, bitset: &mut BitSetVec) {
bitset.bit_and(self.bitset());
}
fn get_single_with_bitset(
self,
bitset: Rc<BitSetVec>,
) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError> {
ComponentStore::get_single_with_bitset_mut(self, bitset)
}
fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter {
ComponentStore::iter_mut_with_bitset(self, bitset)
}
}
/// Immutably iterate over optional component with syntax: `&Optional(&Comp<T>)` / `&Optional(&CompMut<T>)`.
/// (For mutable optional iteration we require `&mut OptionalMut(&mut CompMut<T>)`)
impl<'a, T: HasSchema, S, C> QueryItem for &'a OptionalQueryItem<'a, T, S>
where
C: ComponentIterBitset<'a, T> + 'a,
S: std::ops::Deref<Target = C> + 'a,
{
type Iter = ComponentBitsetOptionalIterator<'a, T>;
fn apply_bitset(&self, _bitset: &mut BitSetVec) {}
fn get_single_with_bitset(
self,
bitset: Rc<BitSetVec>,
) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError> {
match self.0.get_single_with_bitset(bitset) {
Ok(single) => Ok(Some(single)),
Err(QuerySingleError::NoEntities) => Ok(None),
Err(err) => Err(err),
}
}
fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter {
self.0.iter_with_bitset_optional(bitset)
}
}
/// Mutably iterate over optional component with syntax: `&mut OptionalMut(&mut RefMut<ComponentStore<T>>)`
impl<'a, T: HasSchema, S, C> QueryItem for &'a mut OptionalQueryItemMut<'a, T, S>
where
C: ComponentIterBitset<'a, T> + 'a,
S: std::ops::DerefMut<Target = C> + 'a,
{
type Iter = ComponentBitsetOptionalIteratorMut<'a, T>;
fn apply_bitset(&self, _bitset: &mut BitSetVec) {}
fn get_single_with_bitset(
self,
bitset: Rc<BitSetVec>,
) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError> {
match self.0.get_single_mut_with_bitset(bitset) {
Ok(x) => Ok(Some(x)),
Err(QuerySingleError::NoEntities) => Ok(None),
Err(err) => Err(err),
}
}
fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter {
self.0.iter_mut_with_bitset_optional(bitset)
}
}
#[doc(hidden)]
pub struct MultiQueryIter<T> {
data: T,
}
macro_rules! impl_query {
( $( $args:ident, )* ) => {
impl<
'q,
$(
$args: Iterator,
)*
>
Iterator for MultiQueryIter<($($args,)*)> {
type Item = (
$(
$args::Item,
)*
);
#[allow(non_snake_case)]
fn next(&mut self) -> Option<Self::Item> {
let (
$(
$args,
)*
) = &mut self.data;
match (
$(
$args.next(),
)*
) {
(
$(
Some($args),
)*
) => Some((
$(
$args,
)*
)),
_ => None
}
}
}
impl<
$(
$args: QueryItem,
)*
> QueryItem for (
$(
$args,
)*
) {
type Iter = MultiQueryIter< (
$(
<$args as QueryItem>::Iter,
)*
)>;
#[allow(non_snake_case)]
fn apply_bitset(&self, bitset: &mut BitSetVec) {
let (
$(
$args,
)*
) = self;
$(
$args.apply_bitset(bitset);
)*
}
#[allow(non_snake_case)]
fn get_single_with_bitset(
self,
bitset: Rc<BitSetVec>,
) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError> {
let (
$(
$args,
)*
) = self;
let mut query = MultiQueryIter {
data: (
$(
$args.iter_with_bitset(bitset.clone()),
)*
)
};
let Some(items) = query.next() else {
return Err(QuerySingleError::NoEntities);
};
match query.next() {
Some(_) => Err(QuerySingleError::MultipleEntities),
None => Ok(items),
}
}
#[allow(non_snake_case)]
fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter {
let (
$(
$args,
)*
) = self;
MultiQueryIter {
data: (
$(
$args.iter_with_bitset(bitset.clone()),
)*
),
}
}
}
};
}
macro_rules! impl_queries {
// base case
() => {};
(
$head:ident,
$(
$tail:ident,
)*
) => {
// recursive call
impl_query!($head, $( $tail, )* );
impl_queries!($( $tail, )* );
}
}
impl_queries!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,);
/// Iterator over entities returned by [`Entities::iter_with`].
pub struct EntitiesIterWith<'e, I> {
current_id: usize,
next_id: usize,
bitset: Rc<BitSetVec>,
generations: &'e Vec<u32>,
query: I,
}
impl<'a, I: Iterator> Iterator for EntitiesIterWith<'a, I> {
type Item = (Entity, I::Item);
fn next(&mut self) -> Option<Self::Item> {
while !self.bitset.bit_test(self.current_id) && self.current_id < self.next_id {
self.current_id += 1;
}
if self.current_id >= self.next_id {
return None;
}
let entity = Entity::new(self.current_id as u32, self.generations[self.current_id]);
self.current_id += 1;
self.query.next().map(|item| (entity, item))
}
}
impl Entities {
/// Get a single entity and components in the given query if there is exactly one entity
/// matching the query.
///
/// # Panics
///
/// This method panics if the number of matching entities is not *exactly one*.
pub fn single_with<Q: QueryItem>(
&self,
query: Q,
) -> (Entity, <<Q as QueryItem>::Iter as Iterator>::Item) {
self.get_single_with(query).unwrap()
}
/// Get a single entity and components in the given query if there is exactly one entity
/// matching the query.
pub fn get_single_with<Q: QueryItem>(
&self,
query: Q,
) -> Result<(Entity, <<Q as QueryItem>::Iter as Iterator>::Item), QuerySingleError> {
let mut bitset = self.bitset().clone();
query.apply_bitset(&mut bitset);
let entity = {
let mut ids = (0..self.next_id).filter(|&i| bitset.bit_test(i));
let id = ids.next().ok_or(QuerySingleError::NoEntities)?;
if ids.next().is_some() {
return Err(QuerySingleError::MultipleEntities);
}
Entity::new(id as u32, self.generation[id])
};
let bitset = Rc::new(bitset);
query
.get_single_with_bitset(bitset)
.map(|item| (entity, item))
}
/// Get the first entity in the given bitset.
///
/// # Panics
///
/// This method panics if there are no entities in the bitset.
pub fn first_with_bitset(&self, bitset: &BitSetVec) -> Entity {
self.get_first_with_bitset(bitset).unwrap()
}
/// Get the first entity in the given bitset.
pub fn get_first_with_bitset(&self, bitset: &BitSetVec) -> Option<Entity> {
self.iter_with_bitset(bitset).next()
}
/// Get the first entity and components in the given query.
///
/// # Panics
///
/// This method panics if there are no entities that match the query.
pub fn first_with<Q: QueryItem>(
&self,
query: Q,
) -> (Entity, <<Q as QueryItem>::Iter as Iterator>::Item) {
self.get_first_with(query).unwrap()
}
/// Get the first entity and components in the given query.
pub fn get_first_with<Q: QueryItem>(
&self,
query: Q,
) -> Option<(Entity, <<Q as QueryItem>::Iter as Iterator>::Item)> {
self.iter_with(query).next()
}
/// Iterates over entities using the provided bitset.
pub fn iter_with_bitset<'a>(&'a self, bitset: &'a BitSetVec) -> EntityIterator<'a> {
EntityIterator {
current_id: 0,
next_id: self.next_id,
entities: &self.alive,
generations: &self.generation,
bitset,
}
}
/// Iterate over the entities and components in the given query.
///
/// The [`QueryItem`] trait is automatically implemented for references to [`Comp`] and
/// [`CompMut`] and for tuples of up to 26 items, so you can join over your mutable or immutable
/// component borrows in your systems.
///
/// You can also pass a single component, to iterate only over the components that have alive
/// entities.
///
/// # Example
///
/// ```
/// # use bones_ecs::prelude::*;
/// # #[derive(HasSchema, Clone, Default)]
/// # #[repr(C)]
/// # struct Pos { x: f32, y: f32 };
/// # #[derive(HasSchema, Clone, Default)]
/// # #[repr(C)]
/// # struct Vel { x: f32, y: f32 };
///
/// fn my_system(entities: Res<Entities>, mut pos: CompMut<Pos>, vel: Comp<Vel>) {
/// for (entity, (pos, vel)) in entities.iter_with((&mut pos, &vel)) {
/// pos.x += vel.x;
/// pos.y += vel.y;
/// }
/// }
/// ```
///
/// You may optionally iterate over components with `&Optional(&comp)` or mutably with
/// `&mut OptionalMut(&mut comp_mut)`. Entities are not filtered by component in [`OptionalQueryItem`].
/// None is returned for these. If done with single Optional query item, all entities are iterated over.
///
/// Syntax is `&Optional(&comp)`, or `&mut OptionalMut(&mut comp)`. Reference to comp and reference to Optional
/// is required for now.
///
/// # [`Optional`] Example
///
/// ```
/// # use bones_ecs::prelude::*;
/// # #[derive(HasSchema, Clone, Default)]
/// # #[repr(C)]
/// # struct Pos { x: f32, y: f32 };
/// # #[derive(HasSchema, Clone, Default)]
/// # #[repr(C)]
/// # struct Vel { x: f32, y: f32 };
/// # #[derive(HasSchema, Clone, Default)]
/// # #[repr(C)]
/// # struct PosMax { x: f32, y: f32 }
///
/// fn my_system(entities: Res<Entities>, mut pos: CompMut<Pos>, vel: Comp<Vel>, pos_max: Comp<PosMax>) {
/// for (entity, (pos, vel, pos_max)) in entities.iter_with((&mut pos, &vel, &Optional(&pos_max))) {
/// // Update pos from vel on all entities that have pos and vel components
/// pos.x += vel.x;
/// pos.y += vel.y;
///
/// // limit pos.x by pos_max.x if entity has PosMax component
/// if let Some(pos_max) = pos_max {
/// if pos.x > pos_max.x {
/// pos.x = pos_max.x
/// }
/// }
/// }
/// }
/// ```
pub fn iter_with<Q: QueryItem>(&self, query: Q) -> EntitiesIterWith<<Q as QueryItem>::Iter> {
let mut bitset = self.bitset().clone();
query.apply_bitset(&mut bitset);
let bitset = Rc::new(bitset);
EntitiesIterWith {
current_id: 0,
next_id: self.next_id,
bitset: bitset.clone(),
generations: &self.generation,
query: query.iter_with_bitset(bitset),
}
}
/// Creates a new `Entity` and returns it.
///
/// This function will not reuse the index of an entity that is still in the killed entities.
pub fn create(&mut self) -> Entity {
if !self.has_deleted {
let i = self.next_id;
if i >= BITSET_SIZE {
panic!("Exceeded maximum amount of concurrent entities.");
}
self.next_id += 1;
self.alive.bit_set(i);
Entity::new(i as u32, self.generation[i])
} else {
// Skip over sections where all bits are enabled
let mut section = 0;
while self.alive[section].bit_all() {
section += 1;
}
// Start at the beginning of the first section with at least 1 unset bit
let mut i = section * (32 * 8);
// Find the first bit that is not used by an alive or dead entity
while i < BITSET_SIZE
&& (self.alive.bit_test(i) || self.killed.iter().any(|e| e.index() == i as u32))
{
i += 1;
}
if i >= BITSET_SIZE {
panic!("Exceeded maximum amount of concurrent entities.");
}
// Create the entity
self.alive.bit_set(i);
if i >= self.next_id {
self.next_id = i + 1;
self.has_deleted = false;
}
let entity = Entity::new(i as u32, self.generation[i]);
// Make sure we never return the invalid entity.
if unlikely(entity == Entity::INVALID) {
panic!("Ran out of entity IDs");
}
entity
}
}
/// Checks if the `Entity` is still alive.
///
/// Returns true if it is alive. Returns false if it has been killed.
pub fn is_alive(&self, entity: Entity) -> bool {
self.alive.bit_test(entity.index() as usize)
&& self.generation[entity.index() as usize] == entity.generation()
}
/// Kill an entity.
pub fn kill(&mut self, entity: Entity) {
if self.alive.bit_test(entity.index() as usize) {
self.alive.bit_reset(entity.index() as usize);
self.generation[entity.index() as usize] += 1;
self.killed.push(entity);
self.has_deleted = true;
}
}
/// Returns a list of all `Entity`s cloned into a new vec.
pub fn all_cloned(&self) -> Vec<Entity> {
self.iter().collect()
}
/// Kills all entities.
pub fn kill_all(&mut self) {
let entities: Vec<Entity> = self.all_cloned();
for entity in entities {
self.kill(entity);
}
}
/// Returns entities in the killed list.
pub fn killed(&self) -> &Vec<Entity> {
&self.killed
}
/// Clears the killed entity list.
pub fn clear_killed(&mut self) {
self.killed.clear();
}
/// Returns a bitset where each index where the bit is set to 1 indicates the index of an alive
/// entity.
///
/// Useful for joining over [`Entity`] and [`ComponentStore<T>`] at the same time.
pub fn bitset(&self) -> &BitSetVec {
&self.alive
}
/// Iterates over all alive entities.
pub fn iter(&self) -> EntityIterator {
EntityIterator {
current_id: 0,
next_id: self.next_id,
entities: self.bitset(),
generations: &self.generation,
bitset: self.bitset(),
}
}
}
/// Iterator over entities using the provided bitset.
pub struct EntityIterator<'a> {
pub(crate) current_id: usize,
pub(crate) next_id: usize,
pub(crate) entities: &'a BitSetVec,
pub(crate) generations: &'a Vec<u32>,
//pub(crate) bitset: &'a BitSetVec,
pub(crate) bitset: &'a BitSetVec,
}
impl<'a> Iterator for EntityIterator<'a> {
type Item = Entity;
fn next(&mut self) -> Option<Self::Item> {
while !(self.bitset.bit_test(self.current_id) && self.entities.bit_test(self.current_id))
&& self.current_id < self.next_id
{
self.current_id += 1;
}
let ret = if self.current_id < self.next_id {
Some(Entity::new(
self.current_id as u32,
self.generations[self.current_id],
))
} else {
None
};
self.current_id += 1;
ret
}
}
#[cfg(test)]
mod tests {
#![allow(non_snake_case)]
use std::collections::HashSet;
use crate::prelude::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq, HasSchema, Default)]
#[repr(C)]
struct A(u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, HasSchema, Default)]
#[repr(C)]
struct B(u32);
#[test]
fn entities__create_kill() {
let mut entities = Entities::default();
let e1 = entities.create();
let e2 = entities.create();
let e3 = entities.create();
assert_eq!(e1.index(), 0);
assert_eq!(e2.index(), 1);
assert_eq!(e3.index(), 2);
assert_eq!(e1.generation(), 0);
assert!(entities.is_alive(e1));
assert!(entities.is_alive(e2));
assert!(entities.is_alive(e3));
entities.kill(e1);
assert!(!entities.is_alive(e1));
assert!(entities.is_alive(e2));
assert!(entities.is_alive(e3));
let e4 = entities.create();
assert!(!entities.is_alive(e1));
assert!(entities.is_alive(e2));
assert!(entities.is_alive(e3));
assert!(entities.is_alive(e4));
assert_eq!(*entities.killed(), vec![e1]);
entities.clear_killed();
assert_eq!(*entities.killed(), vec![]);
}
#[test]
fn entities__interleaved_create_kill() {
let mut entities = Entities::default();
let e1 = entities.create();
assert_eq!(e1.index(), 0);
let e2 = entities.create();
assert_eq!(e2.index(), 1);
entities.kill(e1);
entities.kill(e2);
assert!(!entities.is_alive(e1));
assert!(!entities.is_alive(e2));
let e3 = entities.create();
assert_eq!(e3.index(), 2);
let e4 = entities.create();
assert_eq!(e4.index(), 3);
entities.kill(e3);
entities.kill(e4);
assert!(!entities.is_alive(e3));
assert!(!entities.is_alive(e4));
}
#[test]
/// Exercise basic operations on entities to increase code coverage
fn entities__clone_debug_hash() {
let mut entities = Entities::default();
let e1 = entities.create();
// Clone
#[allow(clippy::clone_on_copy)]
let _ = e1.clone();
// Debug
assert_eq!(format!("{e1:?}"), "Entity(0, 0)");
// Hash
let mut h = HashSet::new();
h.insert(e1);
}
/// Test to cover the code where an entity is allocated in the next free section.
///
/// Exercises a code path not tested according to code coverage.
#[test]
fn entities__force_generate_next_section() {
let mut entities = Entities::default();
// Create enough entities to fil up the first section of the bitset
for _ in 0..256 {
entities.create();
}
// Create another entity ( this will be the second section)
let e1 = entities.create();
// Kill the entity ( now we will have a deleted entity, but not in the first section )
entities.kill(e1);
// Create a new entity
entities.create();
}
#[test]
#[should_panic(expected = "Exceeded maximum amount")]
fn entities__force_max_entity_panic() {
let mut entities = Entities::default();
for _ in 0..(BITSET_SIZE + 1) {
entities.create();
}
}
#[test]
#[should_panic(expected = "Exceeded maximum amount")]
fn entities__force_max_entity_panic2() {
let mut entities = Entities::default();
let e = (0..BITSET_SIZE).fold(default(), |_, _| entities.create());
entities.kill(e);
entities.create();
entities.create();
}
#[test]
fn entities__iter_with_empty_bitset() {
let mut entities = Entities::default();
// Create a couple entities
entities.create();
entities.create();
// Join with an empty bitset
let bitset = BitSetVec::default();
assert_eq!(entities.iter_with_bitset(&bitset).count(), 0);
}
#[test]
fn entities__get_single__with_one_required__ok() {
let mut entities = Entities::default();
(0..3).map(|_| entities.create()).count();
let e = entities.create();
let a = A(4);
let mut store = ComponentStore::<A>::default();
store.insert(e, a);
assert_eq!(entities.get_single_with(&Ref::new(&store)), Ok((e, &a)));
}
#[test]
fn entities__get_single__with_one_required__none() {
let mut entities = Entities::default();
let store = ComponentStore::<A>::default();
(0..3).map(|_| entities.create()).count();
assert_eq!(
entities.get_single_with(&Ref::new(&store)),
Err(QuerySingleError::NoEntities)
);
}
#[test]
fn entities__get_single__with_one_required__too_many() {
let mut entities = Entities::default();
let mut store = ComponentStore::<A>::default();
for i in 0..3 {
store.insert(entities.create(), A(i));
}
assert_eq!(
entities.get_single_with(&Ref::new(&store)),
Err(QuerySingleError::MultipleEntities)
);
}
#[test]
fn entities__get_single__with_multiple_required() {
let mut entities = Entities::default();
let mut store_a = ComponentStore::<A>::default();
let mut store_b = ComponentStore::<B>::default();
let _e1 = entities.create();
let e2 = entities.create();
store_a.insert(e2, A(2));
let e3 = entities.create();
store_b.insert(e3, B(3));
let e4 = entities.create();
let a4 = A(4);
let b4 = B(4);
store_a.insert(e4, a4);
store_b.insert(e4, b4);
assert_eq!(
entities.get_single_with((&Ref::new(&store_a), &Ref::new(&store_b))),
Ok((e4, (&a4, &b4)))
);
}
#[test]
fn entities__get_single__with_one_optional() {
let mut entities = Entities::default();
let mut store = ComponentStore::<A>::default();
{
let e = entities.create();
assert_eq!(
entities.get_single_with(&Optional(&Ref::new(&store))),
Ok((e, None))
);
assert_eq!(
entities.get_single_with(&mut OptionalMut(&mut RefMut::new(&mut store))),
Ok((e, None))
);
entities.kill(e);
}
{
let e = entities.create();
let mut a = A(1);
store.insert(e, a);
assert_eq!(
entities.get_single_with(&Optional(&Ref::new(&store))),
Ok((e, Some(&a)))
);
assert_eq!(
entities.get_single_with(&mut OptionalMut(&mut RefMut::new(&mut store))),
Ok((e, Some(&mut a)))
);
entities.kill(e);
}
}
#[test]
fn entities__get_single__with_required_and_optional() {
let mut entities = Entities::default();
let mut store_a = ComponentStore::<A>::default();
let mut store_b = ComponentStore::<B>::default();
{
let e = entities.create();
let a = A(1);
store_a.insert(e, a);
assert_eq!(
entities.get_single_with((&Ref::new(&store_a), &Optional(&Ref::new(&store_b)))),
Ok((e, (&a, None)))
);
assert_eq!(
entities.get_single_with((
&Ref::new(&store_a),
&mut OptionalMut(&mut RefMut::new(&mut store_b))
)),
Ok((e, (&a, None)))
);
entities.kill(e);
}
{
let e = entities.create();
let a = A(1);
let mut b = B(1);
store_a.insert(e, a);
store_b.insert(e, b);
assert_eq!(
entities.get_single_with((&Ref::new(&store_a), &Optional(&Ref::new(&store_b)))),
Ok((e, (&a, Some(&b))))
);
assert_eq!(
entities.get_single_with((
&Ref::new(&store_a),
&mut OptionalMut(&mut RefMut::new(&mut store_b))
)),
Ok((e, (&a, Some(&mut b))))
);
entities.kill(e);
}
}
}