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
use core::{
marker::PhantomData,
ops::{Deref, DerefMut},
};
use bevy_ecs::{
bundle::Bundle,
entity::Entity,
relationship::RelatedSpawnerCommands,
system::{Commands, EntityCommands},
};
use bevy_prng::EntropySource;
use crate::{
observers::{RngSource, SeedFromGlobal, SeedFromSource, SeedLinked},
params::RngEntityItem,
seed::RngSeed,
traits::SeedSource,
};
/// Commands for handling RNG specific operations with regards to seeding and
/// linking.
pub struct RngEntityCommands<'w, 's, Rng: EntropySource> {
commands: Commands<'w, 's>,
source: Entity,
_rng: PhantomData<Rng>,
}
/// Extension trait for [`Commands`] for getting access to [`RngEntityCommands`].
pub trait RngEntityCommandsExt {
/// Takes an [`Entity`] and yields the [`RngEntityCommands`] for that entity.
/// ```
/// use bevy_ecs::prelude::*;
/// use bevy_prng::WyRand;
/// use bevy_rand::prelude::*;
///
/// #[derive(Component)]
/// struct Target;
///
/// fn intialise_rng_entities(mut commands: Commands, mut q_targets: Query<Entity, With<Target>>) {
/// for target in &q_targets {
/// commands.rng::<WyRand>(target).reseed_from_os_rng();
/// }
/// }
/// ```
fn rng<Rng: EntropySource>(&mut self, entity: Entity) -> RngEntityCommands<'_, '_, Rng>;
/// Creates a [`RngEntityCommands`] from a given [`RngEntityItem`].
/// ```
/// use bevy_ecs::prelude::*;
/// use bevy_rand::prelude::*;
/// use bevy_prng::WyRand;
///
/// #[derive(Component)]
/// struct Source;
///
/// fn reseed(mut commands: Commands, query: Query<RngEntity<WyRand>, With<Source>>) {
/// for entity in &query {
/// commands.rng_entity(&entity).reseed_linked();
/// }
/// }
/// ```
fn rng_entity<Rng: EntropySource>(
&mut self,
entity: &RngEntityItem<'_, '_, Rng>,
) -> RngEntityCommands<'_, '_, Rng>;
}
impl<'w, 's> RngEntityCommandsExt for Commands<'w, 's> {
fn rng<Rng: EntropySource>(&mut self, entity: Entity) -> RngEntityCommands<'_, '_, Rng> {
RngEntityCommands {
source: entity,
commands: self.reborrow(),
_rng: PhantomData,
}
}
fn rng_entity<Rng: EntropySource>(
&mut self,
entity: &RngEntityItem<'_, '_, Rng>,
) -> RngEntityCommands<'_, '_, Rng> {
self.rng(entity.entity())
}
}
impl<'w, 's, Rng: EntropySource> Deref for RngEntityCommands<'w, 's, Rng> {
type Target = Commands<'w, 's>;
fn deref(&self) -> &Self::Target {
&self.commands
}
}
impl<Rng: EntropySource> DerefMut for RngEntityCommands<'_, '_, Rng> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.commands
}
}
impl<Rng: EntropySource> RngEntityCommands<'_, '_, Rng>
where
Rng::Seed: Send + Sync + Clone,
{
/// Reseeds the current `Rng` with a provided seed value.
#[inline]
pub fn reseed(&mut self, seed: Rng::Seed) -> &mut Self {
let entity = self.source;
self.entity(entity).insert(RngSeed::<Rng>::from_seed(seed));
self
}
/// Reseeds the current `Rng` with a new seed drawn from userspace entropy sources.
///
/// # Panics
///
/// Panics if it is unable to source entropy from a user-space source.
#[inline]
#[cfg(feature = "thread_local_entropy")]
pub fn reseed_from_local_entropy(&mut self) -> &mut Self {
let entity = self.source;
self.entity(entity)
.insert(RngSeed::<Rng>::from_local_entropy());
self
}
/// Reseeds the current `Rng` with a new seed drawn from userspace entropy sources.
#[inline]
#[cfg(feature = "thread_local_entropy")]
pub fn try_reseed_from_local_entropy(&mut self) -> Result<&mut Self, std::thread::AccessError> {
let entity = self.source;
self.entity(entity)
.insert(RngSeed::<Rng>::try_from_local_entropy()?);
Ok(self)
}
/// Reseeds the current `Rng` with a new seed drawn from OS sources.
///
/// # Panics
///
/// Panics if it is unable to source entropy from an OS/Hardware source.
#[inline]
pub fn reseed_from_os_rng(&mut self) -> &mut Self {
let entity = self.source;
self.entity(entity).insert(RngSeed::<Rng>::from_os_rng());
self
}
/// Reseeds the current `Rng` with a new seed drawn from OS sources.
#[inline]
pub fn try_reseed_from_os_rng(&mut self) -> Result<&mut Self, getrandom::Error> {
let entity = self.source;
self.entity(entity)
.insert(RngSeed::<Rng>::try_from_os_rng()?);
Ok(self)
}
}
impl<Rng: EntropySource> RngEntityCommands<'_, '_, Rng> {
/// Spawns entities related to the current Source Rng, linking them so they can be seeded
/// automatically via [`Self::reseed_linked`].
/// ```
/// use bevy_ecs::prelude::*;
/// use bevy_rand::prelude::*;
/// use bevy_prng::WyRand;
///
/// #[derive(Component)]
/// struct Source;
/// #[derive(Component)]
/// struct Target;
///
/// fn setup_rng_sources(mut global: GlobalRngEntity<WyRand>) {
/// global
/// .rng_commands()
/// .with_target_rngs([(
/// Source,
/// RngLinks::<WyRand, WyRand>::spawn((
/// Spawn(Target),
/// Spawn(Target),
/// Spawn(Target),
/// Spawn(Target),
/// Spawn(Target),
/// )),
/// )])
/// .reseed_linked();
/// }
/// ```
#[inline]
pub fn with_target_rngs(
&mut self,
targets: impl IntoIterator<Item = impl Bundle>,
) -> &mut Self {
self.with_target_rngs_as::<Rng>(targets)
}
/// Spawns entities related to the current Source Rng, linking them so they can be seeded
/// automatically with the specified `Target` Rng via [`Self::reseed_linked_as`].
///
/// ```
/// use bevy_ecs::prelude::*;
/// use bevy_rand::prelude::*;
/// use bevy_prng::{ChaCha8Rng, WyRand};
///
/// #[derive(Component)]
/// struct Source;
/// #[derive(Component)]
/// struct Target;
///
/// fn setup_rng_sources(mut global: GlobalRngEntity<ChaCha8Rng>) {
/// global
/// .rng_commands()
/// .with_target_rngs_as::<WyRand>([(
/// Source,
/// RngLinks::<WyRand, WyRand>::spawn((
/// Spawn(Target),
/// Spawn(Target),
/// Spawn(Target),
/// Spawn(Target),
/// Spawn(Target),
/// )),
/// )])
/// .reseed_linked_as::<WyRand>();
/// }
/// ```
pub fn with_target_rngs_as<Target: EntropySource>(
&mut self,
targets: impl IntoIterator<Item = impl Bundle>,
) -> &mut Self {
let entity = self.source;
self.entity(entity).with_related_entities(
|related: &mut RelatedSpawnerCommands<'_, RngSource<Rng, Target>>| {
targets.into_iter().for_each(|bundle| {
related.spawn(bundle);
});
},
);
self
}
/// Links a target [`Entity`] to the current `Rng`, designating it
/// as the Source `Rng` for the Target to draw new seeds from.
#[inline]
pub fn link_target_rng(&mut self, target: Entity) -> &mut Self {
self.link_target_rng_as::<Rng>(target)
}
/// Links a [`Entity`] to the current `Rng` as the specified `Target` type,
/// designating it as the Source `Rng` for the Target to draw new seeds from.
pub fn link_target_rng_as<Target: EntropySource>(&mut self, target: Entity) -> &mut Self {
let entity = self.source;
self.entity(entity)
.add_one_related::<RngSource<Rng, Target>>(target);
self
}
/// Links a list of target [`Entity`]s to the current `Rng`, designating it
/// as the Source `Rng` for the Targets to draw new seeds from.
#[inline]
pub fn link_target_rngs(&mut self, targets: &[Entity]) -> &mut Self {
self.link_target_rngs_as::<Rng>(targets)
}
/// Links a list of target [`Entity`]s to the current `Rng` as the specified `Target` type,
/// designating it as the Source `Rng` for the Targets to draw new seeds from.
pub fn link_target_rngs_as<Target: EntropySource>(&mut self, targets: &[Entity]) -> &mut Self {
let entity = self.source;
self.entity(entity)
.add_related::<RngSource<Rng, Target>>(targets);
self
}
/// Emits an event for the current Source `Rng` to generate and push out new seeds to
/// all linked target `Rng`s.
#[inline]
pub fn reseed_linked(&mut self) -> &mut Self {
self.reseed_linked_as::<Rng>()
}
/// Emits an event for the current Source `Rng` to generate and push out new seeds to
/// all linked target `Rng`s as the specified `Target` type.
pub fn reseed_linked_as<Target: EntropySource>(&mut self) -> &mut Self {
self.commands
.trigger(SeedLinked::<Rng, Target>::new(self.source));
self
}
/// Emits an event for the current `Rng` to pull a new seed from its linked
/// Source `Rng`. This method assumes the `Source` and `Target` are the same `Rng`
/// type.
#[inline]
pub fn reseed_from_source(&mut self) -> &mut Self {
self.reseed_from_source_as::<Rng>()
}
/// Emits an event for the current `Rng` to pull a new seed from its linked
/// Source `Rng`. A `Rng` entity can have multiple linked sources, so a source
/// `Rng` must be specified explicitly if you want to pull from a `Source` that
/// isn't the same `Rng` kind as the target.
pub fn reseed_from_source_as<Source: EntropySource>(&mut self) -> &mut Self {
self.commands
.trigger(SeedFromSource::<Source, Rng>::new(self.source));
self
}
/// Emits an event for the current `Rng` to pull a new seed from the specified
/// Global `Rng`.
#[inline]
pub fn reseed_from_global(&mut self) -> &mut Self {
self.reseed_from_global_as::<Rng>()
}
/// Emits an event for the current `Rng` to pull a new seed from the specified
/// Global `Rng`.
pub fn reseed_from_global_as<Source: EntropySource>(&mut self) -> &mut Self {
self.commands
.trigger(SeedFromGlobal::<Source, Rng>::new(self.source));
self
}
/// Returns the inner [`EntityCommands`] with a smaller lifetime.
#[inline]
pub fn entity_commands(&mut self) -> EntityCommands<'_> {
let entity = self.source;
self.entity(entity)
}
/// Returns the underlying [`Commands`].
#[inline]
pub fn commands(&mut self) -> Commands<'_, '_> {
self.commands.reborrow()
}
}