-
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
child_builder.rs
474 lines (423 loc) · 15.4 KB
/
child_builder.rs
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
use crate::prelude::{Children, Parent, PreviousParent};
use bevy_ecs::{
bundle::Bundle,
entity::Entity,
system::{Command, Commands, EntityCommands},
world::{EntityMut, World},
};
use smallvec::SmallVec;
#[derive(Debug)]
pub struct InsertChildren {
parent: Entity,
children: SmallVec<[Entity; 8]>,
index: usize,
}
impl Command for InsertChildren {
fn write(self, world: &mut World) {
for child in self.children.iter() {
world
.entity_mut(*child)
// FIXME: don't erase the previous parent (see #1545)
.insert_bundle((Parent(self.parent), PreviousParent(self.parent)));
}
{
if let Some(mut children) = world.get_mut::<Children>(self.parent) {
children.0.insert_from_slice(self.index, &self.children);
} else {
world
.entity_mut(self.parent)
.insert(Children(self.children));
}
}
}
}
#[derive(Debug)]
pub struct PushChildren {
parent: Entity,
children: SmallVec<[Entity; 8]>,
}
pub struct ChildBuilder<'a, 'b> {
commands: &'b mut Commands<'a>,
push_children: PushChildren,
}
impl Command for PushChildren {
fn write(self, world: &mut World) {
for child in self.children.iter() {
world
.entity_mut(*child)
// FIXME: don't erase the previous parent (see #1545)
.insert_bundle((Parent(self.parent), PreviousParent(self.parent)));
}
{
let mut added = false;
if let Some(mut children) = world.get_mut::<Children>(self.parent) {
children.0.extend(self.children.iter().cloned());
added = true;
}
// NOTE: ideally this is just an else statement, but currently that _incorrectly_ fails
// borrow-checking
if !added {
world
.entity_mut(self.parent)
.insert(Children(self.children));
}
}
}
}
impl<'a, 'b> ChildBuilder<'a, 'b> {
pub fn spawn_bundle(&mut self, bundle: impl Bundle) -> EntityCommands<'a, '_> {
let e = self.commands.spawn_bundle(bundle);
self.push_children.children.push(e.id());
e
}
pub fn spawn(&mut self) -> EntityCommands<'a, '_> {
let e = self.commands.spawn();
self.push_children.children.push(e.id());
e
}
pub fn parent_entity(&self) -> Entity {
self.push_children.parent
}
pub fn add_command<C: Command + 'static>(&mut self, command: C) -> &mut Self {
self.commands.add(command);
self
}
}
pub trait BuildChildren {
fn with_children(&mut self, f: impl FnOnce(&mut ChildBuilder)) -> &mut Self;
fn push_children(&mut self, children: &[Entity]) -> &mut Self;
fn insert_children(&mut self, index: usize, children: &[Entity]) -> &mut Self;
}
impl<'a, 'b> BuildChildren for EntityCommands<'a, 'b> {
fn with_children(&mut self, spawn_children: impl FnOnce(&mut ChildBuilder)) -> &mut Self {
let parent = self.id();
let push_children = {
let mut builder = ChildBuilder {
commands: self.commands(),
push_children: PushChildren {
children: SmallVec::default(),
parent,
},
};
spawn_children(&mut builder);
builder.push_children
};
self.commands().add(push_children);
self
}
fn push_children(&mut self, children: &[Entity]) -> &mut Self {
let parent = self.id();
self.commands().add(PushChildren {
children: SmallVec::from(children),
parent,
});
self
}
fn insert_children(&mut self, index: usize, children: &[Entity]) -> &mut Self {
let parent = self.id();
self.commands().add(InsertChildren {
children: SmallVec::from(children),
index,
parent,
});
self
}
}
#[derive(Debug)]
pub struct WorldChildBuilder<'w> {
world: &'w mut World,
current_entity: Option<Entity>,
parent_entities: Vec<Entity>,
}
impl<'w> WorldChildBuilder<'w> {
pub fn spawn_bundle(&mut self, bundle: impl Bundle + Send + Sync + 'static) -> EntityMut<'_> {
let parent_entity = self.parent_entity();
let entity = self
.world
.spawn()
.insert_bundle(bundle)
.insert_bundle((Parent(parent_entity), PreviousParent(parent_entity)))
.id();
self.current_entity = Some(entity);
if let Some(mut parent) = self.world.get_entity_mut(parent_entity) {
if let Some(mut children) = parent.get_mut::<Children>() {
children.0.push(entity);
} else {
parent.insert(Children(smallvec::smallvec![entity]));
}
}
self.world.entity_mut(entity)
}
pub fn spawn(&mut self) -> EntityMut<'_> {
let parent_entity = self.parent_entity();
let entity = self
.world
.spawn()
.insert_bundle((Parent(parent_entity), PreviousParent(parent_entity)))
.id();
self.current_entity = Some(entity);
if let Some(mut parent) = self.world.get_entity_mut(parent_entity) {
if let Some(mut children) = parent.get_mut::<Children>() {
children.0.push(entity);
} else {
parent.insert(Children(smallvec::smallvec![entity]));
}
}
self.world.entity_mut(entity)
}
pub fn parent_entity(&self) -> Entity {
self.parent_entities
.last()
.cloned()
.expect("There should always be a parent at this point.")
}
}
pub trait BuildWorldChildren {
fn with_children(&mut self, spawn_children: impl FnOnce(&mut WorldChildBuilder)) -> &mut Self;
fn push_children(&mut self, children: &[Entity]) -> &mut Self;
fn insert_children(&mut self, index: usize, children: &[Entity]) -> &mut Self;
}
impl<'w> BuildWorldChildren for EntityMut<'w> {
fn with_children(&mut self, spawn_children: impl FnOnce(&mut WorldChildBuilder)) -> &mut Self {
{
let entity = self.id();
let mut builder = WorldChildBuilder {
current_entity: None,
parent_entities: vec![entity],
// SAFE: self.update_location() is called below. It is impossible to make EntityMut
// function calls on `self` within the scope defined here
world: unsafe { self.world_mut() },
};
spawn_children(&mut builder);
}
self.update_location();
self
}
fn push_children(&mut self, children: &[Entity]) -> &mut Self {
let parent = self.id();
{
// SAFE: parent entity is not modified
let world = unsafe { self.world_mut() };
for child in children.iter() {
world
.entity_mut(*child)
// FIXME: don't erase the previous parent (see #1545)
.insert_bundle((Parent(parent), PreviousParent(parent)));
}
}
if let Some(mut children_component) = self.get_mut::<Children>() {
children_component.0.extend(children.iter().cloned());
} else {
self.insert(Children::with(children));
}
self
}
fn insert_children(&mut self, index: usize, children: &[Entity]) -> &mut Self {
let parent = self.id();
{
// SAFE: parent entity is not modified
let world = unsafe { self.world_mut() };
for child in children.iter() {
world
.entity_mut(*child)
// FIXME: don't erase the previous parent (see #1545)
.insert_bundle((Parent(parent), PreviousParent(parent)));
}
}
if let Some(mut children_component) = self.get_mut::<Children>() {
children_component.0.insert_from_slice(index, children);
} else {
self.insert(Children::with(children));
}
self
}
}
impl<'w> BuildWorldChildren for WorldChildBuilder<'w> {
fn with_children(
&mut self,
spawn_children: impl FnOnce(&mut WorldChildBuilder<'w>),
) -> &mut Self {
let current_entity = self
.current_entity
.expect("Cannot add children without a parent. Try creating an entity first.");
self.parent_entities.push(current_entity);
self.current_entity = None;
spawn_children(self);
self.current_entity = self.parent_entities.pop();
self
}
fn push_children(&mut self, children: &[Entity]) -> &mut Self {
let parent = self
.current_entity
.expect("Cannot add children without a parent. Try creating an entity first.");
for child in children.iter() {
self.world
.entity_mut(*child)
// FIXME: don't erase the previous parent (see #1545)
.insert_bundle((Parent(parent), PreviousParent(parent)));
}
if let Some(mut children_component) = self.world.get_mut::<Children>(parent) {
children_component.0.extend(children.iter().cloned());
} else {
self.world
.entity_mut(parent)
.insert(Children::with(children));
}
self
}
fn insert_children(&mut self, index: usize, children: &[Entity]) -> &mut Self {
let parent = self
.current_entity
.expect("Cannot add children without a parent. Try creating an entity first.");
for child in children.iter() {
self.world
.entity_mut(*child)
// FIXME: don't erase the previous parent (see #1545)
.insert_bundle((Parent(parent), PreviousParent(parent)));
}
if let Some(mut children_component) = self.world.get_mut::<Children>(parent) {
children_component.0.insert_from_slice(index, children);
} else {
self.world
.entity_mut(parent)
.insert(Children::with(children));
}
self
}
}
#[cfg(test)]
mod tests {
use super::{BuildChildren, BuildWorldChildren};
use crate::prelude::{Children, Parent, PreviousParent};
use bevy_ecs::{
entity::Entity,
system::{CommandQueue, Commands},
world::World,
};
use smallvec::{smallvec, SmallVec};
#[test]
fn build_children() {
let mut world = World::default();
let mut queue = CommandQueue::default();
let mut commands = Commands::new(&mut queue, &world);
let mut children = Vec::new();
let parent = commands.spawn().insert(1).id();
commands.entity(parent).with_children(|parent| {
children.push(parent.spawn().insert(2).id());
children.push(parent.spawn().insert(3).id());
children.push(parent.spawn().insert(4).id());
});
queue.apply(&mut world);
assert_eq!(
world.get::<Children>(parent).unwrap().0.as_slice(),
children.as_slice(),
);
assert_eq!(*world.get::<Parent>(children[0]).unwrap(), Parent(parent));
assert_eq!(*world.get::<Parent>(children[1]).unwrap(), Parent(parent));
assert_eq!(
*world.get::<PreviousParent>(children[0]).unwrap(),
PreviousParent(parent)
);
assert_eq!(
*world.get::<PreviousParent>(children[1]).unwrap(),
PreviousParent(parent)
);
}
#[test]
fn push_and_insert_children_commands() {
let mut world = World::default();
let entities = world
.spawn_batch(vec![(1,), (2,), (3,), (4,), (5,)])
.collect::<Vec<Entity>>();
let mut queue = CommandQueue::default();
{
let mut commands = Commands::new(&mut queue, &world);
commands.entity(entities[0]).push_children(&entities[1..3]);
}
queue.apply(&mut world);
let parent = entities[0];
let child1 = entities[1];
let child2 = entities[2];
let child3 = entities[3];
let child4 = entities[4];
let expected_children: SmallVec<[Entity; 8]> = smallvec![child1, child2];
assert_eq!(
world.get::<Children>(parent).unwrap().0.clone(),
expected_children
);
assert_eq!(*world.get::<Parent>(child1).unwrap(), Parent(parent));
assert_eq!(*world.get::<Parent>(child2).unwrap(), Parent(parent));
assert_eq!(
*world.get::<PreviousParent>(child1).unwrap(),
PreviousParent(parent)
);
assert_eq!(
*world.get::<PreviousParent>(child2).unwrap(),
PreviousParent(parent)
);
{
let mut commands = Commands::new(&mut queue, &world);
commands.entity(parent).insert_children(1, &entities[3..]);
}
queue.apply(&mut world);
let expected_children: SmallVec<[Entity; 8]> = smallvec![child1, child3, child4, child2];
assert_eq!(
world.get::<Children>(parent).unwrap().0.clone(),
expected_children
);
assert_eq!(*world.get::<Parent>(child3).unwrap(), Parent(parent));
assert_eq!(*world.get::<Parent>(child4).unwrap(), Parent(parent));
assert_eq!(
*world.get::<PreviousParent>(child3).unwrap(),
PreviousParent(parent)
);
assert_eq!(
*world.get::<PreviousParent>(child4).unwrap(),
PreviousParent(parent)
);
}
#[test]
fn push_and_insert_children_world() {
let mut world = World::default();
let entities = world
.spawn_batch(vec![(1,), (2,), (3,), (4,), (5,)])
.collect::<Vec<Entity>>();
world.entity_mut(entities[0]).push_children(&entities[1..3]);
let parent = entities[0];
let child1 = entities[1];
let child2 = entities[2];
let child3 = entities[3];
let child4 = entities[4];
let expected_children: SmallVec<[Entity; 8]> = smallvec![child1, child2];
assert_eq!(
world.get::<Children>(parent).unwrap().0.clone(),
expected_children
);
assert_eq!(*world.get::<Parent>(child1).unwrap(), Parent(parent));
assert_eq!(*world.get::<Parent>(child2).unwrap(), Parent(parent));
assert_eq!(
*world.get::<PreviousParent>(child1).unwrap(),
PreviousParent(parent)
);
assert_eq!(
*world.get::<PreviousParent>(child2).unwrap(),
PreviousParent(parent)
);
world.entity_mut(parent).insert_children(1, &entities[3..]);
let expected_children: SmallVec<[Entity; 8]> = smallvec![child1, child3, child4, child2];
assert_eq!(
world.get::<Children>(parent).unwrap().0.clone(),
expected_children
);
assert_eq!(*world.get::<Parent>(child3).unwrap(), Parent(parent));
assert_eq!(*world.get::<Parent>(child4).unwrap(), Parent(parent));
assert_eq!(
*world.get::<PreviousParent>(child3).unwrap(),
PreviousParent(parent)
);
assert_eq!(
*world.get::<PreviousParent>(child4).unwrap(),
PreviousParent(parent)
);
}
}