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
use crate::components::{Children, Parent};
use bevy_ecs::{
entity::Entity,
system::{Command, EntityCommands},
world::{EntityMut, World},
};
use bevy_utils::tracing::debug;
#[derive(Debug)]
pub struct DespawnRecursive {
pub entity: Entity,
}
#[derive(Debug)]
pub struct DespawnChildrenRecursive {
pub entity: Entity,
}
pub fn despawn_with_children_recursive(world: &mut World, entity: Entity) {
if let Some(parent) = world.get::<Parent>(entity).map(|parent| parent.0) {
if let Some(mut children) = world.get_mut::<Children>(parent) {
children.0.retain(|c| *c != entity);
}
}
despawn_with_children_recursive_inner(world, entity);
}
fn despawn_with_children_recursive_inner(world: &mut World, entity: Entity) {
if let Some(mut children) = world.get_mut::<Children>(entity) {
for e in std::mem::take(&mut children.0) {
despawn_with_children_recursive_inner(world, e);
}
}
if !world.despawn(entity) {
debug!("Failed to despawn entity {:?}", entity);
}
}
fn despawn_children(world: &mut World, entity: Entity) {
if let Some(mut children) = world.get_mut::<Children>(entity) {
for e in std::mem::take(&mut children.0) {
despawn_with_children_recursive_inner(world, e);
}
}
}
impl Command for DespawnRecursive {
fn write(self, world: &mut World) {
#[cfg(feature = "trace")]
let _span = bevy_utils::tracing::info_span!(
"command",
name = "DespawnRecursive",
entity = bevy_utils::tracing::field::debug(self.entity)
)
.entered();
despawn_with_children_recursive(world, self.entity);
}
}
impl Command for DespawnChildrenRecursive {
fn write(self, world: &mut World) {
#[cfg(feature = "trace")]
let _span = bevy_utils::tracing::info_span!(
"command",
name = "DespawnChildrenRecursive",
entity = bevy_utils::tracing::field::debug(self.entity)
)
.entered();
despawn_children(world, self.entity);
}
}
pub trait DespawnRecursiveExt {
fn despawn_recursive(self);
fn despawn_descendants(&mut self);
}
impl<'w, 's, 'a> DespawnRecursiveExt for EntityCommands<'w, 's, 'a> {
fn despawn_recursive(mut self) {
let entity = self.id();
self.commands().add(DespawnRecursive { entity });
}
fn despawn_descendants(&mut self) {
let entity = self.id();
self.commands().add(DespawnChildrenRecursive { entity });
}
}
impl<'w> DespawnRecursiveExt for EntityMut<'w> {
fn despawn_recursive(self) {
let entity = self.id();
#[cfg(feature = "trace")]
let _span = bevy_utils::tracing::info_span!(
"despawn_recursive",
entity = bevy_utils::tracing::field::debug(entity)
)
.entered();
despawn_with_children_recursive(self.into_world_mut(), entity);
}
fn despawn_descendants(&mut self) {
let entity = self.id();
#[cfg(feature = "trace")]
let _span = bevy_utils::tracing::info_span!(
"despawn_descendants",
entity = bevy_utils::tracing::field::debug(entity)
)
.entered();
unsafe {
despawn_children(self.world_mut(), entity);
self.update_location();
}
}
}
#[cfg(test)]
mod tests {
use bevy_ecs::{
component::Component,
system::{CommandQueue, Commands},
world::World,
};
use super::DespawnRecursiveExt;
use crate::{child_builder::BuildChildren, components::Children};
#[derive(Component, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Debug)]
struct Idx(u32);
#[derive(Component, Clone, PartialEq, Eq, Ord, PartialOrd, Debug)]
struct N(String);
#[test]
fn despawn_recursive() {
let mut world = World::default();
let mut queue = CommandQueue::default();
let grandparent_entity;
{
let mut commands = Commands::new(&mut queue, &world);
commands
.spawn((N("Another parent".to_owned()), Idx(0)))
.with_children(|parent| {
parent.spawn((N("Another child".to_owned()), Idx(1)));
});
grandparent_entity = commands.spawn((N("Grandparent".to_owned()), Idx(2))).id();
commands.entity(grandparent_entity).with_children(|parent| {
parent
.spawn((N("Parent, to be deleted".to_owned()), Idx(3)))
.with_children(|parent| {
parent
.spawn((N("First Child, to be deleted".to_owned()), Idx(4)))
.with_children(|parent| {
parent.spawn((
N("First grand child, to be deleted".to_owned()),
Idx(5),
));
});
parent.spawn((N("Second child, to be deleted".to_owned()), Idx(6)));
});
});
commands.spawn((N("An innocent bystander".to_owned()), Idx(7)));
}
queue.apply(&mut world);
let parent_entity = world.get::<Children>(grandparent_entity).unwrap()[0];
{
let mut commands = Commands::new(&mut queue, &world);
commands.entity(parent_entity).despawn_recursive();
commands.entity(parent_entity).despawn_recursive();
}
queue.apply(&mut world);
let mut results = world
.query::<(&N, &Idx)>()
.iter(&world)
.map(|(a, b)| (a.clone(), *b))
.collect::<Vec<_>>();
results.sort_unstable_by_key(|(_, index)| *index);
{
let children = world.get::<Children>(grandparent_entity).unwrap();
assert!(
!children.iter().any(|&i| i == parent_entity),
"grandparent should no longer know about its child which has been removed"
);
}
assert_eq!(
results,
vec![
(N("Another parent".to_owned()), Idx(0)),
(N("Another child".to_owned()), Idx(1)),
(N("Grandparent".to_owned()), Idx(2)),
(N("An innocent bystander".to_owned()), Idx(7))
]
);
}
}