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# ๐ฅ Moonshine Spawn
[](https://crates.io/crates/moonshine-spawn)
[](https://crates.io/crates/moonshine-spawn)
[](https://docs.rs/moonshine-spawn)
[](https://github.com/Zeenobit/moonshine_spawn/blob/main/LICENSE)
[](https://github.com/Zeenobit/moonshine_spawn)
Collection of tools for spawning entities in [Bevy](https://bevyengine.org/).
## โ ๏ธ Deprecated
This crate is deprecated in favor of the upcoming [BSN](https://github.com/bevyengine/bevy/discussions/14437) changes to Bevy.
In the meantime, prefer to use [i-can't-believe-its-not-bsn](https://github.com/Leafwing-Studios/i-cant-believe-its-not-bsn) as it is a closer implementation to BSN and will make future migration easier.
The only feature of this library that is not covered by BSN are spawn keys. Implementation of spawn keys on user code should be trivial, especially with [๐ท๏ธ Moonshine Tag](https://github.com/Zeenobit/moonshine_tag).
## Overview
In Bevy, complex hierarchies of entities are typically spawned using the [`ChildBuilder`](https://docs.rs/bevy/latest/bevy/prelude/struct.ChildBuilder.html):
```rust
use bevy::prelude::*;
fn spawn_chicken(commands: &mut Commands) -> Entity {
// Spawn logic is spread between this function and the bundle
commands.spawn(ChickenBundle { /* Components */ }).with_children(|chicken| {
// Children
})
.id()
}
#[derive(Bundle)]
struct ChickenBundle {
// ...
}
```
While this pattern works for most cases, it tends to spread out the logic of entity spawning between the bundle and the function which builds the entity hierarchy. Arguably, this makes the code less modular and harder to read and maintain.
Additionally, there is no built-in functionality to reference a predefined entity hierarchy (i.e. a "prefab").
This crate aims to solve some of these issues by providing tools to make spawning more ergonomic:
```rust
use bevy::prelude::*;
use moonshine_spawn::prelude::*;
let mut app = App::new();
// Make sure `SpawnPlugin` is added to your `App`:
app.add_plugins((DefaultPlugins, SpawnPlugin));
// Register spawnables during initialization:
let chicken_key: SpawnKey = app.add_spawnable("chicken", Chicken);
// Spawn a spawnable with a key:
let chicken = app.world_mut().spawn_key(chicken_key); // .spawn_key("chicken") also works!
#[derive(Component)]
struct Chicken;
impl Spawn for Chicken {
type Output = (Chicken, SpawnChildren);
// Spawn logic is now unified:
fn spawn(&self, world: &World, entity: Entity) -> Self::Output {
// Components
(Chicken,
spawn_children(|chicken| {
// Children
}))
}
}
```
## Usage
### Spawnables
A type is a "spawnable" if it implements either [`Spawn`] or [`SpawnOnce`]:
```rust,ignore
trait Spawn {
type Output;
fn spawn(&self, world: &World, entity: Entity) -> Self::Output;
}
trait SpawnOnce {
type Output;
fn spawn_once(self, world: &World, entity: Entity) -> Self::Output;
}
```
`SpawnOnce` is implemented by default for all Bevy bundles.
`Spawn` is implemented for all types which implement `SpawnOnce + Clone`. This means any `Bundle + Clone` implements `Spawn`.
The output of a spawn is always a bundle which is then inserted into the given `entity` at the end of spawn process.
You may use these traits to define functional spawnables:
```rust
use bevy::prelude::*;
use moonshine_spawn::prelude::*;
#[derive(Resource)]
struct DefaultChickenName(Name);
struct Egg;
impl SpawnOnce for Egg {
type Output = ChickenBundle;
fn spawn_once(self, world: &World, entity: Entity) -> Self::Output {
let DefaultChickenName(name) = world.resource::<DefaultChickenName>();
ChickenBundle::new(name.clone())
}
}
#[derive(Bundle)]
struct ChickenBundle {
chicken: Chicken,
name: Name,
}
impl ChickenBundle {
fn new(name: Name) -> Self {
Self {
chicken: Chicken,
name,
}
}
}
#[derive(Component)]
struct Chicken;
fn open_egg(egg: Egg, commands: &mut Commands) -> Entity {
commands.spawn_once_with(egg).id()
}
```
### Bundles + Children
To spawn bundles with children, use the `WithChildren` trait:
```rust
use bevy::prelude::*;
use moonshine_spawn::prelude::*;
#[derive(Component)]
struct Chicken;
fn chicken() -> impl SpawnOnce {
Chicken.with_children(|chicken| {
// ...
})
}
```
Or use the `SpawnChildren` component and the `spawn_children` function:
```rust
use bevy::prelude::*;
use moonshine_spawn::prelude::*;
#[derive(Bundle)]
struct ChickenBundle {
chicken: Chicken,
children: SpawnChildren,
}
#[derive(Component)]
struct Chicken;
fn chicken() -> impl SpawnOnce {
ChickenBundle {
chicken: Chicken,
children: spawn_children(|chicken| {
// ...
})
}
}
```
### Spawn Keys
A [`SpawnKey`] is a reference to a registered spawnable.
Each key must be unique within the scope of a [`World`] and is registered using the [`AddSpawnable`] extension trait.
Use this to register your spawnables during app initialization:
```rust,ignore
app.add_spawnable("chicken", chicken());
```
You can then spawn a spawnable using a spawn key at runtime, either using `Commands` or a `&mut World`:
```rust,ignore
commands.spawn_with_key("chicken");
```
You may also use spawn keys when spawning children of a bundle:
```rust,ignore
fn chicken() -> impl SpawnOnce {
ChickenBundle {
chicken: Chicken,
children: spawn_children(|chicken| {
chicken.spawn_with_key("chicken_head");
})
}
}
```
### `force_spawn_children`
This crate works by running a system which invokes any [`SpawnChildren`] [`Component`] during the [`First`] schedule.
Sometimes it may be necessary to spawn children manually before the [`First`] schedule runs due to system dependencies.
In such cases, you may use `force_spawn_children` to manually invoke these components:
```rust
use bevy::prelude::*;
use moonshine_spawn::{prelude::*, force_spawn_children};
let mut app = App::new();
// This system spawns a chicken during setup:
fn spawn_chicken(mut commands: Commands) {
commands.spawn_once_with(chicken());
}
// This system depends on children of `Chicken`:
fn update_chicken_head(query: Query<(Entity, &Chicken, &Children)>, mut head: Query<&mut ChickenHead>) {
for (entity, chicken, children) in query.iter() {
if let Ok(mut head) = head.get_mut(children[0]) {
// ...
}
}
}
#[derive(Component)]
struct Chicken;
fn chicken() -> impl SpawnOnce {
Chicken.with_children(|chicken| {
chicken.spawn(ChickenHead);
})
}
#[derive(Component)]
struct ChickenHead;
let mut app = App::new();
app.add_plugins((DefaultPlugins, SpawnPlugin))
.add_systems(Startup, spawn_chicken)
// Without `force_spawn_children`, chicken head would only be updated on the second update cycle after spawn.
// With `force_spawn_children`, chicken head would be updated in the same update cycle.
.add_systems(Startup, force_spawn_children())
.add_systems(Update, update_chicken_head);
```
## Support
Please [post an issue](https://github.com/Zeenobit/moonshine_spawn/issues/new) for any bugs, questions, or suggestions.
You may also contact me on the official [Bevy Discord](https://discord.gg/bevy) server as **@Zeenobit**.
[`World`]:(https://docs.rs/bevy/latest/bevy/ecs/world/struct.World.html)
[`Component`]:(https://docs.rs/bevy/latest/bevy/ecs/component/trait.Component.html)
[`First`]:(https://docs.rs/bevy/latest/bevy/app/struct.First.html)
[`Spawn`]:(https://docs.rs/moonshine-spawn/latest/moonshine_spawn/trait.Spawn.html)
[`SpawnOnce`]:(https://docs.rs/moonshine-spawn/latest/moonshine_spawn/trait.SpawnOnce.html)
[`SpawnKey`]:(https://docs.rs/moonshine-spawn/latest/moonshine_spawn/struct.SpawnKey.html)
[`AddSpawnable`]:(https://docs.rs/moonshine-spawn/latest/moonshine_spawn/trait.AddSpawnable.html)
[`SpawnChildren`]:(https://docs.rs/moonshine-spawn/latest/moonshine_spawn/struct.SpawnChildren.html)