Struct DeferredWorld

Source
pub struct DeferredWorld<'w> { /* private fields */ }
Expand description

A World reference that disallows structural ECS changes. This includes initializing resources, registering components or spawning entities.

Implementations§

Source§

impl<'w> DeferredWorld<'w>

Source

pub fn reborrow(&mut self) -> DeferredWorld<'_>

Reborrow self as a new instance of DeferredWorld

Source

pub fn commands(&mut self) -> Commands<'_, '_>

Creates a Commands instance that pushes to the world’s command queue

Examples found in repository?
examples/ecs/component_hooks.rs (line 130)
60fn setup(world: &mut World) {
61    // In order to register component hooks the component must:
62    // - not be currently in use by any entities in the world
63    // - not already have a hook of that kind registered
64    // This is to prevent overriding hooks defined in plugins and other crates as well as keeping things fast
65    world
66        .register_component_hooks::<MyComponent>()
67        // There are 4 component lifecycle hooks: `on_add`, `on_insert`, `on_replace` and `on_remove`
68        // A hook has 2 arguments:
69        // - a `DeferredWorld`, this allows access to resource and component data as well as `Commands`
70        // - a `HookContext`, this provides access to the following contextual information:
71        //   - the entity that triggered the hook
72        //   - the component id of the triggering component, this is mostly used for dynamic components
73        //   - the location of the code that caused the hook to trigger
74        //
75        // `on_add` will trigger when a component is inserted onto an entity without it
76        .on_add(
77            |mut world,
78             HookContext {
79                 entity,
80                 component_id,
81                 caller,
82                 ..
83             }| {
84                // You can access component data from within the hook
85                let value = world.get::<MyComponent>(entity).unwrap().0;
86                println!(
87                    "{component_id:?} added to {entity} with value {value:?}{}",
88                    caller
89                        .map(|location| format!("due to {location}"))
90                        .unwrap_or_default()
91                );
92                // Or access resources
93                world
94                    .resource_mut::<MyComponentIndex>()
95                    .insert(value, entity);
96                // Or send events
97                world.send_event(MyEvent);
98            },
99        )
100        // `on_insert` will trigger when a component is inserted onto an entity,
101        // regardless of whether or not it already had it and after `on_add` if it ran
102        .on_insert(|world, _| {
103            println!("Current Index: {:?}", world.resource::<MyComponentIndex>());
104        })
105        // `on_replace` will trigger when a component is inserted onto an entity that already had it,
106        // and runs before the value is replaced.
107        // Also triggers when a component is removed from an entity, and runs before `on_remove`
108        .on_replace(|mut world, context| {
109            let value = world.get::<MyComponent>(context.entity).unwrap().0;
110            world.resource_mut::<MyComponentIndex>().remove(&value);
111        })
112        // `on_remove` will trigger when a component is removed from an entity,
113        // since it runs before the component is removed you can still access the component data
114        .on_remove(
115            |mut world,
116             HookContext {
117                 entity,
118                 component_id,
119                 caller,
120                 ..
121             }| {
122                let value = world.get::<MyComponent>(entity).unwrap().0;
123                println!(
124                    "{component_id:?} removed from {entity} with value {value:?}{}",
125                    caller
126                        .map(|location| format!("due to {location}"))
127                        .unwrap_or_default()
128                );
129                // You can also issue commands through `.commands()`
130                world.commands().entity(entity).despawn();
131            },
132        );
133}
Source

pub fn get_mut<T>(&mut self, entity: Entity) -> Option<Mut<'_, T>>
where T: Component<Mutability = Mutable>,

Retrieves a mutable reference to the given entity’s Component of the given type. Returns None if the entity does not have a Component of the given type.

Examples found in repository?
examples/ecs/error_handling.rs (line 139)
133fn fallible_observer(
134    trigger: Trigger<Pointer<Move>>,
135    mut world: DeferredWorld,
136    mut step: Local<f32>,
137) -> Result {
138    let mut transform = world
139        .get_mut::<Transform>(trigger.target)
140        .ok_or("No transform found.")?;
141
142    *step = if transform.translation.x > 3. {
143        -0.1
144    } else if transform.translation.x < -3. || *step == 0. {
145        0.1
146    } else {
147        *step
148    };
149
150    transform.translation.x += *step;
151
152    Ok(())
153}
Source

pub fn get_entity_mut<F>( &mut self, entities: F, ) -> Result<<F as WorldEntityFetch>::DeferredMut<'_>, EntityMutableFetchError>

Returns EntityMuts that expose read and write operations for the given entities, returning Err if any of the given entities do not exist. Instead of immediately unwrapping the value returned from this function, prefer World::entity_mut.

This function supports fetching a single entity or multiple entities:

As DeferredWorld does not allow structural changes, all returned references are EntityMuts, which do not allow structural changes (i.e. adding/removing components or despawning the entity).

§Errors
§Examples

For examples, see DeferredWorld::entity_mut.

Source

pub fn entity_mut<F>( &mut self, entities: F, ) -> <F as WorldEntityFetch>::DeferredMut<'_>

Returns EntityMuts that expose read and write operations for the given entities. This will panic if any of the given entities do not exist. Use DeferredWorld::get_entity_mut if you want to check for entity existence instead of implicitly panicking.

This function supports fetching a single entity or multiple entities:

As DeferredWorld does not allow structural changes, all returned references are EntityMuts, which do not allow structural changes (i.e. adding/removing components or despawning the entity).

§Panics

If any of the given entities do not exist in the world.

§Examples
§Single Entity
#[derive(Component)]
struct Position {
  x: f32,
  y: f32,
}

let mut world: DeferredWorld = // ...

let mut entity_mut = world.entity_mut(entity);
let mut position = entity_mut.get_mut::<Position>().unwrap();
position.y = 1.0;
assert_eq!(position.x, 0.0);
§Array of Entitys
#[derive(Component)]
struct Position {
  x: f32,
  y: f32,
}

let mut world: DeferredWorld = // ...

let [mut e1_ref, mut e2_ref] = world.entity_mut([e1, e2]);
let mut e1_position = e1_ref.get_mut::<Position>().unwrap();
e1_position.x = 1.0;
assert_eq!(e1_position.x, 1.0);
let mut e2_position = e2_ref.get_mut::<Position>().unwrap();
e2_position.x = 2.0;
assert_eq!(e2_position.x, 2.0);
§Slice of Entitys
#[derive(Component)]
struct Position {
  x: f32,
  y: f32,
}

let mut world: DeferredWorld = // ...

let ids = vec![e1, e2, e3];
for mut eref in world.entity_mut(&ids[..]) {
    let mut pos = eref.get_mut::<Position>().unwrap();
    pos.y = 2.0;
    assert_eq!(pos.y, 2.0);
}
§&EntityHashSet
#[derive(Component)]
struct Position {
  x: f32,
  y: f32,
}

let mut world: DeferredWorld = // ...

let ids = EntityHashSet::from_iter([e1, e2, e3]);
for (_id, mut eref) in world.entity_mut(&ids) {
    let mut pos = eref.get_mut::<Position>().unwrap();
    pos.y = 2.0;
    assert_eq!(pos.y, 2.0);
}
Source

pub fn entities_and_commands(&mut self) -> (EntityFetcher<'_>, Commands<'_, '_>)

Simultaneously provides access to entity data and a command queue, which will be applied when the World is next flushed.

This allows using borrowed entity data to construct commands where the borrow checker would otherwise prevent it.

See World::entities_and_commands for the non-deferred version.

§Example
#[derive(Component)]
struct Targets(Vec<Entity>);
#[derive(Component)]
struct TargetedBy(Entity);

let mut world: DeferredWorld = // ...
let (entities, mut commands) = world.entities_and_commands();

let entity = entities.get(eid).unwrap();
for &target in entity.get::<Targets>().unwrap().0.iter() {
    commands.entity(target).insert(TargetedBy(eid));
}
Source

pub fn query<'s, D, F>( &mut self, state: &'s mut QueryState<D, F>, ) -> Query<'_, 's, D, F>
where D: QueryData, F: QueryFilter,

Returns Query for the given QueryState, which is used to efficiently run queries on the World by storing and reusing the QueryState.

§Panics

If state is from a different world then self

Source

pub fn resource_mut<R>(&mut self) -> Mut<'_, R>
where R: Resource,

Gets a mutable reference to the resource of the given type

§Panics

Panics if the resource does not exist. Use get_resource_mut instead if you want to handle this case.

Examples found in repository?
examples/ecs/component_hooks.rs (line 94)
60fn setup(world: &mut World) {
61    // In order to register component hooks the component must:
62    // - not be currently in use by any entities in the world
63    // - not already have a hook of that kind registered
64    // This is to prevent overriding hooks defined in plugins and other crates as well as keeping things fast
65    world
66        .register_component_hooks::<MyComponent>()
67        // There are 4 component lifecycle hooks: `on_add`, `on_insert`, `on_replace` and `on_remove`
68        // A hook has 2 arguments:
69        // - a `DeferredWorld`, this allows access to resource and component data as well as `Commands`
70        // - a `HookContext`, this provides access to the following contextual information:
71        //   - the entity that triggered the hook
72        //   - the component id of the triggering component, this is mostly used for dynamic components
73        //   - the location of the code that caused the hook to trigger
74        //
75        // `on_add` will trigger when a component is inserted onto an entity without it
76        .on_add(
77            |mut world,
78             HookContext {
79                 entity,
80                 component_id,
81                 caller,
82                 ..
83             }| {
84                // You can access component data from within the hook
85                let value = world.get::<MyComponent>(entity).unwrap().0;
86                println!(
87                    "{component_id:?} added to {entity} with value {value:?}{}",
88                    caller
89                        .map(|location| format!("due to {location}"))
90                        .unwrap_or_default()
91                );
92                // Or access resources
93                world
94                    .resource_mut::<MyComponentIndex>()
95                    .insert(value, entity);
96                // Or send events
97                world.send_event(MyEvent);
98            },
99        )
100        // `on_insert` will trigger when a component is inserted onto an entity,
101        // regardless of whether or not it already had it and after `on_add` if it ran
102        .on_insert(|world, _| {
103            println!("Current Index: {:?}", world.resource::<MyComponentIndex>());
104        })
105        // `on_replace` will trigger when a component is inserted onto an entity that already had it,
106        // and runs before the value is replaced.
107        // Also triggers when a component is removed from an entity, and runs before `on_remove`
108        .on_replace(|mut world, context| {
109            let value = world.get::<MyComponent>(context.entity).unwrap().0;
110            world.resource_mut::<MyComponentIndex>().remove(&value);
111        })
112        // `on_remove` will trigger when a component is removed from an entity,
113        // since it runs before the component is removed you can still access the component data
114        .on_remove(
115            |mut world,
116             HookContext {
117                 entity,
118                 component_id,
119                 caller,
120                 ..
121             }| {
122                let value = world.get::<MyComponent>(entity).unwrap().0;
123                println!(
124                    "{component_id:?} removed from {entity} with value {value:?}{}",
125                    caller
126                        .map(|location| format!("due to {location}"))
127                        .unwrap_or_default()
128                );
129                // You can also issue commands through `.commands()`
130                world.commands().entity(entity).despawn();
131            },
132        );
133}
Source

pub fn get_resource_mut<R>(&mut self) -> Option<Mut<'_, R>>
where R: Resource,

Gets a mutable reference to the resource of the given type if it exists

Examples found in repository?
examples/ecs/immutable_components.rs (line 82)
78fn on_insert_name(mut world: DeferredWorld<'_>, HookContext { entity, .. }: HookContext) {
79    let Some(&name) = world.entity(entity).get::<Name>() else {
80        unreachable!("OnInsert hook guarantees `Name` is available on entity")
81    };
82    let Some(mut index) = world.get_resource_mut::<NameIndex>() else {
83        return;
84    };
85
86    index.name_to_entity.insert(name, entity);
87}
88
89/// When a [`Name`] is removed or replaced, remove it from our [`NameIndex`].
90///
91/// Since all mutations to [`Name`] are captured by hooks, we know it is currently
92/// inserted in the index.
93fn on_replace_name(mut world: DeferredWorld<'_>, HookContext { entity, .. }: HookContext) {
94    let Some(&name) = world.entity(entity).get::<Name>() else {
95        unreachable!("OnReplace hook guarantees `Name` is available on entity")
96    };
97    let Some(mut index) = world.get_resource_mut::<NameIndex>() else {
98        return;
99    };
100
101    index.name_to_entity.remove(&name);
102}
Source

pub fn non_send_resource_mut<R>(&mut self) -> Mut<'_, R>
where R: 'static,

Gets a mutable reference to the non-send resource of the given type, if it exists.

§Panics

Panics if the resource does not exist. Use get_non_send_resource_mut instead if you want to handle this case.

This function will panic if it isn’t called from the same thread that the resource was inserted from.

Source

pub fn get_non_send_resource_mut<R>(&mut self) -> Option<Mut<'_, R>>
where R: 'static,

Gets a mutable reference to the non-send resource of the given type, if it exists. Otherwise returns None.

§Panics

This function will panic if it isn’t called from the same thread that the resource was inserted from.

Source

pub fn send_event<E>(&mut self, event: E) -> Option<EventId<E>>
where E: Event,

Sends an Event. This method returns the ID of the sent event, or None if the event could not be sent.

Examples found in repository?
examples/ecs/component_hooks.rs (line 97)
60fn setup(world: &mut World) {
61    // In order to register component hooks the component must:
62    // - not be currently in use by any entities in the world
63    // - not already have a hook of that kind registered
64    // This is to prevent overriding hooks defined in plugins and other crates as well as keeping things fast
65    world
66        .register_component_hooks::<MyComponent>()
67        // There are 4 component lifecycle hooks: `on_add`, `on_insert`, `on_replace` and `on_remove`
68        // A hook has 2 arguments:
69        // - a `DeferredWorld`, this allows access to resource and component data as well as `Commands`
70        // - a `HookContext`, this provides access to the following contextual information:
71        //   - the entity that triggered the hook
72        //   - the component id of the triggering component, this is mostly used for dynamic components
73        //   - the location of the code that caused the hook to trigger
74        //
75        // `on_add` will trigger when a component is inserted onto an entity without it
76        .on_add(
77            |mut world,
78             HookContext {
79                 entity,
80                 component_id,
81                 caller,
82                 ..
83             }| {
84                // You can access component data from within the hook
85                let value = world.get::<MyComponent>(entity).unwrap().0;
86                println!(
87                    "{component_id:?} added to {entity} with value {value:?}{}",
88                    caller
89                        .map(|location| format!("due to {location}"))
90                        .unwrap_or_default()
91                );
92                // Or access resources
93                world
94                    .resource_mut::<MyComponentIndex>()
95                    .insert(value, entity);
96                // Or send events
97                world.send_event(MyEvent);
98            },
99        )
100        // `on_insert` will trigger when a component is inserted onto an entity,
101        // regardless of whether or not it already had it and after `on_add` if it ran
102        .on_insert(|world, _| {
103            println!("Current Index: {:?}", world.resource::<MyComponentIndex>());
104        })
105        // `on_replace` will trigger when a component is inserted onto an entity that already had it,
106        // and runs before the value is replaced.
107        // Also triggers when a component is removed from an entity, and runs before `on_remove`
108        .on_replace(|mut world, context| {
109            let value = world.get::<MyComponent>(context.entity).unwrap().0;
110            world.resource_mut::<MyComponentIndex>().remove(&value);
111        })
112        // `on_remove` will trigger when a component is removed from an entity,
113        // since it runs before the component is removed you can still access the component data
114        .on_remove(
115            |mut world,
116             HookContext {
117                 entity,
118                 component_id,
119                 caller,
120                 ..
121             }| {
122                let value = world.get::<MyComponent>(entity).unwrap().0;
123                println!(
124                    "{component_id:?} removed from {entity} with value {value:?}{}",
125                    caller
126                        .map(|location| format!("due to {location}"))
127                        .unwrap_or_default()
128                );
129                // You can also issue commands through `.commands()`
130                world.commands().entity(entity).despawn();
131            },
132        );
133}
Source

pub fn send_event_default<E>(&mut self) -> Option<EventId<E>>
where E: Event + Default,

Sends the default value of the Event of type E. This method returns the ID of the sent event, or None if the event could not be sent.

Source

pub fn send_event_batch<E>( &mut self, events: impl IntoIterator<Item = E>, ) -> Option<SendBatchIds<E>>
where E: Event,

Sends a batch of Events from an iterator. This method returns the IDs of the sent events, or None if the event could not be sent.

Source

pub fn get_resource_mut_by_id( &mut self, component_id: ComponentId, ) -> Option<MutUntyped<'_>>

Gets a pointer to the resource with the id ComponentId if it exists. The returned pointer may be used to modify the resource, as long as the mutable borrow of the World is still valid.

You should prefer to use the typed API World::get_resource_mut where possible and only use this in cases where the actual types are not known at compile time.

Source

pub fn get_non_send_mut_by_id( &mut self, component_id: ComponentId, ) -> Option<MutUntyped<'_>>

Gets a !Send resource to the resource with the id ComponentId if it exists. The returned pointer may be used to modify the resource, as long as the mutable borrow of the World is still valid.

You should prefer to use the typed API World::get_resource_mut where possible and only use this in cases where the actual types are not known at compile time.

§Panics

This function will panic if it isn’t called from the same thread that the resource was inserted from.

Source

pub fn get_mut_by_id( &mut self, entity: Entity, component_id: ComponentId, ) -> Option<MutUntyped<'_>>

Retrieves a mutable untyped reference to the given entity’s Component of the given ComponentId. Returns None if the entity does not have a Component of the given type.

You should prefer to use the typed API World::get_mut where possible and only use this in cases where the actual types are not known at compile time.

Source

pub fn trigger(&mut self, trigger: impl Event)

Sends a “global” Trigger without any targets.

Source

pub fn trigger_targets( &mut self, trigger: impl Event, targets: impl TriggerTargets + Send + Sync + 'static, )

Sends a Trigger with the given targets.

Methods from Deref<Target = World>§

Source

pub fn get_reflect( &self, entity: Entity, type_id: TypeId, ) -> Result<&(dyn Reflect + 'static), GetComponentReflectError>

Retrieves a reference to the given entity’s Component of the given type_id using reflection.

Requires implementing Reflect for the Component (e.g., using #[derive(Reflect)) and app.register_type::<TheComponent>() to have been called1.

If you want to call this with a ComponentId, see World::components and Components::get_id to get the corresponding TypeId.

Also see the crate documentation for bevy_reflect for more information on Reflect and bevy’s reflection capabilities.

§Errors

See GetComponentReflectError for the possible errors and their descriptions.

§Example
use bevy_ecs::prelude::*;
use bevy_reflect::Reflect;
use std::any::TypeId;

// define a `Component` and derive `Reflect` for it
#[derive(Component, Reflect)]
struct MyComponent;

// create a `World` for this example
let mut world = World::new();

// Note: This is usually handled by `App::register_type()`, but this example cannot use `App`.
world.init_resource::<AppTypeRegistry>();
world.get_resource_mut::<AppTypeRegistry>().unwrap().write().register::<MyComponent>();

// spawn an entity with a `MyComponent`
let entity = world.spawn(MyComponent).id();

// retrieve a reflected reference to the entity's `MyComponent`
let comp_reflected: &dyn Reflect = world.get_reflect(entity, TypeId::of::<MyComponent>()).unwrap();

// make sure we got the expected type
assert!(comp_reflected.is::<MyComponent>());
§Note

Requires the bevy_reflect feature (included in the default features).


  1. More specifically: Requires TypeData for ReflectFromPtr to be registered for the given type_id, which is automatically handled when deriving Reflect and calling App::register_type

Source

pub fn id(&self) -> WorldId

Retrieves this World’s unique ID

Source

pub fn as_unsafe_world_cell_readonly(&self) -> UnsafeWorldCell<'_>

Creates a new UnsafeWorldCell view with only read access to everything.

Source

pub fn entities(&self) -> &Entities

Retrieves this world’s Entities collection.

Source

pub fn archetypes(&self) -> &Archetypes

Retrieves this world’s Archetypes collection.

Examples found in repository?
examples/stress_tests/many_components.rs (line 162)
79fn stress_test(num_entities: u32, num_components: u32, num_systems: u32) {
80    let mut rng = ChaCha8Rng::seed_from_u64(42);
81    let mut app = App::default();
82    let world = app.world_mut();
83
84    // register a bunch of components
85    let component_ids: Vec<ComponentId> = (1..=num_components)
86        .map(|i| {
87            world.register_component_with_descriptor(
88                // SAFETY:
89                // * We don't implement a drop function
90                // * u8 is Sync and Send
91                unsafe {
92                    ComponentDescriptor::new_with_layout(
93                        format!("Component{}", i).to_string(),
94                        StorageType::Table,
95                        Layout::new::<u8>(),
96                        None,
97                        true, // is mutable
98                        ComponentCloneBehavior::Default,
99                    )
100                },
101            )
102        })
103        .collect();
104
105    // fill the schedule with systems
106    let mut schedule = Schedule::new(Update);
107    for _ in 1..=num_systems {
108        let num_access_components = rng.gen_range(1..10);
109        let access_components: Vec<ComponentId> = component_ids
110            .choose_multiple(&mut rng, num_access_components)
111            .copied()
112            .collect();
113        let system = (QueryParamBuilder::new(|builder| {
114            for &access_component in &access_components {
115                if rand::random::<bool>() {
116                    builder.mut_id(access_component);
117                } else {
118                    builder.ref_id(access_component);
119                }
120            }
121        }),)
122            .build_state(world)
123            .build_any_system(base_system);
124        schedule.add_systems((move || access_components.clone()).pipe(system));
125    }
126
127    // spawn a bunch of entities
128    for _ in 1..=num_entities {
129        let num_components = rng.gen_range(1..10);
130        let components: Vec<ComponentId> = component_ids
131            .choose_multiple(&mut rng, num_components)
132            .copied()
133            .collect();
134
135        let mut entity = world.spawn_empty();
136        // We use `ManuallyDrop` here as we need to avoid dropping the u8's when `values` is dropped
137        // since ownership of the values is passed to the world in `insert_by_ids`.
138        // But we do want to deallocate the memory when values is dropped.
139        let mut values: Vec<ManuallyDrop<u8>> = components
140            .iter()
141            .map(|_id| ManuallyDrop::new(rng.gen_range(0..255)))
142            .collect();
143        let ptrs: Vec<OwningPtr> = values
144            .iter_mut()
145            .map(|value| {
146                // SAFETY:
147                // * We don't read/write `values` binding after this and values are `ManuallyDrop`,
148                // so we have the right to drop/move the values
149                unsafe { PtrMut::from(value).promote() }
150            })
151            .collect();
152        // SAFETY:
153        // * component_id's are from the same world
154        // * `values` was initialized above, so references are valid
155        unsafe {
156            entity.insert_by_ids(&components, ptrs.into_iter());
157        }
158    }
159
160    println!(
161        "Number of Archetype-Components: {}",
162        world.archetypes().archetype_components_len()
163    );
164
165    // overwrite Update schedule in the app
166    app.add_schedule(schedule);
167    app.add_plugins(MinimalPlugins)
168        .add_plugins(DiagnosticsPlugin)
169        .add_plugins(LogPlugin::default())
170        .add_plugins(FrameTimeDiagnosticsPlugin::default())
171        .add_plugins(LogDiagnosticsPlugin::filtered(vec![DiagnosticPath::new(
172            "fps",
173        )]));
174    app.run();
175}
Source

pub fn components(&self) -> &Components

Retrieves this world’s Components collection.

Examples found in repository?
examples/ecs/dynamic.rs (line 102)
51fn main() {
52    let mut world = World::new();
53    let mut lines = std::io::stdin().lines();
54    let mut component_names = HashMap::<String, ComponentId>::new();
55    let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
56
57    println!("{PROMPT}");
58    loop {
59        print!("\n> ");
60        let _ = std::io::stdout().flush();
61        let Some(Ok(line)) = lines.next() else {
62            return;
63        };
64
65        if line.is_empty() {
66            return;
67        };
68
69        let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
70            match &line.chars().next() {
71                Some('c') => println!("{COMPONENT_PROMPT}"),
72                Some('s') => println!("{ENTITY_PROMPT}"),
73                Some('q') => println!("{QUERY_PROMPT}"),
74                _ => println!("{PROMPT}"),
75            }
76            continue;
77        };
78
79        match &first[0..1] {
80            "c" => {
81                rest.split(',').for_each(|component| {
82                    let mut component = component.split_whitespace();
83                    let Some(name) = component.next() else {
84                        return;
85                    };
86                    let size = match component.next().map(str::parse) {
87                        Some(Ok(size)) => size,
88                        _ => 0,
89                    };
90                    // Register our new component to the world with a layout specified by it's size
91                    // SAFETY: [u64] is Send + Sync
92                    let id = world.register_component_with_descriptor(unsafe {
93                        ComponentDescriptor::new_with_layout(
94                            name.to_string(),
95                            StorageType::Table,
96                            Layout::array::<u64>(size).unwrap(),
97                            None,
98                            true,
99                            ComponentCloneBehavior::Default,
100                        )
101                    });
102                    let Some(info) = world.components().get_info(id) else {
103                        return;
104                    };
105                    component_names.insert(name.to_string(), id);
106                    component_info.insert(id, info.clone());
107                    println!("Component {} created with id: {}", name, id.index());
108                });
109            }
110            "s" => {
111                let mut to_insert_ids = Vec::new();
112                let mut to_insert_data = Vec::new();
113                rest.split(',').for_each(|component| {
114                    let mut component = component.split_whitespace();
115                    let Some(name) = component.next() else {
116                        return;
117                    };
118
119                    // Get the id for the component with the given name
120                    let Some(&id) = component_names.get(name) else {
121                        println!("Component {name} does not exist");
122                        return;
123                    };
124
125                    // Calculate the length for the array based on the layout created for this component id
126                    let info = world.components().get_info(id).unwrap();
127                    let len = info.layout().size() / size_of::<u64>();
128                    let mut values: Vec<u64> = component
129                        .take(len)
130                        .filter_map(|value| value.parse::<u64>().ok())
131                        .collect();
132                    values.resize(len, 0);
133
134                    // Collect the id and array to be inserted onto our entity
135                    to_insert_ids.push(id);
136                    to_insert_data.push(values);
137                });
138
139                let mut entity = world.spawn_empty();
140
141                // Construct an `OwningPtr` for each component in `to_insert_data`
142                let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
143
144                // SAFETY:
145                // - Component ids have been taken from the same world
146                // - Each array is created to the layout specified in the world
147                unsafe {
148                    entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
149                }
150
151                println!("Entity spawned with id: {}", entity.id());
152            }
153            "q" => {
154                let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
155                parse_query(rest, &mut builder, &component_names);
156                let mut query = builder.build();
157                query.iter_mut(&mut world).for_each(|filtered_entity| {
158                    let terms = filtered_entity
159                        .access()
160                        .try_iter_component_access()
161                        .unwrap()
162                        .map(|component_access| {
163                            let id = *component_access.index();
164                            let ptr = filtered_entity.get_by_id(id).unwrap();
165                            let info = component_info.get(&id).unwrap();
166                            let len = info.layout().size() / size_of::<u64>();
167
168                            // SAFETY:
169                            // - All components are created with layout [u64]
170                            // - len is calculated from the component descriptor
171                            let data = unsafe {
172                                std::slice::from_raw_parts_mut(
173                                    ptr.assert_unique().as_ptr().cast::<u64>(),
174                                    len,
175                                )
176                            };
177
178                            // If we have write access, increment each value once
179                            if matches!(component_access, ComponentAccessKind::Exclusive(_)) {
180                                data.iter_mut().for_each(|data| {
181                                    *data += 1;
182                                });
183                            }
184
185                            format!("{}: {:?}", info.name(), data[0..len].to_vec())
186                        })
187                        .collect::<Vec<_>>()
188                        .join(", ");
189
190                    println!("{}: {}", filtered_entity.id(), terms);
191                });
192            }
193            _ => continue,
194        }
195    }
196}
Source

pub fn components_queue(&self) -> ComponentsQueuedRegistrator<'_>

Prepares a ComponentsQueuedRegistrator for the world. NOTE: ComponentsQueuedRegistrator is easily misused. See its docs for important notes on when and how it should be used.

Source

pub fn storages(&self) -> &Storages

Retrieves this world’s Storages collection.

Source

pub fn bundles(&self) -> &Bundles

Retrieves this world’s Bundles collection.

Source

pub fn removed_components(&self) -> &RemovedComponentEvents

Retrieves this world’s RemovedComponentEvents collection

Source

pub fn get_required_components<C>(&self) -> Option<&RequiredComponents>
where C: Component,

Retrieves the required components for the given component type, if it exists.

Source

pub fn get_required_components_by_id( &self, id: ComponentId, ) -> Option<&RequiredComponents>

Retrieves the required components for the component of the given ComponentId, if it exists.

Source

pub fn component_id<T>(&self) -> Option<ComponentId>
where T: Component,

Returns the ComponentId of the given Component type T.

The returned ComponentId is specific to the World instance it was retrieved from and should not be used with another World instance.

Returns None if the Component type has not yet been initialized within the World using World::register_component.

use bevy_ecs::prelude::*;

let mut world = World::new();

#[derive(Component)]
struct ComponentA;

let component_a_id = world.register_component::<ComponentA>();

assert_eq!(component_a_id, world.component_id::<ComponentA>().unwrap())
§See also
Source

pub fn resource_id<T>(&self) -> Option<ComponentId>
where T: Resource,

Returns the ComponentId of the given Resource type T.

The returned ComponentId is specific to the World instance it was retrieved from and should not be used with another World instance.

Returns None if the Resource type has not yet been initialized within the World using World::register_resource, World::init_resource or World::insert_resource.

Source

pub fn entity<F>(&self, entities: F) -> <F as WorldEntityFetch>::Ref<'_>

Returns EntityRefs that expose read-only operations for the given entities. This will panic if any of the given entities do not exist. Use World::get_entity if you want to check for entity existence instead of implicitly panicking.

This function supports fetching a single entity or multiple entities:

§Panics

If any of the given entities do not exist in the world.

§Examples
§Single Entity
#[derive(Component)]
struct Position {
  x: f32,
  y: f32,
}

let mut world = World::new();
let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();

let position = world.entity(entity).get::<Position>().unwrap();
assert_eq!(position.x, 0.0);
§Array of Entitys
#[derive(Component)]
struct Position {
  x: f32,
  y: f32,
}

let mut world = World::new();
let e1 = world.spawn(Position { x: 0.0, y: 0.0 }).id();
let e2 = world.spawn(Position { x: 1.0, y: 1.0 }).id();

let [e1_ref, e2_ref] = world.entity([e1, e2]);
let e1_position = e1_ref.get::<Position>().unwrap();
assert_eq!(e1_position.x, 0.0);
let e2_position = e2_ref.get::<Position>().unwrap();
assert_eq!(e2_position.x, 1.0);
§Slice of Entitys
#[derive(Component)]
struct Position {
  x: f32,
  y: f32,
}

let mut world = World::new();
let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();

let ids = vec![e1, e2, e3];
for eref in world.entity(&ids[..]) {
    assert_eq!(eref.get::<Position>().unwrap().y, 1.0);
}
§EntityHashSet
#[derive(Component)]
struct Position {
  x: f32,
  y: f32,
}

let mut world = World::new();
let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();

let ids = EntityHashSet::from_iter([e1, e2, e3]);
for (_id, eref) in world.entity(&ids) {
    assert_eq!(eref.get::<Position>().unwrap().y, 1.0);
}
Examples found in repository?
examples/ecs/immutable_components.rs (line 79)
78fn on_insert_name(mut world: DeferredWorld<'_>, HookContext { entity, .. }: HookContext) {
79    let Some(&name) = world.entity(entity).get::<Name>() else {
80        unreachable!("OnInsert hook guarantees `Name` is available on entity")
81    };
82    let Some(mut index) = world.get_resource_mut::<NameIndex>() else {
83        return;
84    };
85
86    index.name_to_entity.insert(name, entity);
87}
88
89/// When a [`Name`] is removed or replaced, remove it from our [`NameIndex`].
90///
91/// Since all mutations to [`Name`] are captured by hooks, we know it is currently
92/// inserted in the index.
93fn on_replace_name(mut world: DeferredWorld<'_>, HookContext { entity, .. }: HookContext) {
94    let Some(&name) = world.entity(entity).get::<Name>() else {
95        unreachable!("OnReplace hook guarantees `Name` is available on entity")
96    };
97    let Some(mut index) = world.get_resource_mut::<NameIndex>() else {
98        return;
99    };
100
101    index.name_to_entity.remove(&name);
102}
Source

pub fn inspect_entity( &self, entity: Entity, ) -> Result<impl Iterator<Item = &ComponentInfo>, EntityDoesNotExistError>

Returns the components of an Entity through ComponentInfo.

Source

pub fn get_entity<F>( &self, entities: F, ) -> Result<<F as WorldEntityFetch>::Ref<'_>, EntityDoesNotExistError>

Returns EntityRefs that expose read-only operations for the given entities, returning Err if any of the given entities do not exist. Instead of immediately unwrapping the value returned from this function, prefer World::entity.

This function supports fetching a single entity or multiple entities:

§Errors

If any of the given entities do not exist in the world, the first Entity found to be missing will return an EntityDoesNotExistError.

§Examples

For examples, see World::entity.

Source

pub fn iter_entities(&self) -> impl Iterator<Item = EntityRef<'_>>

Returns an Entity iterator of current entities.

This is useful in contexts where you only have read-only access to the World.

Source

pub fn get<T>(&self, entity: Entity) -> Option<&T>
where T: Component,

Retrieves a reference to the given entity’s Component of the given type. Returns None if the entity does not have a Component of the given type.

use bevy_ecs::{component::Component, world::World};

#[derive(Component)]
struct Position {
  x: f32,
  y: f32,
}

let mut world = World::new();
let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
let position = world.get::<Position>(entity).unwrap();
assert_eq!(position.x, 0.0);
Examples found in repository?
examples/ecs/component_hooks.rs (line 85)
60fn setup(world: &mut World) {
61    // In order to register component hooks the component must:
62    // - not be currently in use by any entities in the world
63    // - not already have a hook of that kind registered
64    // This is to prevent overriding hooks defined in plugins and other crates as well as keeping things fast
65    world
66        .register_component_hooks::<MyComponent>()
67        // There are 4 component lifecycle hooks: `on_add`, `on_insert`, `on_replace` and `on_remove`
68        // A hook has 2 arguments:
69        // - a `DeferredWorld`, this allows access to resource and component data as well as `Commands`
70        // - a `HookContext`, this provides access to the following contextual information:
71        //   - the entity that triggered the hook
72        //   - the component id of the triggering component, this is mostly used for dynamic components
73        //   - the location of the code that caused the hook to trigger
74        //
75        // `on_add` will trigger when a component is inserted onto an entity without it
76        .on_add(
77            |mut world,
78             HookContext {
79                 entity,
80                 component_id,
81                 caller,
82                 ..
83             }| {
84                // You can access component data from within the hook
85                let value = world.get::<MyComponent>(entity).unwrap().0;
86                println!(
87                    "{component_id:?} added to {entity} with value {value:?}{}",
88                    caller
89                        .map(|location| format!("due to {location}"))
90                        .unwrap_or_default()
91                );
92                // Or access resources
93                world
94                    .resource_mut::<MyComponentIndex>()
95                    .insert(value, entity);
96                // Or send events
97                world.send_event(MyEvent);
98            },
99        )
100        // `on_insert` will trigger when a component is inserted onto an entity,
101        // regardless of whether or not it already had it and after `on_add` if it ran
102        .on_insert(|world, _| {
103            println!("Current Index: {:?}", world.resource::<MyComponentIndex>());
104        })
105        // `on_replace` will trigger when a component is inserted onto an entity that already had it,
106        // and runs before the value is replaced.
107        // Also triggers when a component is removed from an entity, and runs before `on_remove`
108        .on_replace(|mut world, context| {
109            let value = world.get::<MyComponent>(context.entity).unwrap().0;
110            world.resource_mut::<MyComponentIndex>().remove(&value);
111        })
112        // `on_remove` will trigger when a component is removed from an entity,
113        // since it runs before the component is removed you can still access the component data
114        .on_remove(
115            |mut world,
116             HookContext {
117                 entity,
118                 component_id,
119                 caller,
120                 ..
121             }| {
122                let value = world.get::<MyComponent>(entity).unwrap().0;
123                println!(
124                    "{component_id:?} removed from {entity} with value {value:?}{}",
125                    caller
126                        .map(|location| format!("due to {location}"))
127                        .unwrap_or_default()
128                );
129                // You can also issue commands through `.commands()`
130                world.commands().entity(entity).despawn();
131            },
132        );
133}
Source

pub fn try_query<D>(&self) -> Option<QueryState<D>>
where D: QueryData,

Returns QueryState for the given QueryData, which is used to efficiently run queries on the World by storing and reusing the QueryState.

use bevy_ecs::{component::Component, entity::Entity, world::World};

#[derive(Component, Debug, PartialEq)]
struct Position {
  x: f32,
  y: f32,
}

let mut world = World::new();
world.spawn_batch(vec![
    Position { x: 0.0, y: 0.0 },
    Position { x: 1.0, y: 1.0 },
]);

fn get_positions(world: &World) -> Vec<(Entity, &Position)> {
    let mut query = world.try_query::<(Entity, &Position)>().unwrap();
    query.iter(world).collect()
}

let positions = get_positions(&world);

assert_eq!(world.get::<Position>(positions[0].0).unwrap(), positions[0].1);
assert_eq!(world.get::<Position>(positions[1].0).unwrap(), positions[1].1);

Requires only an immutable world reference, but may fail if, for example, the components that make up this query have not been registered into the world.

use bevy_ecs::{component::Component, entity::Entity, world::World};

#[derive(Component)]
struct A;

let mut world = World::new();

let none_query = world.try_query::<&A>();
assert!(none_query.is_none());

world.register_component::<A>();

let some_query = world.try_query::<&A>();
assert!(some_query.is_some());
Source

pub fn try_query_filtered<D, F>(&self) -> Option<QueryState<D, F>>
where D: QueryData, F: QueryFilter,

Returns QueryState for the given filtered QueryData, which is used to efficiently run queries on the World by storing and reusing the QueryState.

use bevy_ecs::{component::Component, entity::Entity, world::World, query::With};

#[derive(Component)]
struct A;
#[derive(Component)]
struct B;

let mut world = World::new();
let e1 = world.spawn(A).id();
let e2 = world.spawn((A, B)).id();

let mut query = world.try_query_filtered::<Entity, With<B>>().unwrap();
let matching_entities = query.iter(&world).collect::<Vec<Entity>>();

assert_eq!(matching_entities, vec![e2]);

Requires only an immutable world reference, but may fail if, for example, the components that make up this query have not been registered into the world.

Source

pub fn removed<T>(&self) -> impl Iterator<Item = Entity>
where T: Component,

Returns an iterator of entities that had components of type T removed since the last call to World::clear_trackers.

Source

pub fn removed_with_id( &self, component_id: ComponentId, ) -> impl Iterator<Item = Entity>

Returns an iterator of entities that had components with the given component_id removed since the last call to World::clear_trackers.

Source

pub fn contains_resource<R>(&self) -> bool
where R: Resource,

Returns true if a resource of type R exists. Otherwise returns false.

Source

pub fn contains_resource_by_id(&self, component_id: ComponentId) -> bool

Returns true if a resource with provided component_id exists. Otherwise returns false.

Source

pub fn contains_non_send<R>(&self) -> bool
where R: 'static,

Returns true if a resource of type R exists. Otherwise returns false.

Source

pub fn contains_non_send_by_id(&self, component_id: ComponentId) -> bool

Returns true if a resource with provided component_id exists. Otherwise returns false.

Source

pub fn is_resource_added<R>(&self) -> bool
where R: Resource,

Returns true if a resource of type R exists and was added since the world’s last_change_tick. Otherwise, this returns false.

This means that:

  • When called from an exclusive system, this will check for additions since the system last ran.
  • When called elsewhere, this will check for additions since the last time that World::clear_trackers was called.
Source

pub fn is_resource_added_by_id(&self, component_id: ComponentId) -> bool

Returns true if a resource with id component_id exists and was added since the world’s last_change_tick. Otherwise, this returns false.

This means that:

  • When called from an exclusive system, this will check for additions since the system last ran.
  • When called elsewhere, this will check for additions since the last time that World::clear_trackers was called.
Source

pub fn is_resource_changed<R>(&self) -> bool
where R: Resource,

Returns true if a resource of type R exists and was modified since the world’s last_change_tick. Otherwise, this returns false.

This means that:

  • When called from an exclusive system, this will check for changes since the system last ran.
  • When called elsewhere, this will check for changes since the last time that World::clear_trackers was called.
Source

pub fn is_resource_changed_by_id(&self, component_id: ComponentId) -> bool

Returns true if a resource with id component_id exists and was modified since the world’s last_change_tick. Otherwise, this returns false.

This means that:

  • When called from an exclusive system, this will check for changes since the system last ran.
  • When called elsewhere, this will check for changes since the last time that World::clear_trackers was called.
Source

pub fn get_resource_change_ticks<R>(&self) -> Option<ComponentTicks>
where R: Resource,

Retrieves the change ticks for the given resource.

Source

pub fn get_resource_change_ticks_by_id( &self, component_id: ComponentId, ) -> Option<ComponentTicks>

Retrieves the change ticks for the given ComponentId.

You should prefer to use the typed API World::get_resource_change_ticks where possible.

Source

pub fn resource<R>(&self) -> &R
where R: Resource,

Gets a reference to the resource of the given type

§Panics

Panics if the resource does not exist. Use get_resource instead if you want to handle this case.

If you want to instead insert a value if the resource does not exist, use get_resource_or_insert_with.

Examples found in repository?
examples/3d/specular_tint.rs (line 33)
32    fn from_world(world: &mut World) -> Self {
33        let asset_server = world.resource::<AssetServer>();
34        Self {
35            noise_texture: asset_server.load("textures/AlphaNoise.png"),
36        }
37    }
More examples
Hide additional examples
examples/shader/custom_render_phase.rs (line 172)
169    fn from_world(world: &mut World) -> Self {
170        Self {
171            mesh_pipeline: MeshPipeline::from_world(world),
172            shader_handle: world.resource::<AssetServer>().load(SHADER_ASSET_PATH),
173        }
174    }
examples/scene/scene.rs (line 91)
90    fn from_world(world: &mut World) -> Self {
91        let time = world.resource::<Time>();
92        ComponentB {
93            _time_since_startup: time.elapsed(),
94            value: "Default Value".to_string(),
95        }
96    }
97}
98
99/// A simple resource that also derives `Reflect`, allowing it to be stored in scenes.
100///
101/// Just like a component, you can skip serializing fields or implement `FromWorld` if needed.
102#[derive(Resource, Reflect, Default)]
103#[reflect(Resource)]
104struct ResourceA {
105    /// This resource tracks a `score` value.
106    pub score: u32,
107}
108
109/// # Scene File Paths
110///
111/// `SCENE_FILE_PATH` points to the original scene file that we'll be loading.
112/// `NEW_SCENE_FILE_PATH` points to the new scene file that we'll be creating
113/// (and demonstrating how to serialize to disk).
114///
115/// The initial scene file will be loaded below and not change when the scene is saved.
116const SCENE_FILE_PATH: &str = "scenes/load_scene_example.scn.ron";
117
118/// The new, updated scene data will be saved here so that you can see the changes.
119const NEW_SCENE_FILE_PATH: &str = "scenes/load_scene_example-new.scn.ron";
120
121/// Loads a scene from an asset file and spawns it in the current world.
122///
123/// Spawning a `DynamicSceneRoot` creates a new parent entity, which then spawns new
124/// instances of the scene's entities as its children. If you modify the
125/// `SCENE_FILE_PATH` scene file, or if you enable file watching, you can see
126/// changes reflected immediately.
127fn load_scene_system(mut commands: Commands, asset_server: Res<AssetServer>) {
128    commands.spawn(DynamicSceneRoot(asset_server.load(SCENE_FILE_PATH)));
129}
130
131/// Logs changes made to `ComponentA` entities, and also checks whether `ResourceA`
132/// has been recently added.
133///
134/// Any time a `ComponentA` is modified, that change will appear here. This system
135/// demonstrates how you might detect and handle scene updates at runtime.
136fn log_system(
137    query: Query<(Entity, &ComponentA), Changed<ComponentA>>,
138    res: Option<Res<ResourceA>>,
139) {
140    for (entity, component_a) in &query {
141        info!("  Entity({})", entity.index());
142        info!(
143            "    ComponentA: {{ x: {} y: {} }}\n",
144            component_a.x, component_a.y
145        );
146    }
147    if let Some(res) = res {
148        if res.is_added() {
149            info!("  New ResourceA: {{ score: {} }}\n", res.score);
150        }
151    }
152}
153
154/// Demonstrates how to create a new scene from scratch, populate it with data,
155/// and then serialize it to a file. The new file is written to `NEW_SCENE_FILE_PATH`.
156///
157/// This system creates a fresh world, duplicates the type registry so that our
158/// custom component types are recognized, spawns some sample entities and resources,
159/// and then serializes the resulting dynamic scene.
160fn save_scene_system(world: &mut World) {
161    // Scenes can be created from any ECS World.
162    // You can either create a new one for the scene or use the current World.
163    // For demonstration purposes, we'll create a new one.
164    let mut scene_world = World::new();
165
166    // The `TypeRegistry` resource contains information about all registered types (including components).
167    // This is used to construct scenes, so we'll want to ensure that our previous type registrations
168    // exist in this new scene world as well.
169    // To do this, we can simply clone the `AppTypeRegistry` resource.
170    let type_registry = world.resource::<AppTypeRegistry>().clone();
171    scene_world.insert_resource(type_registry);
172
173    let mut component_b = ComponentB::from_world(world);
174    component_b.value = "hello".to_string();
175    scene_world.spawn((
176        component_b,
177        ComponentA { x: 1.0, y: 2.0 },
178        Transform::IDENTITY,
179        Name::new("joe"),
180    ));
181    scene_world.spawn(ComponentA { x: 3.0, y: 4.0 });
182    scene_world.insert_resource(ResourceA { score: 1 });
183
184    // With our sample world ready to go, we can now create our scene using DynamicScene or DynamicSceneBuilder.
185    // For simplicity, we will create our scene using DynamicScene:
186    let scene = DynamicScene::from_world(&scene_world);
187
188    // Scenes can be serialized like this:
189    let type_registry = world.resource::<AppTypeRegistry>();
190    let type_registry = type_registry.read();
191    let serialized_scene = scene.serialize(&type_registry).unwrap();
192
193    // Showing the scene in the console
194    info!("{}", serialized_scene);
195
196    // Writing the scene to a new file. Using a task to avoid calling the filesystem APIs in a system
197    // as they are blocking.
198    //
199    // This can't work in Wasm as there is no filesystem access.
200    #[cfg(not(target_arch = "wasm32"))]
201    IoTaskPool::get()
202        .spawn(async move {
203            // Write the scene RON data to file
204            File::create(format!("assets/{NEW_SCENE_FILE_PATH}"))
205                .and_then(|mut file| file.write(serialized_scene.as_bytes()))
206                .expect("Error while writing scene to file");
207        })
208        .detach();
209}
examples/shader/custom_shader_instancing.rs (line 207)
206    fn from_world(world: &mut World) -> Self {
207        let mesh_pipeline = world.resource::<MeshPipeline>();
208
209        CustomPipeline {
210            shader: world.load_asset(SHADER_ASSET_PATH),
211            mesh_pipeline: mesh_pipeline.clone(),
212        }
213    }
examples/shader/specialized_mesh_pipeline.rs (line 174)
172    fn from_world(world: &mut World) -> Self {
173        // Load the shader
174        let shader_handle: Handle<Shader> = world.resource::<AssetServer>().load(SHADER_ASSET_PATH);
175        Self {
176            mesh_pipeline: MeshPipeline::from_world(world),
177            shader_handle,
178        }
179    }
tests/ecs/ambiguity_detection.rs (line 73)
72fn count_ambiguities(sub_app: &SubApp) -> AmbiguitiesCount {
73    let schedules = sub_app.world().resource::<Schedules>();
74    let mut ambiguities = <HashMap<_, _>>::default();
75    for (_, schedule) in schedules.iter() {
76        let ambiguities_in_schedule = schedule.graph().conflicting_systems().len();
77        ambiguities.insert(schedule.label(), ambiguities_in_schedule);
78    }
79    AmbiguitiesCount(ambiguities)
80}
Source

pub fn resource_ref<R>(&self) -> Ref<'_, R>
where R: Resource,

Gets a reference to the resource of the given type

§Panics

Panics if the resource does not exist. Use get_resource_ref instead if you want to handle this case.

If you want to instead insert a value if the resource does not exist, use get_resource_or_insert_with.

Source

pub fn get_resource<R>(&self) -> Option<&R>
where R: Resource,

Gets a reference to the resource of the given type if it exists

Examples found in repository?
examples/ecs/error_handling.rs (line 162)
158fn failing_system(world: &mut World) -> Result {
159    world
160        // `get_resource` returns an `Option<T>`, so we use `ok_or` to convert it to a `Result` on
161        // which we can call `?` to propagate the error.
162        .get_resource::<UninitializedResource>()
163        // We can provide a `str` here because `BevyError` implements `From<&str>`.
164        .ok_or("Resource not initialized")?;
165
166    Ok(())
167}
168
169fn failing_commands(mut commands: Commands) {
170    commands
171        // This entity doesn't exist!
172        .entity(Entity::from_raw(12345678))
173        // Normally, this failed command would panic,
174        // but since we've set the global error handler to `warn`
175        // it will log a warning instead.
176        .insert(Transform::default());
177
178    // The error handlers for commands can be set individually as well,
179    // by using the queue_handled method.
180    commands.queue_handled(
181        |world: &mut World| -> Result {
182            world
183                .get_resource::<UninitializedResource>()
184                .ok_or("Resource not initialized when accessed in a command")?;
185
186            Ok(())
187        },
188        |error, context| {
189            error!("{error}, {context}");
190        },
191    );
192}
More examples
Hide additional examples
examples/shader/custom_render_phase.rs (line 595)
587    fn run<'w>(
588        &self,
589        graph: &mut RenderGraphContext,
590        render_context: &mut RenderContext<'w>,
591        (camera, view, target): QueryItem<'w, Self::ViewQuery>,
592        world: &'w World,
593    ) -> Result<(), NodeRunError> {
594        // First, we need to get our phases resource
595        let Some(stencil_phases) = world.get_resource::<ViewSortedRenderPhases<Stencil3d>>() else {
596            return Ok(());
597        };
598
599        // Get the view entity from the graph
600        let view_entity = graph.view_entity();
601
602        // Get the phase for the current view running our node
603        let Some(stencil_phase) = stencil_phases.get(&view.retained_view_entity) else {
604            return Ok(());
605        };
606
607        // Render pass setup
608        let mut render_pass = render_context.begin_tracked_render_pass(RenderPassDescriptor {
609            label: Some("stencil pass"),
610            // For the purpose of the example, we will write directly to the view target. A real
611            // stencil pass would write to a custom texture and that texture would be used in later
612            // passes to render custom effects using it.
613            color_attachments: &[Some(target.get_color_attachment())],
614            // We don't bind any depth buffer for this pass
615            depth_stencil_attachment: None,
616            timestamp_writes: None,
617            occlusion_query_set: None,
618        });
619
620        if let Some(viewport) = camera.viewport.as_ref() {
621            render_pass.set_camera_viewport(viewport);
622        }
623
624        // Render the phase
625        // This will execute each draw functions of each phase items queued in this phase
626        if let Err(err) = stencil_phase.render(&mut render_pass, world, view_entity) {
627            error!("Error encountered while rendering the stencil phase {err:?}");
628        }
629
630        Ok(())
631    }
examples/app/headless_renderer.rs (line 346)
340    fn run(
341        &self,
342        _graph: &mut RenderGraphContext,
343        render_context: &mut RenderContext,
344        world: &World,
345    ) -> Result<(), NodeRunError> {
346        let image_copiers = world.get_resource::<ImageCopiers>().unwrap();
347        let gpu_images = world
348            .get_resource::<RenderAssets<bevy::render::texture::GpuImage>>()
349            .unwrap();
350
351        for image_copier in image_copiers.iter() {
352            if !image_copier.enabled() {
353                continue;
354            }
355
356            let src_image = gpu_images.get(&image_copier.src_image).unwrap();
357
358            let mut encoder = render_context
359                .render_device()
360                .create_command_encoder(&CommandEncoderDescriptor::default());
361
362            let block_dimensions = src_image.texture_format.block_dimensions();
363            let block_size = src_image.texture_format.block_copy_size(None).unwrap();
364
365            // Calculating correct size of image row because
366            // copy_texture_to_buffer can copy image only by rows aligned wgpu::COPY_BYTES_PER_ROW_ALIGNMENT
367            // That's why image in buffer can be little bit wider
368            // This should be taken into account at copy from buffer stage
369            let padded_bytes_per_row = RenderDevice::align_copy_bytes_per_row(
370                (src_image.size.width as usize / block_dimensions.0 as usize) * block_size as usize,
371            );
372
373            encoder.copy_texture_to_buffer(
374                src_image.texture.as_image_copy(),
375                TexelCopyBufferInfo {
376                    buffer: &image_copier.buffer,
377                    layout: TexelCopyBufferLayout {
378                        offset: 0,
379                        bytes_per_row: Some(
380                            std::num::NonZero::<u32>::new(padded_bytes_per_row as u32)
381                                .unwrap()
382                                .into(),
383                        ),
384                        rows_per_image: None,
385                    },
386                },
387                src_image.size,
388            );
389
390            let render_queue = world.get_resource::<RenderQueue>().unwrap();
391            render_queue.submit(std::iter::once(encoder.finish()));
392        }
393
394        Ok(())
395    }
examples/3d/occlusion_culling.rs (line 429)
419    fn run<'w>(
420        &self,
421        _: &mut RenderGraphContext,
422        render_context: &mut RenderContext<'w>,
423        world: &'w World,
424    ) -> Result<(), NodeRunError> {
425        // Extract the buffers that hold the GPU indirect draw parameters from
426        // the world resources. We're going to read those buffers to determine
427        // how many meshes were actually drawn.
428        let (Some(indirect_parameters_buffers), Some(indirect_parameters_mapping_buffers)) = (
429            world.get_resource::<IndirectParametersBuffers>(),
430            world.get_resource::<IndirectParametersStagingBuffers>(),
431        ) else {
432            return Ok(());
433        };
434
435        // Get the indirect parameters buffers corresponding to the opaque 3D
436        // phase, since all our meshes are in that phase.
437        let Some(phase_indirect_parameters_buffers) =
438            indirect_parameters_buffers.get(&TypeId::of::<Opaque3d>())
439        else {
440            return Ok(());
441        };
442
443        // Grab both the buffers we're copying from and the staging buffers
444        // we're copying to. Remember that we can't map the indirect parameters
445        // buffers directly, so we have to copy their contents to a staging
446        // buffer.
447        let (
448            Some(indexed_data_buffer),
449            Some(indexed_batch_sets_buffer),
450            Some(indirect_parameters_staging_data_buffer),
451            Some(indirect_parameters_staging_batch_sets_buffer),
452        ) = (
453            phase_indirect_parameters_buffers.indexed.data_buffer(),
454            phase_indirect_parameters_buffers
455                .indexed
456                .batch_sets_buffer(),
457            indirect_parameters_mapping_buffers.data.as_ref(),
458            indirect_parameters_mapping_buffers.batch_sets.as_ref(),
459        )
460        else {
461            return Ok(());
462        };
463
464        // Copy from the indirect parameters buffers to the staging buffers.
465        render_context.command_encoder().copy_buffer_to_buffer(
466            indexed_data_buffer,
467            0,
468            indirect_parameters_staging_data_buffer,
469            0,
470            indexed_data_buffer.size(),
471        );
472        render_context.command_encoder().copy_buffer_to_buffer(
473            indexed_batch_sets_buffer,
474            0,
475            indirect_parameters_staging_batch_sets_buffer,
476            0,
477            indexed_batch_sets_buffer.size(),
478        );
479
480        Ok(())
481    }
Source

pub fn get_resource_ref<R>(&self) -> Option<Ref<'_, R>>
where R: Resource,

Gets a reference including change detection to the resource of the given type if it exists.

Source

pub fn non_send_resource<R>(&self) -> &R
where R: 'static,

Gets an immutable reference to the non-send resource of the given type, if it exists.

§Panics

Panics if the resource does not exist. Use get_non_send_resource instead if you want to handle this case.

This function will panic if it isn’t called from the same thread that the resource was inserted from.

Source

pub fn get_non_send_resource<R>(&self) -> Option<&R>
where R: 'static,

Gets a reference to the non-send resource of the given type, if it exists. Otherwise returns None.

§Panics

This function will panic if it isn’t called from the same thread that the resource was inserted from.

Source

pub fn read_change_tick(&self) -> Tick

Reads the current change tick of this world.

If you have exclusive (&mut) access to the world, consider using change_tick(), which is more efficient since it does not require atomic synchronization.

Source

pub fn last_change_tick(&self) -> Tick

When called from within an exclusive system (a System that takes &mut World as its first parameter), this method returns the Tick indicating the last time the exclusive system was run.

Otherwise, this returns the Tick indicating the last time that World::clear_trackers was called.

Source

pub fn get_resource_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>>

Gets a pointer to the resource with the id ComponentId if it exists. The returned pointer must not be used to modify the resource, and must not be dereferenced after the immutable borrow of the World ends.

You should prefer to use the typed API World::get_resource where possible and only use this in cases where the actual types are not known at compile time.

Source

pub fn iter_resources(&self) -> impl Iterator<Item = (&ComponentInfo, Ptr<'_>)>

Iterates over all resources in the world.

The returned iterator provides lifetimed, but type-unsafe pointers. Actually reading the contents of each resource will require the use of unsafe code.

§Examples
§Printing the size of all resources
let mut total = 0;
for (info, _) in world.iter_resources() {
   println!("Resource: {}", info.name());
   println!("Size: {} bytes", info.layout().size());
   total += info.layout().size();
}
println!("Total size: {} bytes", total);
§Dynamically running closures for resources matching specific TypeIds
// In this example, `A` and `B` are resources. We deliberately do not use the
// `bevy_reflect` crate here to showcase the low-level [`Ptr`] usage. You should
// probably use something like `ReflectFromPtr` in a real-world scenario.

// Create the hash map that will store the closures for each resource type
let mut closures: HashMap<TypeId, Box<dyn Fn(&Ptr<'_>)>> = HashMap::default();

// Add closure for `A`
closures.insert(TypeId::of::<A>(), Box::new(|ptr| {
    // SAFETY: We assert ptr is the same type of A with TypeId of A
    let a = unsafe { &ptr.deref::<A>() };
    // ... do something with `a` here
}));

// Add closure for `B`
closures.insert(TypeId::of::<B>(), Box::new(|ptr| {
    // SAFETY: We assert ptr is the same type of B with TypeId of B
    let b = unsafe { &ptr.deref::<B>() };
    // ... do something with `b` here
}));

// Iterate all resources, in order to run the closures for each matching resource type
for (info, ptr) in world.iter_resources() {
    let Some(type_id) = info.type_id() else {
       // It's possible for resources to not have a `TypeId` (e.g. non-Rust resources
       // dynamically inserted via a scripting language) in which case we can't match them.
       continue;
    };

    let Some(closure) = closures.get(&type_id) else {
       // No closure for this resource type, skip it.
       continue;
    };

    // Run the closure for the resource
    closure(&ptr);
}
Source

pub fn get_non_send_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>>

Gets a !Send resource to the resource with the id ComponentId if it exists. The returned pointer must not be used to modify the resource, and must not be dereferenced after the immutable borrow of the World ends.

You should prefer to use the typed API World::get_resource where possible and only use this in cases where the actual types are not known at compile time.

§Panics

This function will panic if it isn’t called from the same thread that the resource was inserted from.

Source

pub fn get_by_id( &self, entity: Entity, component_id: ComponentId, ) -> Option<Ptr<'_>>

Retrieves an immutable untyped reference to the given entity’s Component of the given ComponentId. Returns None if the entity does not have a Component of the given type.

You should prefer to use the typed API World::get_mut where possible and only use this in cases where the actual types are not known at compile time.

§Panics

This function will panic if it isn’t called from the same thread that the resource was inserted from.

Trait Implementations§

Source§

impl<'w> Deref for DeferredWorld<'w>

Source§

type Target = World

The resulting type after dereferencing.
Source§

fn deref(&self) -> &<DeferredWorld<'w> as Deref>::Target

Dereferences the value.
Source§

impl<'w> From<&'w mut World> for DeferredWorld<'w>

Source§

fn from(world: &'w mut World) -> DeferredWorld<'w>

Converts to this type from the input type.
Source§

impl<'w> SystemParam for DeferredWorld<'w>

SAFETY: DeferredWorld can read all components and resources but cannot be used to gain any other mutable references.

Source§

type State = ()

Used to store data which persists across invocations of a system.
Source§

type Item<'world, 'state> = DeferredWorld<'world>

The item type returned when constructing this system param. The value of this associated type should be Self, instantiated with new lifetimes. Read more
Source§

fn init_state( _world: &mut World, system_meta: &mut SystemMeta, ) -> <DeferredWorld<'w> as SystemParam>::State

Registers any World access used by this SystemParam and creates a new instance of this param’s State.
Source§

unsafe fn get_param<'world, 'state>( _state: &'state mut <DeferredWorld<'w> as SystemParam>::State, _system_meta: &SystemMeta, world: UnsafeWorldCell<'world>, _change_tick: Tick, ) -> <DeferredWorld<'w> as SystemParam>::Item<'world, 'state>

Creates a parameter to be passed into a SystemParamFunction. Read more
Source§

unsafe fn new_archetype( state: &mut Self::State, archetype: &Archetype, system_meta: &mut SystemMeta, )

For the specified Archetype, registers the components accessed by this SystemParam (if applicable).a Read more
Source§

fn apply(state: &mut Self::State, system_meta: &SystemMeta, world: &mut World)

Applies any deferred mutations stored in this SystemParam’s state. This is used to apply Commands during ApplyDeferred.
Source§

fn queue( state: &mut Self::State, system_meta: &SystemMeta, world: DeferredWorld<'_>, )

Queues any deferred mutations to be applied at the next ApplyDeferred.
Source§

unsafe fn validate_param( state: &Self::State, system_meta: &SystemMeta, world: UnsafeWorldCell<'_>, ) -> Result<(), SystemParamValidationError>

Validates that the param can be acquired by the get_param. Read more

Auto Trait Implementations§

§

impl<'w> Freeze for DeferredWorld<'w>

§

impl<'w> !RefUnwindSafe for DeferredWorld<'w>

§

impl<'w> Send for DeferredWorld<'w>

§

impl<'w> Sync for DeferredWorld<'w>

§

impl<'w> Unpin for DeferredWorld<'w>

§

impl<'w> !UnwindSafe for DeferredWorld<'w>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

Source§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<T> Pipe for T
where T: ?Sized,

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ConditionalSend for T
where T: Send,

Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T> Settings for T
where T: 'static + Send + Sync,

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,