bevy_rand/
global.rs

1use core::fmt::Debug;
2
3use bevy_ecs::{
4    component::Component,
5    query::With,
6    system::{Commands, Single, SystemParam},
7};
8use bevy_prng::EntropySource;
9
10use crate::{
11    params::{RngEntity, RngEntityItem},
12    prelude::{RngEntityCommands, RngEntityCommandsExt},
13};
14
15/// A marker component to signify a global source. Warning: there should only be **one** entity per
16/// PRNG type that qualifies as the `Global` source.
17#[derive(Debug, Component)]
18pub struct GlobalRng;
19
20/// A helper [`SystemParam`] to obtain the [`GlobalRng`] entity & seed of a given `Rng`. This yields
21/// read-only access to the global entity and its seed, and also allows constructing a
22/// [`RngEntityCommands`] directly from it.
23/// ```
24/// use bevy_ecs::prelude::*;
25/// use bevy_rand::prelude::*;
26/// use bevy_prng::WyRand;
27///
28/// fn reseed_all_linked_rngs_from_global(mut global: GlobalRngEntity<WyRand>) {
29///     global.rng_commands().reseed_linked();
30/// }
31/// ```
32#[derive(SystemParam)]
33pub struct GlobalRngEntity<'w, 's, Rng: EntropySource> {
34    commands: Commands<'w, 's>,
35    data: Single<'w, 's, RngEntity<Rng>, With<GlobalRng>>,
36}
37
38impl<Rng: EntropySource> GlobalRngEntity<'_, '_, Rng> {
39    /// Creates a [`GlobalRng`]'s [`RngEntityCommands`].
40    pub fn rng_commands(&mut self) -> RngEntityCommands<'_, '_, Rng> {
41        self.commands.rng(self.data.entity())
42    }
43}
44
45impl<'w, 's, Rng: EntropySource> core::ops::Deref for GlobalRngEntity<'w, 's, Rng> {
46    type Target = RngEntityItem<'w, 's, Rng>;
47
48    fn deref(&self) -> &Self::Target {
49        &self.data
50    }
51}