Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Merged by Bors] - Add ability to inspect entity's components #5136

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion crates/bevy_ecs/src/system/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
entity::{Entities, Entity},
world::{FromWorld, World},
};
use bevy_utils::tracing::{error, warn};
use bevy_utils::tracing::{debug, error, warn};
pub use command_queue::CommandQueue;
pub use parallel_scope::*;
use std::marker::PhantomData;
Expand Down Expand Up @@ -217,6 +217,11 @@ impl<'w, 's> Commands<'w, 's> {
}
}

/// Logs the components of a given entity at the debug level.
pub fn debug_entity(&mut self, entity: Entity) {
self.queue.push(DebugEntity { entity });
}

/// Spawns entities to the [`World`] according to the given iterator (or a type that can
/// be converted to it).
///
Expand Down Expand Up @@ -793,6 +798,20 @@ impl<R: Resource> Command for RemoveResource<R> {
}
}

pub struct DebugEntity {
harudagondi marked this conversation as resolved.
Show resolved Hide resolved
harudagondi marked this conversation as resolved.
Show resolved Hide resolved
entity: Entity,
}

impl Command for DebugEntity {
fn write(self, world: &mut World) {
debug!(
"Entity {:?}: {:?}",
self.entity,
world.inspect_entity(self.entity)
);
}
}

#[cfg(test)]
#[allow(clippy::float_cmp, clippy::approx_constant)]
mod tests {
Expand Down
77 changes: 75 additions & 2 deletions crates/bevy_ecs/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ use crate::{
bundle::{Bundle, BundleInserter, BundleSpawner, Bundles},
change_detection::{MutUntyped, Ticks},
component::{
Component, ComponentDescriptor, ComponentId, ComponentTicks, Components, StorageType,
Component, ComponentDescriptor, ComponentId, ComponentInfo, ComponentTicks, Components,
StorageType,
},
entity::{AllocAtWithoutReplacement, Entities, Entity},
query::{QueryState, WorldQuery},
Expand Down Expand Up @@ -280,6 +281,16 @@ impl World {
.unwrap_or_else(|| panic!("Entity {:?} does not exist", entity))
}

/// Returns the components of an [`Entity`](crate::entity::Entity) through [`ComponentInfo`](crate::component::ComponentInfo).
#[inline]
pub fn inspect_entity(&mut self, entity: Entity) -> Vec<&ComponentInfo> {
harudagondi marked this conversation as resolved.
Show resolved Hide resolved
let entity_ref = self.entity(entity);
self.components()
.iter()
.filter(|component| entity_ref.contains_id(component.id()))
.collect()
}
harudagondi marked this conversation as resolved.
Show resolved Hide resolved

/// Returns an [`EntityMut`] 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.
///
Expand Down Expand Up @@ -1542,11 +1553,13 @@ mod tests {
use super::World;
use crate::{
change_detection::DetectChanges,
component::{ComponentDescriptor, ComponentId, StorageType},
component::{ComponentDescriptor, ComponentId, ComponentInfo, StorageType},
ptr::OwningPtr,
};
use bevy_ecs_macros::Component;
use bevy_utils::HashSet;
use std::{
any::TypeId,
panic,
sync::{
atomic::{AtomicBool, AtomicU32, Ordering},
Expand Down Expand Up @@ -1762,4 +1775,64 @@ mod tests {
world.insert_resource_by_id(invalid_component_id, ptr);
});
}

#[derive(Component)]
struct Foo;

#[derive(Component)]
struct Bar;

#[derive(Component)]
struct Baz;

#[test]
fn inspect_entity_components() {
let mut world = World::new();
let ent0 = world.spawn().insert_bundle((Foo, Bar, Baz)).id();
let ent1 = world.spawn().insert_bundle((Foo, Bar)).id();
let ent2 = world.spawn().insert_bundle((Bar, Baz)).id();
let ent3 = world.spawn().insert_bundle((Foo, Baz)).id();
let ent4 = world.spawn().insert_bundle((Foo,)).id();
let ent5 = world.spawn().insert_bundle((Bar,)).id();
let ent6 = world.spawn().insert_bundle((Baz,)).id();

fn to_type_ids(component_infos: Vec<&ComponentInfo>) -> HashSet<Option<TypeId>> {
component_infos
.into_iter()
.map(|component_info| component_info.type_id())
.collect()
}

let foo_id = TypeId::of::<Foo>();
let bar_id = TypeId::of::<Bar>();
let baz_id = TypeId::of::<Baz>();
assert_eq!(
to_type_ids(world.inspect_entity(ent0)),
[Some(foo_id), Some(bar_id), Some(baz_id)].into()
);
assert_eq!(
to_type_ids(world.inspect_entity(ent1)),
[Some(foo_id), Some(bar_id)].into()
);
assert_eq!(
to_type_ids(world.inspect_entity(ent2)),
[Some(bar_id), Some(baz_id)].into()
);
assert_eq!(
to_type_ids(world.inspect_entity(ent3)),
[Some(foo_id), Some(baz_id)].into()
);
assert_eq!(
to_type_ids(world.inspect_entity(ent4)),
[Some(foo_id)].into()
);
assert_eq!(
to_type_ids(world.inspect_entity(ent5)),
[Some(bar_id)].into()
);
assert_eq!(
to_type_ids(world.inspect_entity(ent6)),
[Some(baz_id)].into()
);
}
}