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
pub(crate) mod impls;
mod inspectable_registry;
mod plugin;
use bevy::{ecs::archetype::Archetype, render::camera::Camera, ui::FocusPolicy, window::WindowId};
pub use inspectable_registry::InspectableRegistry;
pub use plugin::WorldInspectorPlugin;
use bevy::{
ecs::{
component::{ComponentId, ComponentTicks, StorageType},
entity::EntityLocation,
query::{FilterFetch, WorldQuery},
world::EntityRef,
},
prelude::*,
reflect::{TypeRegistryArc, TypeRegistryInternal},
utils::HashSet,
};
use bevy_egui::egui::{self, Color32};
use egui::CollapsingHeader;
use pretty_type_name::pretty_type_name_str;
use std::{any::TypeId, borrow::Cow, cell::Cell};
use crate::{utils::ui::label_button, Context};
use impls::EntityAttributes;
use inspectable_registry::InspectCallback;
#[derive(Debug, Clone)]
pub struct WorldInspectorParams {
pub ignore_components: HashSet<TypeId>,
pub read_only_components: HashSet<TypeId>,
pub sort_components: bool,
pub enabled: bool,
pub despawnable_entities: bool,
pub window: WindowId,
pub name_filter: Option<String>,
pub highlight_changes: bool,
}
impl WorldInspectorParams {
fn empty() -> Self {
WorldInspectorParams {
ignore_components: HashSet::default(),
read_only_components: HashSet::default(),
sort_components: false,
enabled: true,
despawnable_entities: false,
window: WindowId::primary(),
name_filter: Some(String::new()),
highlight_changes: false,
}
}
pub fn ignore_component<T: 'static>(&mut self) {
self.ignore_components.insert(TypeId::of::<T>());
}
pub fn filter_by_name<S: Into<String>>(&mut self, filter: S) {
self.name_filter = Some(filter.into());
}
fn should_ignore_component(&self, type_id: TypeId) -> bool {
self.ignore_components.contains(&type_id)
}
fn is_read_only(&self, type_id: TypeId) -> bool {
self.read_only_components.contains(&type_id)
}
fn entity_options(&self) -> EntityAttributes {
EntityAttributes {
despawnable: self.despawnable_entities,
}
}
}
impl Default for WorldInspectorParams {
fn default() -> Self {
let mut params = WorldInspectorParams::empty();
params.ignore_components = [
TypeId::of::<Name>(),
TypeId::of::<Children>(),
TypeId::of::<Parent>(),
TypeId::of::<PreviousParent>(),
]
.iter()
.copied()
.collect();
params.read_only_components = [TypeId::of::<GlobalTransform>()].iter().copied().collect();
#[cfg(feature = "rapier")]
{
params
.ignore_components
.insert(TypeId::of::<bevy_rapier3d::prelude::RigidBodyIds>());
params
.ignore_components
.insert(TypeId::of::<bevy_rapier3d::prelude::ColliderBroadPhaseData>());
}
#[cfg(feature = "rapier2d")]
{
params
.ignore_components
.insert(TypeId::of::<bevy_rapier2d::prelude::RigidBodyIds>());
params
.ignore_components
.insert(TypeId::of::<bevy_rapier2d::prelude::ColliderBroadPhaseData>());
}
params
}
}
pub struct WorldUIContext<'a> {
world: &'a mut World,
ui_ctx: Option<&'a egui::CtxRef>,
delete_entity: Cell<Option<Entity>>,
}
impl Drop for WorldUIContext<'_> {
fn drop(&mut self) {
if let Some(entity) = self.delete_entity.get() {
despawn_with_children_recursive(self.world, entity);
}
}
}
impl<'a> WorldUIContext<'a> {
pub fn new(world: &'a mut World, ui_ctx: Option<&'a egui::CtxRef>) -> WorldUIContext<'a> {
WorldUIContext {
world,
ui_ctx,
delete_entity: Cell::new(None),
}
}
pub fn world_ui<F>(&mut self, ui: &mut egui::Ui, params: &mut WorldInspectorParams) -> bool
where
F: WorldQuery,
F::Fetch: FilterFetch,
{
let mut root_entities = self.world.query_filtered::<Entity, (Without<Parent>, F)>();
let dummy_id = egui::Id::new(42);
let entity_options = params.entity_options();
let mut changed = false;
if let Some(filter) = params.name_filter.as_mut() {
ui.horizontal(|ui| {
ui.label("Named");
ui.text_edit_singleline(filter);
});
}
let entites = root_entities.iter(self.world).collect::<Vec<_>>();
for entity in entites {
changed |= self.entity_ui(ui, entity, params, dummy_id.with(entity), &entity_options);
}
changed
}
pub fn entity_ui(
&mut self,
ui: &mut egui::Ui,
entity: Entity,
params: &WorldInspectorParams,
id: egui::Id,
entity_options: &EntityAttributes,
) -> bool {
let entity_name = self.entity_name(entity);
let show_entity = params
.name_filter
.as_ref()
.map(|filter| {
filter.is_empty() || entity_name.to_lowercase().contains(&filter.to_lowercase())
})
.unwrap_or(true);
if show_entity {
CollapsingHeader::new(self.entity_name(entity).to_string())
.id_source(id.with(entity))
.show(ui, |ui| {
self.entity_ui_inner(ui, entity, params, id, entity_options)
})
.body_returned
.unwrap_or(false)
} else {
let children = self.world.get::<Children>(entity).cloned();
if let Some(children) = children {
for &child in children.iter() {
self.entity_ui(ui, child, params, id.with(child), entity_options);
}
}
false
}
}
pub fn entity_ui_inner(
&mut self,
ui: &mut egui::Ui,
entity: Entity,
params: &WorldInspectorParams,
id: egui::Id,
entity_options: &EntityAttributes,
) -> bool {
let mut changed = false;
changed |= self.component_kind_ui(
ui,
|archetype| archetype.table_components(),
"Components",
entity,
params,
id,
);
changed |= self.component_kind_ui(
ui,
|archetype| archetype.sparse_set_components(),
"Components (Sparse)",
entity,
params,
id,
);
ui.separator();
let children = self.world.get::<Children>(entity).cloned();
if let Some(children) = children {
ui.label("Children");
for &child in children.iter() {
self.entity_ui(ui, child, params, id.with(child), entity_options);
}
} else {
ui.label("No children");
}
if entity_options.despawnable {
if label_button(ui, "✖ Despawn", Color32::RED) {
self.delete_entity.set(Some(entity));
changed = true;
}
}
changed
}
fn component_kind_ui(
&mut self,
ui: &mut egui::Ui,
components: impl Fn(&Archetype) -> &[ComponentId],
title: &str,
entity: Entity,
params: &WorldInspectorParams,
id: egui::Id,
) -> bool {
let (entity_location, components) = {
let entity_ref = match self.world.get_entity(entity) {
Some(entity_ref) => entity_ref,
None => {
ui.label("Entity does not exist");
return false;
}
};
let entity_location = entity_ref.location();
let archetype = entity_ref.archetype();
let components = components(archetype).to_vec();
(entity_location, components)
};
if !components.is_empty() {
ui.label(title);
let mut components: Vec<_> = components
.iter()
.map(|component_id| {
let component_info = self.world.components().get_info(*component_id).unwrap();
let name = pretty_type_name_str(component_info.name());
(
name,
component_info.id(),
component_info.type_id(),
component_info.layout().size(),
)
})
.collect();
if params.sort_components {
components.sort_by(|a, b| a.0.cmp(&b.0));
}
let mut changed = false;
for (name, component_id, component_type_id, size) in components {
let is_zst = size == 0;
changed |= unsafe {
self.component_ui(
ui,
name,
entity,
entity_location,
component_id,
component_type_id,
is_zst,
params,
id,
)
}
}
changed
} else {
false
}
}
unsafe fn component_ui(
&mut self,
ui: &mut egui::Ui,
name: String,
entity: Entity,
entity_location: EntityLocation,
component_id: ComponentId,
component_type_id: Option<TypeId>,
is_zst: bool,
params: &WorldInspectorParams,
id: egui::Id,
) -> bool {
let type_id = match component_type_id {
Some(id) => id,
None => {
ui.label("No type id");
return false;
}
};
if params.should_ignore_component(type_id) {
return false;
}
let (component_ptr, component_ticks) = {
let (ptr, ticks) =
get_component_and_ticks(self.world, component_id, entity, entity_location).unwrap();
(ptr, { &mut *ticks })
};
if params.highlight_changes
&& component_ticks
.is_changed(self.world.last_change_tick(), self.world.read_change_tick())
{
ui.style_mut().visuals.collapsing_header_frame = true;
ui.style_mut().visuals.widgets.inactive.bg_stroke = egui::Stroke {
width: 1.0,
color: egui::Color32::GOLD,
};
ui.style_mut().visuals.widgets.active.bg_stroke = egui::Stroke {
width: 1.0,
color: egui::Color32::GOLD,
};
ui.style_mut().visuals.widgets.hovered.bg_stroke = egui::Stroke {
width: 1.0,
color: egui::Color32::GOLD,
};
ui.style_mut().visuals.widgets.noninteractive.bg_stroke = egui::Stroke {
width: 1.0,
color: egui::Color32::GOLD,
};
}
let id = id.with(component_id);
let changed = CollapsingHeader::new(name)
.id_source(id)
.show(ui, |ui| {
ui.reset_style();
if params.is_read_only(type_id) {
ui.set_enabled(false);
}
let result = self.world
.resource_scope(|world, inspectable_registry: Mut<InspectableRegistry>| {
world.resource_scope(|world, type_registry: Mut<TypeRegistryArc>| {
let type_registry = &*type_registry.internal.read();
try_display(
world,
entity,
component_ptr,
is_zst,
type_id,
&*inspectable_registry,
type_registry,
ui,
self.ui_ctx,
id,
)
})
});
if result.is_err() {
ui.label("This component is neither `Reflect` nor `Inspectable`.\nMake sure to also call `app.register_type` or `app.register_inspectable`.");
}
result.unwrap_or(false)
})
.body_returned
.unwrap_or(false);
if changed {
component_ticks.set_changed(self.world.change_tick());
}
ui.reset_style();
changed
}
fn entity_name(&self, entity: Entity) -> Cow<'_, str> {
match self.world.get_entity(entity) {
Some(entity) => guess_entity_name(entity),
None => format!("Entity {} (inexistent)", entity.id()).into(),
}
}
}
pub(crate) unsafe fn try_display(
world: &mut World,
entity: Entity,
component_ptr: *mut u8,
is_zst: bool,
type_id: TypeId,
inspectable_registry: &InspectableRegistry,
type_registry: &TypeRegistryInternal,
ui: &mut egui::Ui,
ui_ctx: Option<&egui::CtxRef>,
id: egui::Id,
) -> Result<bool, ()> {
if let Some(inspect_callback) = inspectable_registry.impls.get(&type_id) {
let id = id_to_u64(&id);
let mut context = Context::new_world_access(ui_ctx, world);
let mut context = context.with_id(id);
let changed =
display_by_inspectable_registry(inspect_callback, component_ptr, ui, &mut context);
return Ok(changed);
}
if is_zst {
return Ok(false);
}
if let Ok(changed) =
display_by_reflection(type_registry, type_id, world, entity, ui, ui_ctx, id)
{
return Ok(changed);
}
Err(())
}
unsafe fn display_by_inspectable_registry(
inspect_callback: &InspectCallback,
component_ptr: *mut u8,
ui: &mut egui::Ui,
context: &mut Context,
) -> bool {
inspect_callback(component_ptr, ui, context)
}
fn display_by_reflection(
type_registry: &TypeRegistryInternal,
type_id: TypeId,
world: &mut World,
entity: Entity,
ui: &mut egui::Ui,
ui_ctx: Option<&egui::CtxRef>,
id: egui::Id,
) -> Result<bool, ()> {
let registration = type_registry.get(type_id).ok_or(())?;
let reflect_component = match registration.data::<ReflectComponent>() {
Some(reflect_component) => reflect_component,
None => {
ui.label(format!(
"`{}` implements reflect, but does not have a `#[reflect(Component)` attribute.",
registration.short_name(),
));
return Ok(false);
}
};
let mut reflected = {
let world = unsafe { &mut *(world as *mut _) };
reflect_component
.reflect_component_mut(world, entity)
.ok_or(())?
};
let id = id_to_u64(&id);
let mut context = Context::new_world_access(ui_ctx, world);
let mut context = context.with_id(id);
Ok(crate::reflect::ui_for_reflect(
&mut *reflected,
ui,
&mut context,
))
}
#[inline]
unsafe fn get_component_and_ticks(
world: &mut World,
component_id: ComponentId,
entity: Entity,
location: EntityLocation,
) -> Option<(*mut u8, *mut ComponentTicks)> {
let archetype = &world.archetypes()[location.archetype_id];
let component_info = world.components().get_info_unchecked(component_id);
match component_info.storage_type() {
StorageType::Table => {
let table = &world.storages().tables[archetype.table_id()];
let components = table.get_column(component_id)?;
let table_row = archetype.entity_table_row(location.index);
Some((
components.get_data_unchecked(table_row),
components.get_ticks_mut_ptr_unchecked(table_row),
))
}
StorageType::SparseSet => world
.storages()
.sparse_sets
.get(component_id)
.and_then(|sparse_set| sparse_set.get_with_ticks(entity)),
}
}
macro_rules! is_bundle {
($entity:ident: $($ty:ty),* $(,)?) => {
$( $entity.contains::<$ty>() && )* true
};
}
fn guess_entity_name(entity: EntityRef) -> Cow<'_, str> {
if let Some(name) = entity.get::<Name>() {
return name.as_str().into();
}
if let Some(camera) = entity.get::<Camera>() {
match &camera.name {
Some(name) => return name.as_str().into(),
None => return "Camera".into(),
}
}
if is_bundle!(entity: PointLight, Transform, GlobalTransform) {
return format!("Light ({:?})", entity.id().id()).into();
}
if is_bundle!(entity: DirectionalLight, Transform, GlobalTransform) {
return format!("Directional Light ({:?})", entity.id().id()).into();
}
if is_bundle!(
entity: Handle<Mesh>,
Handle<StandardMaterial>,
Transform,
GlobalTransform
) {
return format!("Pbr Mesh ({:?})", entity.id().id()).into();
}
if is_bundle!(
entity: Node,
Style,
Text,
CalculatedSize,
FocusPolicy,
Transform,
GlobalTransform
) {
return format!("Entity {:?} (Text)", entity.id().id()).into();
}
if is_bundle!(
entity: Text,
Transform,
GlobalTransform,
bevy::text::Text2dSize
) {
return format!("Entity {:?} (Text2d)", entity.id().id()).into();
}
if is_bundle!(
entity: Node,
Style,
UiColor,
UiImage,
Transform,
GlobalTransform
) {
return format!("Entity {:?} (Node)", entity.id().id()).into();
}
format!("Entity {:?}", entity.id()).into()
}
fn id_to_u64(id: &egui::Id) -> u64 {
use std::collections::hash_map::DefaultHasher;
use std::hash::Hash;
use std::hash::Hasher;
let mut hasher = DefaultHasher::default();
id.hash(&mut hasher);
hasher.finish()
}