Skip to main content

FallbackImageFormatMsaaCache

Struct FallbackImageFormatMsaaCache 

Source
pub struct FallbackImageFormatMsaaCache(/* private fields */);
Available on crate feature bevy_render only.
Expand description

A Cache of fallback textures that uses the sample count and TextureFormat as a key

§WARNING

Images using MSAA with sample count > 1 are not initialized with data, therefore, you shouldn’t sample them before writing data to them first.

Methods from Deref<Target = HashMap<(u32, TextureFormat), GpuImage>>§

Source

pub fn hasher(&self) -> &S

Available on crate feature bevy_animation only.

Returns a reference to the map’s BuildHasher, or S parameter.

Refer to hasher for further details.

Source

pub fn capacity(&self) -> usize

Available on crate feature bevy_animation only.

Returns the number of elements the map can hold without reallocating.

Refer to capacity for further details.

§Examples
let map = HashMap::with_capacity(5);

assert!(map.capacity() >= 5);
Source

pub fn keys(&self) -> Keys<'_, K, V> ⓘ

Available on crate feature bevy_animation only.

An iterator visiting all keys in arbitrary order. The iterator element type is &'a K.

Refer to keys for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);
map.insert("bar", 1);
map.insert("baz", 2);

for key in map.keys() {
    // foo, bar, baz
    // Note that the above order is not guaranteed
}
Source

pub fn values(&self) -> Values<'_, K, V> ⓘ

Available on crate feature bevy_animation only.

An iterator visiting all values in arbitrary order. The iterator element type is &'a V.

Refer to values for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);
map.insert("bar", 1);
map.insert("baz", 2);

for key in map.values() {
    // 0, 1, 2
    // Note that the above order is not guaranteed
}
Examples found in repository?
tests/ecs/ambiguity_detection.rs (line 66)
65    fn total(&self) -> usize {
66        self.values().sum()
67    }
More examples
Hide additional examples
examples/usage/debug_frustum_culling.rs (line 316)
304fn update_shape_aabb_colors(
305    view_query: Query<&VisibleEntities, With<MyCamera>>,
306    mut gizmo_query: Query<&mut ShowAabbGizmo, With<MyShape>>,
307) -> Result {
308    // Reset the color to use the config's default color
309    for mut shape_gizmo in &mut gizmo_query {
310        shape_gizmo.color = None;
311    }
312
313    // Query for the shape entities visible for this camera
314    // Update the gizmo on any such shape entity to be green
315    let visible_entities = view_query.single()?;
316    for entity in visible_entities.entities.values().flatten() {
317        if let Ok(mut shape_gizmo) = gizmo_query.get_mut(*entity) {
318            shape_gizmo.color = Some(Color::LinearRgba(LinearRgba::GREEN));
319        }
320    }
321    Ok(())
322}
examples/ui/scroll_and_overflow/scroll.rs (line 44)
27fn send_scroll_events(
28    mut mouse_wheel_reader: MessageReader<MouseWheel>,
29    hover_map: Res<HoverMap>,
30    keyboard_input: Res<ButtonInput<KeyCode>>,
31    mut commands: Commands,
32) {
33    for mouse_wheel in mouse_wheel_reader.read() {
34        let mut delta = -Vec2::new(mouse_wheel.x, mouse_wheel.y);
35
36        if mouse_wheel.unit == MouseScrollUnit::Line {
37            delta *= LINE_HEIGHT;
38        }
39
40        if keyboard_input.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight]) {
41            std::mem::swap(&mut delta.x, &mut delta.y);
42        }
43
44        for pointer_map in hover_map.values() {
45            for entity in pointer_map.keys().copied() {
46                commands.trigger(Scroll { entity, delta });
47            }
48        }
49    }
50}
examples/ui/text/font_atlas_debug.rs (line 45)
39fn atlas_render_system(
40    mut commands: Commands,
41    mut state: ResMut<State>,
42    font_atlas_set: Res<FontAtlasSet>,
43    images: Res<Assets<Image>>,
44) {
45    if let Some(font_atlases) = font_atlas_set.values().next() {
46        let x_offset = state.atlas_count as f32;
47        if state.atlas_count == font_atlases.len() as u32 {
48            return;
49        }
50        let font_atlas = &font_atlases[state.atlas_count as usize];
51        let image = images.get(&font_atlas.texture).unwrap();
52        state.atlas_count += 1;
53        commands.spawn((
54            ImageNode::new(font_atlas.texture.clone()),
55            Node {
56                position_type: PositionType::Absolute,
57                top: Val::ZERO,
58                left: px(image.width() as f32 * x_offset),
59                ..default()
60            },
61        ));
62    }
63}
Source

pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> ⓘ

Available on crate feature bevy_animation only.

An iterator visiting all values mutably in arbitrary order. The iterator element type is &'a mut V.

Refer to values for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);
map.insert("bar", 1);
map.insert("baz", 2);

for key in map.values_mut() {
    // 0, 1, 2
    // Note that the above order is not guaranteed
}
Source

pub fn iter(&self) -> Iter<'_, K, V> ⓘ

Available on crate feature bevy_animation only.

An iterator visiting all key-value pairs in arbitrary order. The iterator element type is (&'a K, &'a V).

Refer to iter for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);
map.insert("bar", 1);
map.insert("baz", 2);

for (key, value) in map.iter() {
    // ("foo", 0), ("bar", 1), ("baz", 2)
    // Note that the above order is not guaranteed
}
Examples found in repository?
examples/stress_tests/many_text2d.rs (line 192)
179fn print_counts(
180    time: Res<Time>,
181    mut timer: Local<PrintingTimer>,
182    texts: Query<&ViewVisibility, With<Text2d>>,
183    font_atlas_set: Res<FontAtlasSet>,
184    images: Res<Assets<Image>>,
185) {
186    timer.tick(time.delta());
187    if !timer.just_finished() {
188        return;
189    }
190
191    let num_atlases = font_atlas_set
192        .iter()
193        // Removed this filter for now as the keys no longer include the AssetIds
194        //        .filter(|(key, _)| key.0 == font_id)
195        .map(|(_, atlases)| atlases.len())
196        .sum::<usize>();
197
198    let visible_texts = texts.iter().filter(|visibility| visibility.get()).count();
199
200    info!(
201        "Texts: {} Visible: {} Atlases: {} Bytes: {}",
202        texts.iter().count(),
203        visible_texts,
204        num_atlases,
205        font_atlas_set.total_bytes(images.as_ref())
206    );
207}
More examples
Hide additional examples
examples/testbed/full_ui.rs (line 456)
439pub fn update_scroll_position(
440    mut mouse_wheel_reader: MessageReader<MouseWheel>,
441    hover_map: Res<HoverMap>,
442    mut scrolled_node_query: Query<(&mut ScrollPosition, &ComputedNode), Without<Scrollbar>>,
443    keyboard_input: Res<ButtonInput<KeyCode>>,
444) {
445    for mouse_wheel in mouse_wheel_reader.read() {
446        let (mut dx, mut dy) = match mouse_wheel.unit {
447            MouseScrollUnit::Line => (mouse_wheel.x * 20., mouse_wheel.y * 20.),
448            MouseScrollUnit::Pixel => (mouse_wheel.x, mouse_wheel.y),
449        };
450
451        if keyboard_input.pressed(KeyCode::ShiftLeft) || keyboard_input.pressed(KeyCode::ShiftRight)
452        {
453            std::mem::swap(&mut dx, &mut dy);
454        }
455
456        for (_pointer, pointer_map) in hover_map.iter() {
457            for (entity, _hit) in pointer_map.iter() {
458                if let Ok((mut scroll_position, scroll_content)) =
459                    scrolled_node_query.get_mut(*entity)
460                {
461                    let visible_size = scroll_content.size();
462                    let content_size = scroll_content.content_size();
463
464                    let range = (content_size.y - visible_size.y).max(0.)
465                        * scroll_content.inverse_scale_factor;
466
467                    scroll_position.x -= dx;
468                    scroll_position.y = (scroll_position.y - dy).clamp(0., range);
469                }
470            }
471        }
472    }
473}
examples/camera/pan_orbit_camera_custom_input_plugin.rs (line 263)
185    pub fn receive_messages(
186        mut events: MessageReader<Self>,
187        mut controllers: Query<(&mut PanOrbitCamera, &GlobalTransform)>,
188        mut camera_map: ResMut<CameraPointerMap>,
189        pointer_map: Res<PointerMap>,
190        pointer_interactions: Query<&PointerInteraction>,
191        pointer_locations: Query<&PointerLocation>,
192        cameras: Query<(&Camera, &Projection)>,
193        windows: Query<&Window>,
194    ) {
195        for event in events.read() {
196            let Ok((mut controller, cam_transform)) = controllers.get_mut(event.camera()) else {
197                continue;
198            };
199
200            match event {
201                PanOrbitCameraInputMessage::Start { kind, pointer, .. } => {
202                    if controller.is_actively_controlled() {
203                        continue;
204                    }
205                    let anchor = pointer_map
206                        .get_entity(*pointer)
207                        .and_then(|entity| pointer_interactions.get(entity).ok())
208                        .and_then(|interaction| interaction.get_nearest_hit())
209                        // Since `bevy` 0.17.3:
210                        //
211                        // If the current hit is on a window, we cannot use the `hit.position` as an anchor
212                        // as the `hit.position` is in viewport coordinates.
213                        .filter(|(entity, _hit)| !windows.contains(*entity))
214                        .and_then(|(_, hit)| hit.position)
215                        .map(|world_space_hit| {
216                            // Convert the world space hit to view (camera) space
217                            cam_transform
218                                .to_matrix()
219                                .as_dmat4()
220                                .inverse()
221                                .transform_point3(world_space_hit.into())
222                        })
223                        .filter(|p| {
224                            #[cfg(debug_assertions)]
225                            if !p.is_finite() {
226                                bevy::log::warn!(
227                                    "Non-finite input fed to camera controller: {p:?}"
228                                );
229                            }
230                            p.is_finite()
231                        })
232                        .or_else(|| {
233                            let camera = cameras.get(event.camera()).ok();
234                            let pointer_location = pointer_map
235                                .get_entity(*pointer)
236                                .and_then(|entity| pointer_locations.get(entity).ok())
237                                .and_then(|l| l.location());
238                            if let Some(((camera, proj), pointer_location)) =
239                                camera.zip(pointer_location)
240                            {
241                                screen_to_view_space(
242                                    camera,
243                                    proj,
244                                    &controller,
245                                    pointer_location.position,
246                                )
247                            } else {
248                                None
249                            }
250                        })
251                        .filter(|p| p.is_finite());
252
253                    match kind {
254                        MotionKind::OrbitZoom => controller.start_orbit(anchor),
255                        MotionKind::PanZoom => controller.start_pan(anchor),
256                        MotionKind::Zoom => controller.start_zoom(anchor),
257                    }
258                    camera_map.insert(*pointer, event.camera());
259                }
260                PanOrbitCameraInputMessage::End { .. } => {
261                    controller.end_move();
262                    if let Some(pointer) = camera_map
263                        .iter()
264                        .find(|(.., camera)| **camera == event.camera())
265                        .map(|(&pointer, ..)| pointer)
266                    {
267                        camera_map.remove(&pointer);
268                    }
269                }
270            }
271        }
272    }
273
274    /// While a camera motion is active, this system will take care of sending new pointer motion to
275    /// the camera controller. The camera controller assumes that pan and orbit movements are tied
276    /// to screen space pointer motion.
277    ///
278    /// This is because some of the pixel-perfect features of the controller require that data be
279    /// passed in as screen space deltas, to compute perfect first-order control. This is also
280    /// because the plugin uses pointer information to know which camera is being controlled.
281    ///
282    /// If you want to control the camera with different inputs, you will need to replace this
283    /// system with one that tracks other input methods, and sends the required zoom and screenspace
284    /// movement information.
285    pub fn send_pointer_inputs(
286        camera_map: Res<CameraPointerMap>,
287        mut camera_controllers: Query<&mut PanOrbitCamera>,
288        mut mouse_wheel: MessageReader<MouseWheel>,
289        mut moves: MessageReader<PointerInput>,
290    ) {
291        let moves_list: Vec<_> = moves.read().collect();
292        for (pointer, camera) in camera_map.iter() {
293            let Ok(mut camera_controller) = camera_controllers.get_mut(*camera) else {
294                continue;
295            };
296
297            let screenspace_input = moves_list
298                .iter()
299                .filter(|m| m.pointer_id.eq(pointer))
300                .filter_map(|m| match m.action {
301                    PointerAction::Move { delta } => Some(delta),
302                    _ => None,
303                })
304                .sum();
305
306            let zoom_amount = match pointer {
307                // TODO: add pinch zoom support
308                PointerId::Mouse => mouse_wheel
309                    .read()
310                    .map(|mw| {
311                        let scroll_multiplier = match mw.unit {
312                            MouseScrollUnit::Line => 150.0,
313                            MouseScrollUnit::Pixel => 1.0,
314                        };
315                        mw.y * scroll_multiplier
316                    })
317                    .sum::<f32>(),
318                _ => 0.0,
319            };
320
321            camera_controller.send_screenspace_input(screenspace_input);
322            camera_controller.send_zoom_input(zoom_amount);
323        }
324        // This must be cleared manually because reading these inputs is conditional - we are not
325        // guaranteed to be flushing the events every frame.
326        mouse_wheel.clear();
327    }
Source

pub fn iter_mut(&mut self) -> IterMut<'_, K, V> ⓘ

Available on crate feature bevy_animation only.

An iterator visiting all key-value pairs in arbitrary order, with mutable references to the values. The iterator element type is (&'a K, &'a mut V).

Refer to iter_mut for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);
map.insert("bar", 1);
map.insert("baz", 2);

for (key, value) in map.iter_mut() {
    // ("foo", 0), ("bar", 1), ("baz", 2)
    // Note that the above order is not guaranteed
}
Examples found in repository?
examples/3d/tonemapping.rs (line 383)
340fn update_color_grading_settings(
341    keys: Res<ButtonInput<KeyCode>>,
342    time: Res<Time>,
343    mut per_method_settings: ResMut<PerMethodSettings>,
344    tonemapping: Single<&Tonemapping>,
345    current_scene: Res<CurrentScene>,
346    mut selected_parameter: ResMut<SelectedParameter>,
347) {
348    let color_grading = per_method_settings.settings.get_mut(*tonemapping).unwrap();
349    let mut dt = time.delta_secs() * 0.25;
350    if keys.pressed(KeyCode::ArrowLeft) {
351        dt = -dt;
352    }
353
354    if keys.just_pressed(KeyCode::ArrowDown) {
355        selected_parameter.next();
356    }
357    if keys.just_pressed(KeyCode::ArrowUp) {
358        selected_parameter.prev();
359    }
360    if keys.pressed(KeyCode::ArrowLeft) || keys.pressed(KeyCode::ArrowRight) {
361        match selected_parameter.value {
362            0 => {
363                color_grading.global.exposure += dt;
364            }
365            1 => {
366                color_grading
367                    .all_sections_mut()
368                    .for_each(|section| section.gamma += dt);
369            }
370            2 => {
371                color_grading
372                    .all_sections_mut()
373                    .for_each(|section| section.saturation += dt);
374            }
375            3 => {
376                color_grading.global.post_saturation += dt;
377            }
378            _ => {}
379        }
380    }
381
382    if keys.just_pressed(KeyCode::Space) {
383        for (_, grading) in per_method_settings.settings.iter_mut() {
384            *grading = ColorGrading::default();
385        }
386    }
387
388    if keys.just_pressed(KeyCode::Enter) && current_scene.0 == 1 {
389        for (mapper, grading) in per_method_settings.settings.iter_mut() {
390            *grading = PerMethodSettings::basic_scene_recommendation(*mapper);
391        }
392    }
393}
Source

pub fn len(&self) -> usize

Available on crate feature bevy_animation only.

Returns the number of elements in the map.

Refer to len for further details.

§Examples
let mut map = HashMap::new();

assert_eq!(map.len(), 0);

map.insert("foo", 0);

assert_eq!(map.len(), 1);
Examples found in repository?
examples/stress_tests/many_lights.rs (line 182)
166fn print_visible_light_count(
167    time: Res<Time>,
168    mut timer: Local<PrintingTimer>,
169    visible: Query<&ExtractedPointLight>,
170    global_clusterable_object_meta: Res<GlobalClusterableObjectMeta>,
171) {
172    timer.0.tick(time.delta());
173
174    if timer.0.just_finished() {
175        // Note that it's not generally a safe assumption that the number of
176        // lights equals the number of clusterable objects, since some objects
177        // other than lights are clusterable. However, in this specific example,
178        // the only clusterable objects are lights.
179        info!(
180            "Visible Lights: {}, Rendered Lights: {}",
181            visible.iter().len(),
182            global_clusterable_object_meta.entity_to_index.len()
183        );
184    }
185}
Source

pub fn is_empty(&self) -> bool

Available on crate feature bevy_animation only.

Returns true if the map contains no elements.

Refer to is_empty for further details.

§Examples
let mut map = HashMap::new();

assert!(map.is_empty());

map.insert("foo", 0);

assert!(!map.is_empty());
Examples found in repository?
examples/2d/mesh2d_manual.rs (line 575)
565fn queue_colored_mesh2d(
566    transparent_draw_functions: Res<DrawFunctions<TransparentColoredMesh2d>>,
567    colored_mesh2d_pipeline: Res<ColoredMesh2dPipeline>,
568    mut pipelines: ResMut<SpecializedRenderPipelines<ColoredMesh2dPipeline>>,
569    pipeline_cache: Res<PipelineCache>,
570    render_meshes: Res<RenderAssets<RenderMesh>>,
571    render_mesh_instances: Res<RenderColoredMesh2dInstances>,
572    mut transparent_render_phases: ResMut<ViewSortedRenderPhases<TransparentColoredMesh2d>>,
573    views: Query<(&RenderVisibleEntities, &ExtractedView, &Msaa)>,
574) {
575    if render_mesh_instances.is_empty() {
576        return;
577    }
578
579    // Iterate each view (a camera is a view)
580    for (visible_entities, view, msaa) in &views {
581        let Some(transparent_phase) = transparent_render_phases.get_mut(&view.retained_view_entity)
582        else {
583            continue;
584        };
585
586        let draw_colored_mesh2d = transparent_draw_functions
587            .read()
588            .id::<DrawTransparentColoredMesh2d>();
589
590        let mesh_key = Mesh2dPipelineKey::from_msaa_samples(msaa.samples())
591            | Mesh2dPipelineKey::from_target_format(view.target_format);
592
593        // Queue all entities visible to that view
594        let Some(visible_entities) = visible_entities.get::<Mesh2d>() else {
595            continue;
596        };
597        for (render_entity, visible_entity) in visible_entities.iter_visible() {
598            if let Some(mesh_instance) = render_mesh_instances.get(visible_entity) {
599                let mesh2d_handle = mesh_instance.mesh_asset_id;
600                let mesh2d_transforms = &mesh_instance.transforms;
601                // Get our specialized pipeline
602                let mut mesh2d_key = mesh_key;
603                let Some(mesh) = render_meshes.get(mesh2d_handle) else {
604                    continue;
605                };
606                mesh2d_key |= Mesh2dPipelineKey::from(
607                    BaseMeshPipelineKey::from_primitive_topology_and_strip_index(
608                        mesh.primitive_topology(),
609                        mesh.index_format(),
610                    )
611                    .bits(),
612                );
613
614                let pipeline_id =
615                    pipelines.specialize(&pipeline_cache, &colored_mesh2d_pipeline, mesh2d_key);
616
617                let mesh_z = mesh2d_transforms.world_from_local.translation.z;
618                transparent_phase.add_retained(TransparentColoredMesh2d {
619                    entity: (*render_entity, *visible_entity),
620                    draw_function: draw_colored_mesh2d,
621                    pipeline: pipeline_id,
622                    // The 2d render items are sorted according to their z value before rendering,
623                    // in order to get correct transparency
624                    sort_key: FloatOrd(mesh_z),
625                    // This material is not batched
626                    batch_range: 0..1,
627                    extra_index: PhaseItemExtraIndex::None,
628                    indexed: mesh.indexed(),
629                });
630            }
631        }
632    }
633}
Source

pub fn drain(&mut self) -> Drain<'_, K, V> ⓘ

Available on crate feature bevy_animation only.

Clears the map, returning all key-value pairs as an iterator. Keeps the allocated memory for reuse.

Refer to drain for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);
map.insert("bar", 1);
map.insert("baz", 2);

for (key, value) in map.drain() {
    // ("foo", 0), ("bar", 1), ("baz", 2)
    // Note that the above order is not guaranteed
}

assert!(map.is_empty());
Source

pub fn retain<F>(&mut self, f: F)
where F: FnMut(&K, &mut V) -> bool,

Available on crate feature bevy_animation only.

Retains only the elements specified by the predicate. Keeps the allocated memory for reuse.

Refer to retain for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);
map.insert("bar", 1);
map.insert("baz", 2);

map.retain(|key, value| *value == 2);

assert_eq!(map.len(), 1);
Examples found in repository?
examples/shader_advanced/custom_render_phase.rs (line 546)
528fn extract_camera_phases(
529    mut stencil_phases: ResMut<ViewSortedRenderPhases<Stencil3d>>,
530    cameras: Extract<Query<(Entity, &Camera), With<Camera3d>>>,
531    mut live_entities: Local<HashSet<RetainedViewEntity>>,
532) {
533    live_entities.clear();
534    for (main_entity, camera) in &cameras {
535        if !camera.is_active {
536            continue;
537        }
538        // This is the main camera, so we use the first subview index (0)
539        let retained_view_entity = RetainedViewEntity::new(main_entity.into(), None, 0);
540
541        stencil_phases.prepare_for_new_frame(retained_view_entity);
542        live_entities.insert(retained_view_entity);
543    }
544
545    // Clear out all dead views.
546    stencil_phases.retain(|camera_entity, _| live_entities.contains(camera_entity));
547}
More examples
Hide additional examples
examples/2d/mesh2d_manual.rs (line 513)
492fn extract_colored_mesh2d_camera_phases(
493    mut colored_mesh2d_render_phases: ResMut<ViewSortedRenderPhases<TransparentColoredMesh2d>>,
494    cameras_2d: Extract<Query<(Entity, &Camera), With<Camera2d>>>,
495    mut live_entities: Local<HashSet<RetainedViewEntity>>,
496) {
497    live_entities.clear();
498
499    for (main_entity, camera) in &cameras_2d {
500        if !camera.is_active {
501            continue;
502        }
503
504        // This is the main 2D camera, so we use the first subview index (0).
505        let retained_view_entity = RetainedViewEntity::new(main_entity.into(), None, 0);
506
507        colored_mesh2d_render_phases.prepare_for_new_frame(retained_view_entity);
508
509        live_entities.insert(retained_view_entity);
510    }
511
512    // Clear out all dead views.
513    colored_mesh2d_render_phases.retain(|camera_entity, _| live_entities.contains(camera_entity));
514}
Source

pub fn extract_if<F>(&mut self, f: F) -> ExtractIf<'_, K, V, F> ⓘ
where F: FnMut(&K, &mut V) -> bool,

Available on crate feature bevy_animation only.

Drains elements which are true under the given predicate, and returns an iterator over the removed items.

Refer to extract_if for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);
map.insert("bar", 1);
map.insert("baz", 2);

let extracted = map
    .extract_if(|key, value| *value == 2)
    .collect::<Vec<_>>();

assert_eq!(map.len(), 2);
assert_eq!(extracted.len(), 1);
Source

pub fn clear(&mut self)

Available on crate feature bevy_animation only.

Clears the map, removing all key-value pairs. Keeps the allocated memory for reuse.

Refer to clear for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);
map.insert("bar", 1);
map.insert("baz", 2);

map.clear();

assert!(map.is_empty());
Source

pub fn reserve(&mut self, additional: usize)

Available on crate feature bevy_animation only.

Reserves capacity for at least additional more elements to be inserted in the HashMap. The collection may reserve more space to avoid frequent reallocations.

Refer to reserve for further details.

§Examples
let mut map = HashMap::with_capacity(5);

assert!(map.capacity() >= 5);

map.reserve(10);

assert!(map.capacity() - map.len() >= 10);
Source

pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>

Available on crate feature bevy_animation only.

Tries to reserve capacity for at least additional more elements to be inserted in the given HashMap<K,V>. The collection may reserve more space to avoid frequent reallocations.

Refer to try_reserve for further details.

§Examples
let mut map = HashMap::with_capacity(5);

assert!(map.capacity() >= 5);

map.try_reserve(10).expect("Out of Memory!");

assert!(map.capacity() - map.len() >= 10);
Source

pub fn shrink_to_fit(&mut self)

Available on crate feature bevy_animation only.

Shrinks the capacity of the map as much as possible. It will drop down as much as possible while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.

Refer to shrink_to_fit for further details.

§Examples
let mut map = HashMap::with_capacity(5);

map.insert("foo", 0);
map.insert("bar", 1);
map.insert("baz", 2);

assert!(map.capacity() >= 5);

map.shrink_to_fit();

assert_eq!(map.capacity(), 3);
Source

pub fn shrink_to(&mut self, min_capacity: usize)

Available on crate feature bevy_animation only.

Shrinks the capacity of the map with a lower limit. It will drop down no lower than the supplied limit while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.

Refer to shrink_to for further details.

Source

pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S>

Available on crate feature bevy_animation only.

Gets the given key’s corresponding entry in the map for in-place manipulation.

Refer to entry for further details.

§Examples
let mut map = HashMap::new();

let value = map.entry("foo").or_insert(0);
Examples found in repository?
examples/ecs/observers.rs (line 148)
142fn on_add_mine(add: On<Add<Mine>>, query: Query<&Mine>, mut index: ResMut<SpatialIndex>) {
143    let mine = query.get(add.entity).unwrap();
144    let tile = (
145        (mine.pos.x / CELL_SIZE).floor() as i32,
146        (mine.pos.y / CELL_SIZE).floor() as i32,
147    );
148    index.map.entry(tile).or_default().insert(add.entity);
149}
150
151// Remove despawned mines from our index
152fn on_remove_mine(remove: On<Remove<Mine>>, query: Query<&Mine>, mut index: ResMut<SpatialIndex>) {
153    let mine = query.get(remove.entity).unwrap();
154    let tile = (
155        (mine.pos.x / CELL_SIZE).floor() as i32,
156        (mine.pos.y / CELL_SIZE).floor() as i32,
157    );
158    index.map.entry(tile).and_modify(|set| {
159        set.remove(&remove.entity);
160    });
161}
More examples
Hide additional examples
examples/shader_advanced/manual_material.rs (line 187)
147    fn prepare_asset(
148        source_asset: Self::SourceAsset,
149        asset_id: AssetId<Self::SourceAsset>,
150        (
151            opaque_draw_functions,
152            material_layout,
153            asset_server,
154            bind_group_allocators,
155            render_material_bindings,
156            gpu_images,
157            image_material_sampler,
158        ): &mut SystemParamItem<Self::Param>,
159    ) -> std::result::Result<Self::ErasedAsset, PrepareAssetError<Self::SourceAsset>> {
160        let material_layout = material_layout.0.clone();
161        let draw_function_id = opaque_draw_functions.read().id::<DrawMaterial>();
162        let bind_group_allocator = bind_group_allocators
163            .get_mut(&TypeId::of::<ImageMaterial>())
164            .unwrap();
165        let Some(image) = gpu_images.get(&source_asset.image) else {
166            return Err(PrepareAssetError::RetryNextUpdate(source_asset));
167        };
168        let mut unprepared = BindGroupBuilder {
169            binding_resources: UnpreparedBindingResources(vec![
170                (
171                    0,
172                    UnpreparedBindingResource::TextureView(
173                        TextureViewDimension::D2,
174                        image.texture_view.clone(),
175                    ),
176                ),
177                (
178                    1,
179                    UnpreparedBindingResource::Sampler(
180                        SamplerBindingType::NonFiltering,
181                        image_material_sampler.0.clone(),
182                    ),
183                ),
184            ]),
185            data_buffer: vec![],
186        };
187        let binding = match render_material_bindings.entry(asset_id.into()) {
188            Entry::Occupied(mut occupied_entry) => {
189                bind_group_allocator.free(*occupied_entry.get());
190                let new_binding =
191                    bind_group_allocator.allocate_unprepared(&mut unprepared, &material_layout);
192                *occupied_entry.get_mut() = new_binding;
193                new_binding
194            }
195            Entry::Vacant(vacant_entry) => *vacant_entry.insert(
196                bind_group_allocator.allocate_unprepared(&mut unprepared, &material_layout),
197            ),
198        };
199
200        let mut properties = MaterialProperties {
201            material_layout: Some(material_layout),
202            mesh_pipeline_key_bits: ErasedMeshPipelineKey::new(MeshPipelineKey::empty()),
203            base_specialize: Some(base_specialize),
204            ..Default::default()
205        };
206        properties.add_draw_function(MainPassOpaqueDrawFunction, draw_function_id);
207        properties.add_shader(MaterialFragmentShader, asset_server.load(SHADER_ASSET_PATH));
208
209        Ok(PreparedMaterial {
210            binding,
211            properties: Arc::new(properties),
212        })
213    }
Source

pub fn entry_ref<'a, 'b, Q>( &'a mut self, key: &'b Q, ) -> EntryRef<'a, 'b, K, Q, V, S>
where Q: Hash + Equivalent<K> + ?Sized,

Available on crate feature bevy_animation only.

Gets the given key’s corresponding entry by reference in the map for in-place manipulation.

Refer to entry_ref for further details.

§Examples
let mut map = HashMap::new();

let value = map.entry_ref("foo").or_insert(0);
Source

pub fn get<Q>(&self, k: &Q) -> Option<&V>
where Q: Hash + Equivalent<K> + ?Sized,

Available on crate feature bevy_animation only.

Returns a reference to the value corresponding to the key.

Refer to get for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);

assert_eq!(map.get("foo"), Some(&0));
Examples found in repository?
examples/ecs/immutable_components.rs (line 69)
68    fn get_entity(&self, name: &'static str) -> Option<Entity> {
69        self.name_to_entity.get(&Name(name)).copied()
70    }
More examples
Hide additional examples
examples/gltf/gltf_extension_animation_graph.rs (line 240)
231    fn on_animations_collected(
232        &mut self,
233        _load_context: &mut LoadContext<'_>,
234        _animations: &[Handle<AnimationClip>],
235        named_animations: &HashMap<Box<str>, Handle<AnimationClip>>,
236        animation_roots: &HashSet<usize>,
237    ) {
238        self.animation_root_indices = animation_roots.clone();
239
240        if let Some(handle) = named_animations.get("Run") {
241            self.clip = Some(handle.clone());
242        }
243    }
examples/ecs/observers.rs (line 229)
221    fn get_nearby(&self, pos: Vec2) -> Vec<Entity> {
222        let tile = (
223            (pos.x / CELL_SIZE).floor() as i32,
224            (pos.y / CELL_SIZE).floor() as i32,
225        );
226        let mut nearby = Vec::new();
227        for x in -1..2 {
228            for y in -1..2 {
229                if let Some(mines) = self.map.get(&(tile.0 + x, tile.1 + y)) {
230                    nearby.extend(mines.iter());
231                }
232            }
233        }
234        nearby
235    }
tests/3d/test_skinned_mesh_bounds.rs (line 81)
72fn spawn_scene(
73    mut commands: Commands,
74    query: Query<(Entity, &PendingScene)>,
75    assets: Res<Assets<Gltf>>,
76    mut graphs: ResMut<Assets<AnimationGraph>>,
77) {
78    for (entity, PendingScene(asset)) in query.iter() {
79        if let Some(gltf) = assets.get(asset)
80            && let Some(scene_handle) = gltf.scenes.first()
81            && let Some(animation_handle) = gltf.named_animations.get("Run")
82        {
83            let (graph, graph_node_index) = AnimationGraph::from_clip(animation_handle.clone());
84
85            commands
86                .entity(entity)
87                .remove::<PendingScene>()
88                .insert((
89                    WorldAssetRoot(scene_handle.clone()),
90                    PendingAnimation((graphs.add(graph), graph_node_index)),
91                ))
92                .observe(play_animation);
93        }
94    }
95}
examples/2d/mesh2d_manual.rs (line 472)
465    fn get_batch_data(
466        (mesh_instances, mesh_allocator): &SystemParamItem<Self::Param>,
467        (_entity, main_entity): (Entity, MainEntity),
468    ) -> Option<(
469        Self::BufferData,
470        Option<(Self::BatchSetCompareData, Self::BatchCompareData)>,
471    )> {
472        let mesh_instance = mesh_instances.get(&main_entity)?;
473        let metadata_index = mesh_allocator
474            .mesh_metadata_slice(&mesh_instance.mesh_asset_id)
475            .map(|mesh_metadata_slice| mesh_metadata_slice.range.start);
476
477        Some((
478            Mesh2dUniform::from_components(
479                &mesh_instance.transforms,
480                MaterialBindGroupSlot(0),
481                mesh_instance.tag,
482                metadata_index,
483            ),
484            mesh_instance
485                .automatic_batching
486                .then_some((mesh_instance.mesh_asset_id, None)),
487        ))
488    }
489}
490
491/// Prepares our custom render phase for a new frame.
492fn extract_colored_mesh2d_camera_phases(
493    mut colored_mesh2d_render_phases: ResMut<ViewSortedRenderPhases<TransparentColoredMesh2d>>,
494    cameras_2d: Extract<Query<(Entity, &Camera), With<Camera2d>>>,
495    mut live_entities: Local<HashSet<RetainedViewEntity>>,
496) {
497    live_entities.clear();
498
499    for (main_entity, camera) in &cameras_2d {
500        if !camera.is_active {
501            continue;
502        }
503
504        // This is the main 2D camera, so we use the first subview index (0).
505        let retained_view_entity = RetainedViewEntity::new(main_entity.into(), None, 0);
506
507        colored_mesh2d_render_phases.prepare_for_new_frame(retained_view_entity);
508
509        live_entities.insert(retained_view_entity);
510    }
511
512    // Clear out all dead views.
513    colored_mesh2d_render_phases.retain(|camera_entity, _| live_entities.contains(camera_entity));
514}
515
516/// Extract the [`ColoredMesh2d`] marker component into the render app
517pub fn extract_colored_mesh2d(
518    mut commands: Commands,
519    mut previous_len: Local<usize>,
520    // When extracting, you must use `Extract` to mark the `SystemParam`s
521    // which should be taken from the main world.
522    query: Extract<
523        Query<
524            (
525                Entity,
526                RenderEntity,
527                &ViewVisibility,
528                &GlobalTransform,
529                &Mesh2d,
530            ),
531            With<ColoredMesh2d>,
532        >,
533    >,
534    mut render_mesh_instances: ResMut<RenderColoredMesh2dInstances>,
535) {
536    let mut values = Vec::with_capacity(*previous_len);
537    for (entity, render_entity, view_visibility, transform, handle) in &query {
538        if !view_visibility.get() {
539            continue;
540        }
541
542        let transforms = Mesh2dTransforms {
543            world_from_local: transform.affine().into(),
544            flags: MeshFlags::empty().bits(),
545        };
546
547        values.push((render_entity, ColoredMesh2d));
548        render_mesh_instances.insert(
549            entity.into(),
550            RenderMesh2dInstance {
551                mesh_asset_id: handle.0.id(),
552                transforms,
553                // This is unused here.
554                material_bindings_index: MaterialBindingId::default(),
555                automatic_batching: false,
556                tag: 0,
557            },
558        );
559    }
560    *previous_len = values.len();
561    commands.try_insert_batch(values);
562}
563
564/// Queue the 2d meshes marked with [`ColoredMesh2d`] using our custom pipeline and draw function
565fn queue_colored_mesh2d(
566    transparent_draw_functions: Res<DrawFunctions<TransparentColoredMesh2d>>,
567    colored_mesh2d_pipeline: Res<ColoredMesh2dPipeline>,
568    mut pipelines: ResMut<SpecializedRenderPipelines<ColoredMesh2dPipeline>>,
569    pipeline_cache: Res<PipelineCache>,
570    render_meshes: Res<RenderAssets<RenderMesh>>,
571    render_mesh_instances: Res<RenderColoredMesh2dInstances>,
572    mut transparent_render_phases: ResMut<ViewSortedRenderPhases<TransparentColoredMesh2d>>,
573    views: Query<(&RenderVisibleEntities, &ExtractedView, &Msaa)>,
574) {
575    if render_mesh_instances.is_empty() {
576        return;
577    }
578
579    // Iterate each view (a camera is a view)
580    for (visible_entities, view, msaa) in &views {
581        let Some(transparent_phase) = transparent_render_phases.get_mut(&view.retained_view_entity)
582        else {
583            continue;
584        };
585
586        let draw_colored_mesh2d = transparent_draw_functions
587            .read()
588            .id::<DrawTransparentColoredMesh2d>();
589
590        let mesh_key = Mesh2dPipelineKey::from_msaa_samples(msaa.samples())
591            | Mesh2dPipelineKey::from_target_format(view.target_format);
592
593        // Queue all entities visible to that view
594        let Some(visible_entities) = visible_entities.get::<Mesh2d>() else {
595            continue;
596        };
597        for (render_entity, visible_entity) in visible_entities.iter_visible() {
598            if let Some(mesh_instance) = render_mesh_instances.get(visible_entity) {
599                let mesh2d_handle = mesh_instance.mesh_asset_id;
600                let mesh2d_transforms = &mesh_instance.transforms;
601                // Get our specialized pipeline
602                let mut mesh2d_key = mesh_key;
603                let Some(mesh) = render_meshes.get(mesh2d_handle) else {
604                    continue;
605                };
606                mesh2d_key |= Mesh2dPipelineKey::from(
607                    BaseMeshPipelineKey::from_primitive_topology_and_strip_index(
608                        mesh.primitive_topology(),
609                        mesh.index_format(),
610                    )
611                    .bits(),
612                );
613
614                let pipeline_id =
615                    pipelines.specialize(&pipeline_cache, &colored_mesh2d_pipeline, mesh2d_key);
616
617                let mesh_z = mesh2d_transforms.world_from_local.translation.z;
618                transparent_phase.add_retained(TransparentColoredMesh2d {
619                    entity: (*render_entity, *visible_entity),
620                    draw_function: draw_colored_mesh2d,
621                    pipeline: pipeline_id,
622                    // The 2d render items are sorted according to their z value before rendering,
623                    // in order to get correct transparency
624                    sort_key: FloatOrd(mesh_z),
625                    // This material is not batched
626                    batch_range: 0..1,
627                    extra_index: PhaseItemExtraIndex::None,
628                    indexed: mesh.indexed(),
629                });
630            }
631        }
632    }
633}
634
635/// The render node system that draws all items in the
636/// [`TransparentColoredMesh2d`] phase.
637fn main_colored_transparent_pass_2d(
638    world: &World,
639    view: ViewQuery<(
640        &ExtractedCamera,
641        &ExtractedView,
642        &ViewTarget,
643        &ViewDepthStencilTexture,
644    )>,
645    transparent_phases: Res<ViewSortedRenderPhases<TransparentColoredMesh2d>>,
646    mut ctx: RenderContext,
647) {
648    let view_entity = view.entity();
649    let (camera, extracted_view, target, depth) = view.into_inner();
650
651    let Some(transparent_phase) = transparent_phases.get(&extracted_view.retained_view_entity)
652    else {
653        return;
654    };
655
656    #[cfg(feature = "trace")]
657    let _span = info_span!("main_colored_transparent_pass_2d").entered();
658
659    let diagnostics = ctx.diagnostic_recorder();
660    let diagnostics = diagnostics.as_deref();
661
662    let color_attachments = [Some(target.get_color_attachment())];
663    // NOTE: For the transparent pass we load the depth buffer. There should be no
664    // need to write to it, but store is set to `true` as a workaround for issue #3776,
665    // https://github.com/bevyengine/bevy/issues/3776
666    // so that wgpu does not clear the depth buffer.
667    // As the opaque and alpha mask passes run first, opaque meshes can occlude
668    // transparent ones.
669    let depth_stencil_attachment = Some(depth.get_attachment(StoreOp::Store));
670
671    {
672        let mut render_pass = ctx.begin_tracked_render_pass(RenderPassDescriptor {
673            label: Some("main_colored_transparent_pass_2d"),
674            color_attachments: &color_attachments,
675            depth_stencil_attachment,
676            timestamp_writes: None,
677            occlusion_query_set: None,
678            multiview_mask: None,
679        });
680        let pass_span = diagnostics.pass_span(&mut render_pass, "main_colored_transparent_pass_2d");
681
682        if let Some(viewport) = camera.viewport.as_ref() {
683            render_pass.set_camera_viewport(viewport);
684        }
685
686        if !transparent_phase.items.is_empty() {
687            #[cfg(feature = "trace")]
688            let _transparent_span = info_span!("colored_transparent_main_pass_2d").entered();
689            if let Err(err) = transparent_phase.render(&mut render_pass, world, view_entity) {
690                error!(
691                    "Error encountered while rendering the colored transparent 2D phase {err:?}"
692                );
693            }
694        }
695
696        pass_span.end(&mut render_pass);
697    }
698}
699
700/// The render command that sets the right bind group.
701///
702/// Since the normal `SetMesh2dBindGroup` render command is hardwired to use
703/// `RenderMesh2dInstances`, we need to replace it with our own render command.
704struct SetColoredMesh2dBindGroup<const I: usize>;
705
706impl<P, const I: usize> RenderCommand<P> for SetColoredMesh2dBindGroup<I>
707where
708    P: PhaseItem,
709{
710    type Param = (
711        SRes<Mesh2dBindGroup>,
712        SRes<RenderColoredMesh2dInstances>,
713        SRes<MeshAllocator>,
714        SRes<MeshMetadataFallbackBuffer>,
715    );
716    type ViewQuery = ();
717    type ItemQuery = ();
718
719    #[inline]
720    fn render<'w>(
721        item: &P,
722        _view: (),
723        _item_query: Option<()>,
724        (mesh2d_bind_group, render_mesh2d_instances, mesh_allocator,metadata_fallback_buffer): SystemParamItem<
725            'w,
726            '_,
727            Self::Param,
728        >,
729        pass: &mut TrackedRenderPass<'w>,
730    ) -> RenderCommandResult {
731        let render_mesh2d_instances = render_mesh2d_instances.into_inner();
732        let mesh_allocator = mesh_allocator.into_inner();
733        let mesh2d_bind_group = mesh2d_bind_group.into_inner();
734
735        let Some(RenderMesh2dInstance { mesh_asset_id, .. }) =
736            render_mesh2d_instances.get(&item.main_entity())
737        else {
738            return RenderCommandResult::Skip;
739        };
740        let metadata_slab_id = mesh_allocator
741            .key_to_slab
742            .get(&bevy_render::mesh::allocator::MeshAllocationKey::new(
743                *mesh_asset_id,
744                bevy_render::mesh::allocator::ElementClass::Metadata,
745            ))
746            .cloned()
747            .unwrap_or(metadata_fallback_buffer.slab_id);
748        let Some(bind_group) = &mesh2d_bind_group.value.get(&metadata_slab_id) else {
749            return RenderCommandResult::Failure(
750                "The mesh2d bind group wasn't set in the render phase.",
751            );
752        };
753
754        let mut dynamic_offsets: [u32; 1] = Default::default();
755        let mut offset_count = 0;
756        if let PhaseItemExtraIndex::DynamicOffset(dynamic_offset) = item.extra_index() {
757            dynamic_offsets[offset_count] = dynamic_offset;
758            offset_count += 1;
759        }
760        pass.set_bind_group(I, bind_group, &dynamic_offsets[..offset_count]);
761        RenderCommandResult::Success
762    }
763}
764
765/// The render command that draws all the meshes in our custom render phase.
766struct DrawColoredMesh2d;
767
768impl<P: PhaseItem> RenderCommand<P> for DrawColoredMesh2d {
769    type Param = (
770        SRes<RenderAssets<RenderMesh>>,
771        SRes<RenderColoredMesh2dInstances>,
772        SRes<MeshAllocator>,
773    );
774    type ViewQuery = ();
775    type ItemQuery = ();
776
777    #[inline]
778    fn render<'w>(
779        item: &P,
780        _view: (),
781        _item_query: Option<()>,
782        (meshes, render_mesh2d_instances, mesh_allocator): SystemParamItem<'w, '_, Self::Param>,
783        pass: &mut TrackedRenderPass<'w>,
784    ) -> RenderCommandResult {
785        let meshes = meshes.into_inner();
786        let render_mesh2d_instances = render_mesh2d_instances.into_inner();
787        let mesh_allocator = mesh_allocator.into_inner();
788
789        let Some(RenderMesh2dInstance { mesh_asset_id, .. }) =
790            render_mesh2d_instances.get(&item.main_entity())
791        else {
792            return RenderCommandResult::Skip;
793        };
794        let Some(gpu_mesh) = meshes.get(*mesh_asset_id) else {
795            return RenderCommandResult::Skip;
796        };
797        let Some(vertex_buffer_slice) = mesh_allocator.mesh_vertex_slice(mesh_asset_id) else {
798            return RenderCommandResult::Skip;
799        };
800
801        pass.set_vertex_buffer(0, vertex_buffer_slice.buffer.slice(..));
802
803        let batch_range = item.batch_range();
804        match &gpu_mesh.buffer_info {
805            RenderMeshBufferInfo::Indexed {
806                index_format,
807                count,
808            } => {
809                let Some(index_buffer_slice) = mesh_allocator.mesh_index_slice(mesh_asset_id)
810                else {
811                    return RenderCommandResult::Skip;
812                };
813
814                pass.set_index_buffer(index_buffer_slice.buffer.slice(..), *index_format);
815
816                pass.draw_indexed(
817                    index_buffer_slice.range.start..(index_buffer_slice.range.start + count),
818                    vertex_buffer_slice.range.start as i32,
819                    batch_range.clone(),
820                );
821            }
822            RenderMeshBufferInfo::NonIndexed => {
823                pass.draw(vertex_buffer_slice.range, batch_range.clone());
824            }
825        }
826        RenderCommandResult::Success
827    }
examples/3d/tonemapping.rs (line 319)
291fn toggle_tonemapping_method(
292    keys: Res<ButtonInput<KeyCode>>,
293    mut tonemapping: Single<&mut Tonemapping>,
294    mut color_grading: Single<&mut ColorGrading>,
295    per_method_settings: Res<PerMethodSettings>,
296) {
297    if keys.just_pressed(KeyCode::Digit1) {
298        **tonemapping = Tonemapping::Linear;
299    } else if keys.just_pressed(KeyCode::Digit2) {
300        **tonemapping = Tonemapping::Reinhard;
301    } else if keys.just_pressed(KeyCode::Digit3) {
302        **tonemapping = Tonemapping::ReinhardLuminance;
303    } else if keys.just_pressed(KeyCode::Digit4) {
304        **tonemapping = Tonemapping::AcesFitted;
305    } else if keys.just_pressed(KeyCode::Digit5) {
306        **tonemapping = Tonemapping::AgX;
307    } else if keys.just_pressed(KeyCode::Digit6) {
308        **tonemapping = Tonemapping::SomewhatBoringDisplayTransform;
309    } else if keys.just_pressed(KeyCode::Digit7) {
310        **tonemapping = Tonemapping::TonyMcMapface;
311    } else if keys.just_pressed(KeyCode::Digit8) {
312        **tonemapping = Tonemapping::BlenderFilmic;
313    } else if keys.just_pressed(KeyCode::Digit9) {
314        **tonemapping = Tonemapping::KhronosPbrNeutral;
315    }
316
317    **color_grading = (*per_method_settings
318        .settings
319        .get::<Tonemapping>(&tonemapping)
320        .as_ref()
321        .unwrap())
322    .clone();
323}
Source

pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
where Q: Hash + Equivalent<K> + ?Sized,

Available on crate feature bevy_animation only.

Returns the key-value pair corresponding to the supplied key.

Refer to get_key_value for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);

assert_eq!(map.get_key_value("foo"), Some((&"foo", &0)));
Source

pub fn get_key_value_mut<Q>(&mut self, k: &Q) -> Option<(&K, &mut V)>
where Q: Hash + Equivalent<K> + ?Sized,

Available on crate feature bevy_animation only.

Returns the key-value pair corresponding to the supplied key, with a mutable reference to value.

Refer to get_key_value_mut for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);

assert_eq!(map.get_key_value_mut("foo"), Some((&"foo", &mut 0)));
Source

pub fn contains_key<Q>(&self, k: &Q) -> bool
where Q: Hash + Equivalent<K> + ?Sized,

Available on crate feature bevy_animation only.

Returns true if the map contains a value for the specified key.

Refer to contains_key for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);

assert!(map.contains_key("foo"));
Source

pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
where Q: Hash + Equivalent<K> + ?Sized,

Available on crate feature bevy_animation only.

Returns a mutable reference to the value corresponding to the key.

Refer to get_mut for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);

assert_eq!(map.get_mut("foo"), Some(&mut 0));
Examples found in repository?
examples/ui/styling/box_shadow.rs (line 307)
304fn get_example_theme() -> ThemeProps {
305    let mut props = create_dark_theme();
306    // Pane background color is made a little transparent to see the objects behind the setting controls.
307    if let Some(color) = props.semantic_base.get_mut(&SURFACE_PANE_BODY) {
308        color.set_alpha(0.9);
309    }
310    props
311}
More examples
Hide additional examples
examples/3d/color_grading.rs (line 449)
444fn get_example_theme() -> ThemeProps {
445    let mut props = create_dark_theme();
446
447    // Pane background colors are made a little transparent to see the objects behind the setting controls.
448    for token in [SURFACE_PANE_BODY, SURFACE_PANE_HEADER] {
449        if let Some(color) = props.semantic_base.get_mut(&token) {
450            color.set_alpha(0.9);
451        }
452    }
453
454    props
455}
examples/3d/tonemapping.rs (line 348)
340fn update_color_grading_settings(
341    keys: Res<ButtonInput<KeyCode>>,
342    time: Res<Time>,
343    mut per_method_settings: ResMut<PerMethodSettings>,
344    tonemapping: Single<&Tonemapping>,
345    current_scene: Res<CurrentScene>,
346    mut selected_parameter: ResMut<SelectedParameter>,
347) {
348    let color_grading = per_method_settings.settings.get_mut(*tonemapping).unwrap();
349    let mut dt = time.delta_secs() * 0.25;
350    if keys.pressed(KeyCode::ArrowLeft) {
351        dt = -dt;
352    }
353
354    if keys.just_pressed(KeyCode::ArrowDown) {
355        selected_parameter.next();
356    }
357    if keys.just_pressed(KeyCode::ArrowUp) {
358        selected_parameter.prev();
359    }
360    if keys.pressed(KeyCode::ArrowLeft) || keys.pressed(KeyCode::ArrowRight) {
361        match selected_parameter.value {
362            0 => {
363                color_grading.global.exposure += dt;
364            }
365            1 => {
366                color_grading
367                    .all_sections_mut()
368                    .for_each(|section| section.gamma += dt);
369            }
370            2 => {
371                color_grading
372                    .all_sections_mut()
373                    .for_each(|section| section.saturation += dt);
374            }
375            3 => {
376                color_grading.global.post_saturation += dt;
377            }
378            _ => {}
379        }
380    }
381
382    if keys.just_pressed(KeyCode::Space) {
383        for (_, grading) in per_method_settings.settings.iter_mut() {
384            *grading = ColorGrading::default();
385        }
386    }
387
388    if keys.just_pressed(KeyCode::Enter) && current_scene.0 == 1 {
389        for (mapper, grading) in per_method_settings.settings.iter_mut() {
390            *grading = PerMethodSettings::basic_scene_recommendation(*mapper);
391        }
392    }
393}
examples/shader_advanced/manual_material.rs (line 163)
147    fn prepare_asset(
148        source_asset: Self::SourceAsset,
149        asset_id: AssetId<Self::SourceAsset>,
150        (
151            opaque_draw_functions,
152            material_layout,
153            asset_server,
154            bind_group_allocators,
155            render_material_bindings,
156            gpu_images,
157            image_material_sampler,
158        ): &mut SystemParamItem<Self::Param>,
159    ) -> std::result::Result<Self::ErasedAsset, PrepareAssetError<Self::SourceAsset>> {
160        let material_layout = material_layout.0.clone();
161        let draw_function_id = opaque_draw_functions.read().id::<DrawMaterial>();
162        let bind_group_allocator = bind_group_allocators
163            .get_mut(&TypeId::of::<ImageMaterial>())
164            .unwrap();
165        let Some(image) = gpu_images.get(&source_asset.image) else {
166            return Err(PrepareAssetError::RetryNextUpdate(source_asset));
167        };
168        let mut unprepared = BindGroupBuilder {
169            binding_resources: UnpreparedBindingResources(vec![
170                (
171                    0,
172                    UnpreparedBindingResource::TextureView(
173                        TextureViewDimension::D2,
174                        image.texture_view.clone(),
175                    ),
176                ),
177                (
178                    1,
179                    UnpreparedBindingResource::Sampler(
180                        SamplerBindingType::NonFiltering,
181                        image_material_sampler.0.clone(),
182                    ),
183                ),
184            ]),
185            data_buffer: vec![],
186        };
187        let binding = match render_material_bindings.entry(asset_id.into()) {
188            Entry::Occupied(mut occupied_entry) => {
189                bind_group_allocator.free(*occupied_entry.get());
190                let new_binding =
191                    bind_group_allocator.allocate_unprepared(&mut unprepared, &material_layout);
192                *occupied_entry.get_mut() = new_binding;
193                new_binding
194            }
195            Entry::Vacant(vacant_entry) => *vacant_entry.insert(
196                bind_group_allocator.allocate_unprepared(&mut unprepared, &material_layout),
197            ),
198        };
199
200        let mut properties = MaterialProperties {
201            material_layout: Some(material_layout),
202            mesh_pipeline_key_bits: ErasedMeshPipelineKey::new(MeshPipelineKey::empty()),
203            base_specialize: Some(base_specialize),
204            ..Default::default()
205        };
206        properties.add_draw_function(MainPassOpaqueDrawFunction, draw_function_id);
207        properties.add_shader(MaterialFragmentShader, asset_server.load(SHADER_ASSET_PATH));
208
209        Ok(PreparedMaterial {
210            binding,
211            properties: Arc::new(properties),
212        })
213    }
examples/shader_advanced/custom_shader_instancing.rs (line 155)
137fn queue_custom(
138    transparent_3d_draw_functions: Res<DrawFunctions<Transparent3d>>,
139    custom_pipeline: Res<CustomPipeline>,
140    mut pipelines: ResMut<SpecializedMeshPipelines<CustomPipeline>>,
141    pipeline_cache: Res<PipelineCache>,
142    meshes: Res<RenderAssets<RenderMesh>>,
143    render_mesh_instances: Res<RenderMeshInstances>,
144    maybe_batched_instance_buffers: Option<
145        Res<BatchedInstanceBuffers<MeshUniform, MeshInputUniform>>,
146    >,
147    material_meshes: Query<(Entity, &MainEntity), With<InstanceMaterialData>>,
148    mut transparent_render_phases: ResMut<ViewSortedRenderPhases<Transparent3d>>,
149    views: Query<&ExtractedView>,
150    view_key_cache: Res<ViewKeyCache>,
151) {
152    let draw_custom = transparent_3d_draw_functions.read().id::<DrawCustom>();
153
154    for view in &views {
155        let Some(transparent_phase) = transparent_render_phases.get_mut(&view.retained_view_entity)
156        else {
157            continue;
158        };
159
160        let Some(&view_key) = view_key_cache.get(&view.retained_view_entity) else {
161            continue;
162        };
163
164        for (entity, main_entity) in &material_meshes {
165            let Some(mesh_instance) = render_mesh_instances.render_mesh_queue_data(*main_entity)
166            else {
167                continue;
168            };
169            let Some(mesh) = meshes.get(mesh_instance.mesh_asset_id()) else {
170                continue;
171            };
172            let key = view_key
173                | MeshPipelineKey::from_primitive_topology_and_strip_index(
174                    mesh.primitive_topology(),
175                    mesh.index_format(),
176                );
177            let pipeline = pipelines
178                .specialize(&pipeline_cache, &custom_pipeline, key, &mesh.layout)
179                .unwrap();
180            transparent_phase.add_retained(Transparent3d {
181                sorting_info: TransparentSortingInfo3d::Sorted {
182                    mesh_center: pbr::get_mesh_instance_world_from_local(
183                        *main_entity,
184                        mesh_instance.current_uniform_index,
185                        &render_mesh_instances,
186                        maybe_batched_instance_buffers.as_deref(),
187                    )
188                    .transform_point3(
189                        meshes
190                            .get(mesh_instance.mesh_asset_id())
191                            .unwrap()
192                            .aabb_center,
193                    ),
194                    depth_bias: 0.0,
195                },
196                entity: (entity, *main_entity),
197                pipeline,
198                draw_function: draw_custom,
199                distance: 0.0,
200                batch_range: 0..1,
201                extra_index: PhaseItemExtraIndex::None,
202                indexed: true,
203            });
204        }
205    }
206}
examples/2d/mesh2d_manual.rs (line 581)
565fn queue_colored_mesh2d(
566    transparent_draw_functions: Res<DrawFunctions<TransparentColoredMesh2d>>,
567    colored_mesh2d_pipeline: Res<ColoredMesh2dPipeline>,
568    mut pipelines: ResMut<SpecializedRenderPipelines<ColoredMesh2dPipeline>>,
569    pipeline_cache: Res<PipelineCache>,
570    render_meshes: Res<RenderAssets<RenderMesh>>,
571    render_mesh_instances: Res<RenderColoredMesh2dInstances>,
572    mut transparent_render_phases: ResMut<ViewSortedRenderPhases<TransparentColoredMesh2d>>,
573    views: Query<(&RenderVisibleEntities, &ExtractedView, &Msaa)>,
574) {
575    if render_mesh_instances.is_empty() {
576        return;
577    }
578
579    // Iterate each view (a camera is a view)
580    for (visible_entities, view, msaa) in &views {
581        let Some(transparent_phase) = transparent_render_phases.get_mut(&view.retained_view_entity)
582        else {
583            continue;
584        };
585
586        let draw_colored_mesh2d = transparent_draw_functions
587            .read()
588            .id::<DrawTransparentColoredMesh2d>();
589
590        let mesh_key = Mesh2dPipelineKey::from_msaa_samples(msaa.samples())
591            | Mesh2dPipelineKey::from_target_format(view.target_format);
592
593        // Queue all entities visible to that view
594        let Some(visible_entities) = visible_entities.get::<Mesh2d>() else {
595            continue;
596        };
597        for (render_entity, visible_entity) in visible_entities.iter_visible() {
598            if let Some(mesh_instance) = render_mesh_instances.get(visible_entity) {
599                let mesh2d_handle = mesh_instance.mesh_asset_id;
600                let mesh2d_transforms = &mesh_instance.transforms;
601                // Get our specialized pipeline
602                let mut mesh2d_key = mesh_key;
603                let Some(mesh) = render_meshes.get(mesh2d_handle) else {
604                    continue;
605                };
606                mesh2d_key |= Mesh2dPipelineKey::from(
607                    BaseMeshPipelineKey::from_primitive_topology_and_strip_index(
608                        mesh.primitive_topology(),
609                        mesh.index_format(),
610                    )
611                    .bits(),
612                );
613
614                let pipeline_id =
615                    pipelines.specialize(&pipeline_cache, &colored_mesh2d_pipeline, mesh2d_key);
616
617                let mesh_z = mesh2d_transforms.world_from_local.translation.z;
618                transparent_phase.add_retained(TransparentColoredMesh2d {
619                    entity: (*render_entity, *visible_entity),
620                    draw_function: draw_colored_mesh2d,
621                    pipeline: pipeline_id,
622                    // The 2d render items are sorted according to their z value before rendering,
623                    // in order to get correct transparency
624                    sort_key: FloatOrd(mesh_z),
625                    // This material is not batched
626                    batch_range: 0..1,
627                    extra_index: PhaseItemExtraIndex::None,
628                    indexed: mesh.indexed(),
629                });
630            }
631        }
632    }
633}
Source

pub fn get_disjoint_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N]
where Q: Hash + Equivalent<K> + ?Sized,

Available on crate feature bevy_animation only.

Attempts to get mutable references to N values in the map at once.

Refer to get_disjoint_mut for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);
map.insert("bar", 1);
map.insert("baz", 2);

let result = map.get_disjoint_mut(["foo", "bar"]);

assert_eq!(result, [Some(&mut 0), Some(&mut 1)]);
Source

pub fn get_disjoint_key_value_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<(&K, &mut V)>; N]
where Q: Hash + Equivalent<K> + ?Sized,

Available on crate feature bevy_animation only.

Attempts to get mutable references to N values in the map at once, with immutable references to the corresponding keys.

Refer to get_disjoint_key_value_mut for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);
map.insert("bar", 1);
map.insert("baz", 2);

let result = map.get_disjoint_key_value_mut(["foo", "bar"]);

assert_eq!(result, [Some((&"foo", &mut 0)), Some((&"bar", &mut 1))]);
Source

pub fn insert(&mut self, k: K, v: V) -> Option<V>

Available on crate feature bevy_animation only.

Inserts a key-value pair into the map.

Refer to insert for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);

assert_eq!(map.get("foo"), Some(&0));
Examples found in repository?
examples/ecs/immutable_components.rs (line 85)
77fn on_insert_name(mut world: DeferredWorld<'_>, HookContext { entity, .. }: HookContext) {
78    let Some(&name) = world.entity(entity).get::<Name>() else {
79        unreachable!("Insert hook guarantees `Name` is available on entity")
80    };
81    let Some(mut index) = world.get_resource_mut::<NameIndex>() else {
82        return;
83    };
84
85    index.name_to_entity.insert(name, entity);
86}
More examples
Hide additional examples
examples/3d/tonemapping.rs (lines 603-606)
589    fn default() -> Self {
590        let mut settings = <HashMap<_, _>>::default();
591
592        for method in [
593            Tonemapping::Linear,
594            Tonemapping::Reinhard,
595            Tonemapping::ReinhardLuminance,
596            Tonemapping::AcesFitted,
597            Tonemapping::AgX,
598            Tonemapping::SomewhatBoringDisplayTransform,
599            Tonemapping::TonyMcMapface,
600            Tonemapping::BlenderFilmic,
601            Tonemapping::KhronosPbrNeutral,
602        ] {
603            settings.insert(
604                method,
605                PerMethodSettings::basic_scene_recommendation(method),
606            );
607        }
608
609        Self { settings }
610    }
tests/ecs/ambiguity_detection.rs (line 107)
91fn count_ambiguities(sub_app: &mut SubApp) -> AmbiguitiesCount {
92    let schedule_labels = sub_app
93        .world()
94        .resource::<Schedules>()
95        .iter()
96        .map(|(_, schedule)| schedule.label())
97        .collect::<Vec<_>>();
98    let mut ambiguities = <HashMap<_, _>>::default();
99    for label in schedule_labels {
100        let ambiguities_in_schedule =
101            sub_app
102                .world_mut()
103                .schedule_scope(label, |world, schedule| {
104                    schedule.initialize(world).unwrap().unwrap();
105                    schedule.graph().conflicting_systems().len()
106                });
107        ambiguities.insert(label, ambiguities_in_schedule);
108    }
109    AmbiguitiesCount(ambiguities)
110}
examples/shader_advanced/manual_material.rs (lines 100-109)
81fn init_image_material_resources(
82    mut commands: Commands,
83    render_device: Res<RenderDevice>,
84    mut bind_group_allocators: ResMut<MaterialBindGroupAllocators>,
85) {
86    let bind_group_layout = BindGroupLayoutDescriptor::new(
87        "image_material_layout",
88        &BindGroupLayoutEntries::sequential(
89            ShaderStages::FRAGMENT,
90            (
91                texture_2d(TextureSampleType::Float { filterable: false }),
92                sampler(SamplerBindingType::NonFiltering),
93            ),
94        ),
95    );
96    let sampler = render_device.create_sampler(&SamplerDescriptor::default());
97    commands.insert_resource(ImageMaterialBindGroupLayout(bind_group_layout.clone()));
98    commands.insert_resource(ImageMaterialBindGroupSampler(sampler));
99
100    bind_group_allocators.insert(
101        TypeId::of::<ImageMaterial>(),
102        MaterialBindGroupAllocator::new(
103            &render_device,
104            "image_material_allocator",
105            None,
106            bind_group_layout,
107            None,
108        ),
109    );
110}
111
112#[derive(Resource)]
113struct ImageMaterialBindGroupLayout(BindGroupLayoutDescriptor);
114
115#[derive(Resource)]
116struct ImageMaterialBindGroupSampler(Sampler);
117
118#[derive(Component)]
119struct ImageMaterial3d(Handle<ImageMaterial>);
120
121impl AsAssetId for ImageMaterial3d {
122    type Asset = ImageMaterial;
123
124    fn as_asset_id(&self) -> AssetId<Self::Asset> {
125        self.0.id()
126    }
127}
128
129#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]
130struct ImageMaterial {
131    image: Handle<Image>,
132}
133
134impl ErasedRenderAsset for ImageMaterial {
135    type SourceAsset = ImageMaterial;
136    type ErasedAsset = PreparedMaterial;
137    type Param = (
138        SRes<DrawFunctions<Opaque3d>>,
139        SRes<ImageMaterialBindGroupLayout>,
140        SRes<AssetServer>,
141        SResMut<MaterialBindGroupAllocators>,
142        SResMut<RenderMaterialBindings>,
143        SRes<RenderAssets<GpuImage>>,
144        SRes<ImageMaterialBindGroupSampler>,
145    );
146
147    fn prepare_asset(
148        source_asset: Self::SourceAsset,
149        asset_id: AssetId<Self::SourceAsset>,
150        (
151            opaque_draw_functions,
152            material_layout,
153            asset_server,
154            bind_group_allocators,
155            render_material_bindings,
156            gpu_images,
157            image_material_sampler,
158        ): &mut SystemParamItem<Self::Param>,
159    ) -> std::result::Result<Self::ErasedAsset, PrepareAssetError<Self::SourceAsset>> {
160        let material_layout = material_layout.0.clone();
161        let draw_function_id = opaque_draw_functions.read().id::<DrawMaterial>();
162        let bind_group_allocator = bind_group_allocators
163            .get_mut(&TypeId::of::<ImageMaterial>())
164            .unwrap();
165        let Some(image) = gpu_images.get(&source_asset.image) else {
166            return Err(PrepareAssetError::RetryNextUpdate(source_asset));
167        };
168        let mut unprepared = BindGroupBuilder {
169            binding_resources: UnpreparedBindingResources(vec![
170                (
171                    0,
172                    UnpreparedBindingResource::TextureView(
173                        TextureViewDimension::D2,
174                        image.texture_view.clone(),
175                    ),
176                ),
177                (
178                    1,
179                    UnpreparedBindingResource::Sampler(
180                        SamplerBindingType::NonFiltering,
181                        image_material_sampler.0.clone(),
182                    ),
183                ),
184            ]),
185            data_buffer: vec![],
186        };
187        let binding = match render_material_bindings.entry(asset_id.into()) {
188            Entry::Occupied(mut occupied_entry) => {
189                bind_group_allocator.free(*occupied_entry.get());
190                let new_binding =
191                    bind_group_allocator.allocate_unprepared(&mut unprepared, &material_layout);
192                *occupied_entry.get_mut() = new_binding;
193                new_binding
194            }
195            Entry::Vacant(vacant_entry) => *vacant_entry.insert(
196                bind_group_allocator.allocate_unprepared(&mut unprepared, &material_layout),
197            ),
198        };
199
200        let mut properties = MaterialProperties {
201            material_layout: Some(material_layout),
202            mesh_pipeline_key_bits: ErasedMeshPipelineKey::new(MeshPipelineKey::empty()),
203            base_specialize: Some(base_specialize),
204            ..Default::default()
205        };
206        properties.add_draw_function(MainPassOpaqueDrawFunction, draw_function_id);
207        properties.add_shader(MaterialFragmentShader, asset_server.load(SHADER_ASSET_PATH));
208
209        Ok(PreparedMaterial {
210            binding,
211            properties: Arc::new(properties),
212        })
213    }
214}
215
216/// set up a simple 3D scene
217fn setup(
218    mut commands: Commands,
219    mut meshes: ResMut<Assets<Mesh>>,
220    mut materials: ResMut<Assets<ImageMaterial>>,
221    asset_server: Res<AssetServer>,
222) {
223    // cube
224    commands.spawn((
225        Mesh3d(meshes.add(Cuboid::new(2.0, 2.0, 2.0))),
226        ImageMaterial3d(materials.add(ImageMaterial {
227            image: asset_server.load("branding/icon.png"),
228        })),
229        Transform::from_xyz(0.0, 0.5, 0.0),
230    ));
231    // light
232    commands.spawn((
233        PointLight {
234            shadow_maps_enabled: true,
235            ..default()
236        },
237        Transform::from_xyz(4.0, 8.0, 4.0),
238    ));
239    // camera
240    commands.spawn((
241        Camera3d::default(),
242        Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
243    ));
244}
245
246fn extract_image_materials(
247    mut material_instances: ResMut<RenderMaterialInstances>,
248    changed_meshes_query: Extract<
249        Query<
250            (Entity, &ViewVisibility, &ImageMaterial3d),
251            Or<(Changed<ViewVisibility>, Changed<ImageMaterial3d>)>,
252        >,
253    >,
254) {
255    let last_change_tick = material_instances.current_change_tick;
256
257    for (entity, view_visibility, material) in &changed_meshes_query {
258        if view_visibility.get() {
259            material_instances.instances.insert(
260                entity.into(),
261                RenderMaterialInstance {
262                    asset_id: material.0.id().untyped(),
263                    last_change_tick,
264                },
265            );
266        } else {
267            material_instances
268                .instances
269                .remove(&MainEntity::from(entity));
270        }
271    }
272}
examples/2d/mesh2d_manual.rs (lines 548-558)
517pub fn extract_colored_mesh2d(
518    mut commands: Commands,
519    mut previous_len: Local<usize>,
520    // When extracting, you must use `Extract` to mark the `SystemParam`s
521    // which should be taken from the main world.
522    query: Extract<
523        Query<
524            (
525                Entity,
526                RenderEntity,
527                &ViewVisibility,
528                &GlobalTransform,
529                &Mesh2d,
530            ),
531            With<ColoredMesh2d>,
532        >,
533    >,
534    mut render_mesh_instances: ResMut<RenderColoredMesh2dInstances>,
535) {
536    let mut values = Vec::with_capacity(*previous_len);
537    for (entity, render_entity, view_visibility, transform, handle) in &query {
538        if !view_visibility.get() {
539            continue;
540        }
541
542        let transforms = Mesh2dTransforms {
543            world_from_local: transform.affine().into(),
544            flags: MeshFlags::empty().bits(),
545        };
546
547        values.push((render_entity, ColoredMesh2d));
548        render_mesh_instances.insert(
549            entity.into(),
550            RenderMesh2dInstance {
551                mesh_asset_id: handle.0.id(),
552                transforms,
553                // This is unused here.
554                material_bindings_index: MaterialBindingId::default(),
555                automatic_batching: false,
556                tag: 0,
557            },
558        );
559    }
560    *previous_len = values.len();
561    commands.try_insert_batch(values);
562}
examples/camera/pan_orbit_camera_custom_input_plugin.rs (line 258)
185    pub fn receive_messages(
186        mut events: MessageReader<Self>,
187        mut controllers: Query<(&mut PanOrbitCamera, &GlobalTransform)>,
188        mut camera_map: ResMut<CameraPointerMap>,
189        pointer_map: Res<PointerMap>,
190        pointer_interactions: Query<&PointerInteraction>,
191        pointer_locations: Query<&PointerLocation>,
192        cameras: Query<(&Camera, &Projection)>,
193        windows: Query<&Window>,
194    ) {
195        for event in events.read() {
196            let Ok((mut controller, cam_transform)) = controllers.get_mut(event.camera()) else {
197                continue;
198            };
199
200            match event {
201                PanOrbitCameraInputMessage::Start { kind, pointer, .. } => {
202                    if controller.is_actively_controlled() {
203                        continue;
204                    }
205                    let anchor = pointer_map
206                        .get_entity(*pointer)
207                        .and_then(|entity| pointer_interactions.get(entity).ok())
208                        .and_then(|interaction| interaction.get_nearest_hit())
209                        // Since `bevy` 0.17.3:
210                        //
211                        // If the current hit is on a window, we cannot use the `hit.position` as an anchor
212                        // as the `hit.position` is in viewport coordinates.
213                        .filter(|(entity, _hit)| !windows.contains(*entity))
214                        .and_then(|(_, hit)| hit.position)
215                        .map(|world_space_hit| {
216                            // Convert the world space hit to view (camera) space
217                            cam_transform
218                                .to_matrix()
219                                .as_dmat4()
220                                .inverse()
221                                .transform_point3(world_space_hit.into())
222                        })
223                        .filter(|p| {
224                            #[cfg(debug_assertions)]
225                            if !p.is_finite() {
226                                bevy::log::warn!(
227                                    "Non-finite input fed to camera controller: {p:?}"
228                                );
229                            }
230                            p.is_finite()
231                        })
232                        .or_else(|| {
233                            let camera = cameras.get(event.camera()).ok();
234                            let pointer_location = pointer_map
235                                .get_entity(*pointer)
236                                .and_then(|entity| pointer_locations.get(entity).ok())
237                                .and_then(|l| l.location());
238                            if let Some(((camera, proj), pointer_location)) =
239                                camera.zip(pointer_location)
240                            {
241                                screen_to_view_space(
242                                    camera,
243                                    proj,
244                                    &controller,
245                                    pointer_location.position,
246                                )
247                            } else {
248                                None
249                            }
250                        })
251                        .filter(|p| p.is_finite());
252
253                    match kind {
254                        MotionKind::OrbitZoom => controller.start_orbit(anchor),
255                        MotionKind::PanZoom => controller.start_pan(anchor),
256                        MotionKind::Zoom => controller.start_zoom(anchor),
257                    }
258                    camera_map.insert(*pointer, event.camera());
259                }
260                PanOrbitCameraInputMessage::End { .. } => {
261                    controller.end_move();
262                    if let Some(pointer) = camera_map
263                        .iter()
264                        .find(|(.., camera)| **camera == event.camera())
265                        .map(|(&pointer, ..)| pointer)
266                    {
267                        camera_map.remove(&pointer);
268                    }
269                }
270            }
271        }
272    }
Source

pub fn try_insert( &mut self, key: K, value: V, ) -> Result<&mut V, OccupiedError<'_, K, V, S>>

Available on crate feature bevy_animation only.

Tries to insert a key-value pair into the map, and returns a mutable reference to the value in the entry.

Refer to try_insert for further details.

§Examples
let mut map = HashMap::new();

map.try_insert("foo", 0).unwrap();

assert!(map.try_insert("foo", 1).is_err());
Source

pub fn remove<Q>(&mut self, k: &Q) -> Option<V>
where Q: Hash + Equivalent<K> + ?Sized,

Available on crate feature bevy_animation only.

Removes a key from the map, returning the value at the key if the key was previously in the map. Keeps the allocated memory for reuse.

Refer to remove for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);

assert_eq!(map.remove("foo"), Some(0));

assert!(map.is_empty());
Examples found in repository?
examples/ecs/immutable_components.rs (line 100)
92fn on_discard_name(mut world: DeferredWorld<'_>, HookContext { entity, .. }: HookContext) {
93    let Some(&name) = world.entity(entity).get::<Name>() else {
94        unreachable!("Discard hook guarantees `Name` is available on entity")
95    };
96    let Some(mut index) = world.get_resource_mut::<NameIndex>() else {
97        return;
98    };
99
100    index.name_to_entity.remove(&name);
101}
More examples
Hide additional examples
examples/shader_advanced/manual_material.rs (line 269)
246fn extract_image_materials(
247    mut material_instances: ResMut<RenderMaterialInstances>,
248    changed_meshes_query: Extract<
249        Query<
250            (Entity, &ViewVisibility, &ImageMaterial3d),
251            Or<(Changed<ViewVisibility>, Changed<ImageMaterial3d>)>,
252        >,
253    >,
254) {
255    let last_change_tick = material_instances.current_change_tick;
256
257    for (entity, view_visibility, material) in &changed_meshes_query {
258        if view_visibility.get() {
259            material_instances.instances.insert(
260                entity.into(),
261                RenderMaterialInstance {
262                    asset_id: material.0.id().untyped(),
263                    last_change_tick,
264                },
265            );
266        } else {
267            material_instances
268                .instances
269                .remove(&MainEntity::from(entity));
270        }
271    }
272}
examples/camera/pan_orbit_camera_custom_input_plugin.rs (line 267)
185    pub fn receive_messages(
186        mut events: MessageReader<Self>,
187        mut controllers: Query<(&mut PanOrbitCamera, &GlobalTransform)>,
188        mut camera_map: ResMut<CameraPointerMap>,
189        pointer_map: Res<PointerMap>,
190        pointer_interactions: Query<&PointerInteraction>,
191        pointer_locations: Query<&PointerLocation>,
192        cameras: Query<(&Camera, &Projection)>,
193        windows: Query<&Window>,
194    ) {
195        for event in events.read() {
196            let Ok((mut controller, cam_transform)) = controllers.get_mut(event.camera()) else {
197                continue;
198            };
199
200            match event {
201                PanOrbitCameraInputMessage::Start { kind, pointer, .. } => {
202                    if controller.is_actively_controlled() {
203                        continue;
204                    }
205                    let anchor = pointer_map
206                        .get_entity(*pointer)
207                        .and_then(|entity| pointer_interactions.get(entity).ok())
208                        .and_then(|interaction| interaction.get_nearest_hit())
209                        // Since `bevy` 0.17.3:
210                        //
211                        // If the current hit is on a window, we cannot use the `hit.position` as an anchor
212                        // as the `hit.position` is in viewport coordinates.
213                        .filter(|(entity, _hit)| !windows.contains(*entity))
214                        .and_then(|(_, hit)| hit.position)
215                        .map(|world_space_hit| {
216                            // Convert the world space hit to view (camera) space
217                            cam_transform
218                                .to_matrix()
219                                .as_dmat4()
220                                .inverse()
221                                .transform_point3(world_space_hit.into())
222                        })
223                        .filter(|p| {
224                            #[cfg(debug_assertions)]
225                            if !p.is_finite() {
226                                bevy::log::warn!(
227                                    "Non-finite input fed to camera controller: {p:?}"
228                                );
229                            }
230                            p.is_finite()
231                        })
232                        .or_else(|| {
233                            let camera = cameras.get(event.camera()).ok();
234                            let pointer_location = pointer_map
235                                .get_entity(*pointer)
236                                .and_then(|entity| pointer_locations.get(entity).ok())
237                                .and_then(|l| l.location());
238                            if let Some(((camera, proj), pointer_location)) =
239                                camera.zip(pointer_location)
240                            {
241                                screen_to_view_space(
242                                    camera,
243                                    proj,
244                                    &controller,
245                                    pointer_location.position,
246                                )
247                            } else {
248                                None
249                            }
250                        })
251                        .filter(|p| p.is_finite());
252
253                    match kind {
254                        MotionKind::OrbitZoom => controller.start_orbit(anchor),
255                        MotionKind::PanZoom => controller.start_pan(anchor),
256                        MotionKind::Zoom => controller.start_zoom(anchor),
257                    }
258                    camera_map.insert(*pointer, event.camera());
259                }
260                PanOrbitCameraInputMessage::End { .. } => {
261                    controller.end_move();
262                    if let Some(pointer) = camera_map
263                        .iter()
264                        .find(|(.., camera)| **camera == event.camera())
265                        .map(|(&pointer, ..)| pointer)
266                    {
267                        camera_map.remove(&pointer);
268                    }
269                }
270            }
271        }
272    }
Source

pub fn remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>
where Q: Hash + Equivalent<K> + ?Sized,

Available on crate feature bevy_animation only.

Removes a key from the map, returning the stored key and value if the key was previously in the map. Keeps the allocated memory for reuse.

Refer to remove_entry for further details.

§Examples
let mut map = HashMap::new();

map.insert("foo", 0);

assert_eq!(map.remove_entry("foo"), Some(("foo", 0)));

assert!(map.is_empty());
Source

pub fn allocation_size(&self) -> usize

Available on crate feature bevy_animation only.

Returns the total amount of memory allocated internally by the hash set, in bytes.

Refer to allocation_size for further details.

§Examples
let mut map = HashMap::new();

assert_eq!(map.allocation_size(), 0);

map.insert("foo", 0u32);

assert!(map.allocation_size() >= size_of::<&'static str>() + size_of::<u32>());
Source

pub unsafe fn insert_unique_unchecked( &mut self, key: K, value: V, ) -> (&K, &mut V)

Available on crate feature bevy_animation only.

Insert a key-value pair into the map without checking if the key already exists in the map.

Refer to insert_unique_unchecked for further details.

§Safety

This operation is safe if a key does not exist in the map.

However, if a key exists in the map already, the behavior is unspecified: this operation may panic, loop forever, or any following operation with the map may panic, loop forever or return arbitrary result.

That said, this operation (and following operations) are guaranteed to not violate memory safety.

However this operation is still unsafe because the resulting HashMap may be passed to unsafe code which does expect the map to behave correctly, and would cause unsoundness as a result.

Source

pub unsafe fn get_disjoint_unchecked_mut<Q, const N: usize>( &mut self, keys: [&Q; N], ) -> [Option<&mut V>; N]
where Q: Hash + Equivalent<K> + ?Sized,

Available on crate feature bevy_animation only.

Attempts to get mutable references to N values in the map at once, without validating that the values are unique.

Refer to get_disjoint_unchecked_mut for further details.

Returns an array of length N with the results of each query. None will be used if the key is missing.

For a safe alternative see get_disjoint_mut.

§Safety

Calling this method with overlapping keys is undefined behavior even if the resulting references are not used.

Source

pub unsafe fn get_disjoint_key_value_unchecked_mut<Q, const N: usize>( &mut self, keys: [&Q; N], ) -> [Option<(&K, &mut V)>; N]
where Q: Hash + Equivalent<K> + ?Sized,

Available on crate feature bevy_animation only.

Attempts to get mutable references to N values in the map at once, with immutable references to the corresponding keys, without validating that the values are unique.

Refer to get_disjoint_key_value_unchecked_mut for further details.

Returns an array of length N with the results of each query. None will be returned if any of the keys are missing.

For a safe alternative see get_disjoint_key_value_mut.

§Safety

Calling this method with overlapping keys is undefined behavior even if the resulting references are not used.

Methods from Deref<Target = HashMap<K, V, S>>§

Source

pub fn allocator(&self) -> &A

Returns a reference to the underlying allocator.

Source

pub fn hasher(&self) -> &S

Returns a reference to the map’s BuildHasher.

§Examples
use hashbrown::HashMap;
use hashbrown::DefaultHashBuilder;

let hasher = DefaultHashBuilder::default();
let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
let hasher: &DefaultHashBuilder = map.hasher();
Source

pub fn capacity(&self) -> usize

Returns the number of elements the map can hold without reallocating.

This number is a lower bound; the HashMap<K, V> might be able to hold more, but is guaranteed to be able to hold at least this many.

§Examples
use hashbrown::HashMap;
let map: HashMap<i32, i32> = HashMap::with_capacity(100);
assert_eq!(map.len(), 0);
assert!(map.capacity() >= 100);
Source

pub fn keys(&self) -> Keys<'_, K, V> ⓘ

An iterator visiting all keys in arbitrary order. The iterator element type is &'a K.

§Examples
use hashbrown::HashMap;

let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
assert_eq!(map.len(), 3);
let mut vec: Vec<&str> = Vec::new();

for key in map.keys() {
    println!("{}", key);
    vec.push(*key);
}

// The `Keys` iterator produces keys in arbitrary order, so the
// keys must be sorted to test them against a sorted array.
vec.sort_unstable();
assert_eq!(vec, ["a", "b", "c"]);

assert_eq!(map.len(), 3);
Source

pub fn values(&self) -> Values<'_, K, V> ⓘ

An iterator visiting all values in arbitrary order. The iterator element type is &'a V.

§Examples
use hashbrown::HashMap;

let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
assert_eq!(map.len(), 3);
let mut vec: Vec<i32> = Vec::new();

for val in map.values() {
    println!("{}", val);
    vec.push(*val);
}

// The `Values` iterator produces values in arbitrary order, so the
// values must be sorted to test them against a sorted array.
vec.sort_unstable();
assert_eq!(vec, [1, 2, 3]);

assert_eq!(map.len(), 3);
Source

pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> ⓘ

An iterator visiting all values mutably in arbitrary order. The iterator element type is &'a mut V.

§Examples
use hashbrown::HashMap;

let mut map = HashMap::new();

map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);

for val in map.values_mut() {
    *val = *val + 10;
}

assert_eq!(map.len(), 3);
let mut vec: Vec<i32> = Vec::new();

for val in map.values() {
    println!("{}", val);
    vec.push(*val);
}

// The `Values` iterator produces values in arbitrary order, so the
// values must be sorted to test them against a sorted array.
vec.sort_unstable();
assert_eq!(vec, [11, 12, 13]);

assert_eq!(map.len(), 3);
Source

pub fn iter(&self) -> Iter<'_, K, V> ⓘ

An iterator visiting all key-value pairs in arbitrary order. The iterator element type is (&'a K, &'a V).

§Examples
use hashbrown::HashMap;

let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
assert_eq!(map.len(), 3);
let mut vec: Vec<(&str, i32)> = Vec::new();

for (key, val) in map.iter() {
    println!("key: {} val: {}", key, val);
    vec.push((*key, *val));
}

// The `Iter` iterator produces items in arbitrary order, so the
// items must be sorted to test them against a sorted array.
vec.sort_unstable();
assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);

assert_eq!(map.len(), 3);
Source

pub fn iter_mut(&mut self) -> IterMut<'_, K, V> ⓘ

An iterator visiting all key-value pairs in arbitrary order, with mutable references to the values. The iterator element type is (&'a K, &'a mut V).

§Examples
use hashbrown::HashMap;

let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);

// Update all values
for (_, val) in map.iter_mut() {
    *val *= 2;
}

assert_eq!(map.len(), 3);
let mut vec: Vec<(&str, i32)> = Vec::new();

for (key, val) in &map {
    println!("key: {} val: {}", key, val);
    vec.push((*key, *val));
}

// The `Iter` iterator produces items in arbitrary order, so the
// items must be sorted to test them against a sorted array.
vec.sort_unstable();
assert_eq!(vec, [("a", 2), ("b", 4), ("c", 6)]);

assert_eq!(map.len(), 3);
Source

pub fn len(&self) -> usize

Returns the number of elements in the map.

§Examples
use hashbrown::HashMap;

let mut a = HashMap::new();
assert_eq!(a.len(), 0);
a.insert(1, "a");
assert_eq!(a.len(), 1);
Source

pub fn is_empty(&self) -> bool

Returns true if the map contains no elements.

§Examples
use hashbrown::HashMap;

let mut a = HashMap::new();
assert!(a.is_empty());
a.insert(1, "a");
assert!(!a.is_empty());
Source

pub fn drain(&mut self) -> Drain<'_, K, V, A> ⓘ

Clears the map, returning all key-value pairs as an iterator. Keeps the allocated memory for reuse.

If the returned iterator is dropped before being fully consumed, it drops the remaining key-value pairs. The returned iterator keeps a mutable borrow on the vector to optimize its implementation.

§Examples
use hashbrown::HashMap;

let mut a = HashMap::new();
a.insert(1, "a");
a.insert(2, "b");
let capacity_before_drain = a.capacity();

for (k, v) in a.drain().take(1) {
    assert!(k == 1 || k == 2);
    assert!(v == "a" || v == "b");
}

// As we can see, the map is empty and contains no element.
assert!(a.is_empty() && a.len() == 0);
// But map capacity is equal to old one.
assert_eq!(a.capacity(), capacity_before_drain);

let mut a = HashMap::new();
a.insert(1, "a");
a.insert(2, "b");

{   // Iterator is dropped without being consumed.
    let d = a.drain();
}

// But the map is empty even if we do not use Drain iterator.
assert!(a.is_empty());
Source

pub fn retain<F>(&mut self, f: F)
where F: FnMut(&K, &mut V) -> bool,

Retains only the elements specified by the predicate. Keeps the allocated memory for reuse.

In other words, remove all pairs (k, v) such that f(&k, &mut v) returns false. The elements are visited in unsorted (and unspecified) order.

§Examples
use hashbrown::HashMap;

let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
assert_eq!(map.len(), 8);

map.retain(|&k, _| k % 2 == 0);

// We can see, that the number of elements inside map is changed.
assert_eq!(map.len(), 4);

let mut vec: Vec<(i32, i32)> = map.iter().map(|(&k, &v)| (k, v)).collect();
vec.sort_unstable();
assert_eq!(vec, [(0, 0), (2, 20), (4, 40), (6, 60)]);
Source

pub fn extract_if<F>(&mut self, f: F) -> ExtractIf<'_, K, V, F, A> ⓘ
where F: FnMut(&K, &mut V) -> bool,

Drains elements which are true under the given predicate, and returns an iterator over the removed items.

In other words, move all pairs (k, v) such that f(&k, &mut v) returns true out into another iterator.

Note that extract_if lets you mutate every value in the filter closure, regardless of whether you choose to keep or remove it.

If the returned ExtractIf is not exhausted, e.g. because it is dropped without iterating or the iteration short-circuits, then the remaining elements will be retained. Use retain() with a negated predicate if you do not need the returned iterator.

Keeps the allocated memory for reuse.

§Examples
use hashbrown::HashMap;

let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();

let drained: HashMap<i32, i32> = map.extract_if(|k, _v| k % 2 == 0).collect();

let mut evens = drained.keys().cloned().collect::<Vec<_>>();
let mut odds = map.keys().cloned().collect::<Vec<_>>();
evens.sort();
odds.sort();

assert_eq!(evens, vec![0, 2, 4, 6]);
assert_eq!(odds, vec![1, 3, 5, 7]);

let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();

{   // Iterator is dropped without being consumed.
    let d = map.extract_if(|k, _v| k % 2 != 0);
}

// ExtractIf was not exhausted, therefore no elements were drained.
assert_eq!(map.len(), 8);
Source

pub fn clear(&mut self)

Clears the map, removing all key-value pairs. Keeps the allocated memory for reuse.

§Examples
use hashbrown::HashMap;

let mut a = HashMap::new();
a.insert(1, "a");
let capacity_before_clear = a.capacity();

a.clear();

// Map is empty.
assert!(a.is_empty());
// But map capacity is equal to old one.
assert_eq!(a.capacity(), capacity_before_clear);
Source

pub fn reserve(&mut self, additional: usize)

Reserves capacity for at least additional more elements to be inserted in the HashMap. The collection may reserve more space to avoid frequent reallocations.

§Panics

Panics if the new capacity exceeds isize::MAX bytes and abort the program in case of allocation error. Use try_reserve instead if you want to handle memory allocation failure.

§Examples
use hashbrown::HashMap;
let mut map: HashMap<&str, i32> = HashMap::new();
// Map is empty and doesn't allocate memory
assert_eq!(map.capacity(), 0);

map.reserve(10);

// And now map can hold at least 10 elements
assert!(map.capacity() >= 10);
Source

pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>

Tries to reserve capacity for at least additional more elements to be inserted in the given HashMap<K,V>. The collection may reserve more space to avoid frequent reallocations.

§Errors

If the capacity overflows, or the allocator reports a failure, then an error is returned.

§Examples
use hashbrown::HashMap;

let mut map: HashMap<&str, isize> = HashMap::new();
// Map is empty and doesn't allocate memory
assert_eq!(map.capacity(), 0);

map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");

// And now map can hold at least 10 elements
assert!(map.capacity() >= 10);

If the capacity overflows, or the allocator reports a failure, then an error is returned:

use hashbrown::HashMap;
use hashbrown::TryReserveError;
let mut map: HashMap<i32, i32> = HashMap::new();

match map.try_reserve(usize::MAX) {
    Err(error) => match error {
        TryReserveError::CapacityOverflow => {}
        _ => panic!("TryReserveError::AllocError ?"),
    },
    _ => panic!(),
}
Source

pub fn shrink_to_fit(&mut self)

Shrinks the capacity of the map as much as possible. It will drop down as much as possible while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.

§Examples
use hashbrown::HashMap;

let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
map.insert(1, 2);
map.insert(3, 4);
assert!(map.capacity() >= 100);
map.shrink_to_fit();
assert!(map.capacity() >= 2);
Source

pub fn shrink_to(&mut self, min_capacity: usize)

Shrinks the capacity of the map with a lower limit. It will drop down no lower than the supplied limit while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.

This function does nothing if the current capacity is smaller than the supplied minimum capacity.

§Examples
use hashbrown::HashMap;

let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
map.insert(1, 2);
map.insert(3, 4);
assert!(map.capacity() >= 100);
map.shrink_to(10);
assert!(map.capacity() >= 10);
map.shrink_to(0);
assert!(map.capacity() >= 2);
map.shrink_to(10);
assert!(map.capacity() >= 2);
Source

pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A>

Gets the given key’s corresponding entry in the map for in-place manipulation.

§Examples
use hashbrown::HashMap;

let mut letters = HashMap::new();

for ch in "a short treatise on fungi".chars() {
    let counter = letters.entry(ch).or_insert(0);
    *counter += 1;
}

assert_eq!(letters[&'s'], 2);
assert_eq!(letters[&'t'], 3);
assert_eq!(letters[&'u'], 1);
assert_eq!(letters.get(&'y'), None);
Source

pub fn entry_ref<'a, 'b, Q>( &'a mut self, key: &'b Q, ) -> EntryRef<'a, 'b, K, Q, V, S, A>
where Q: Hash + Equivalent<K> + ?Sized,

Gets the given key’s corresponding entry by reference in the map for in-place manipulation.

§Examples
use hashbrown::HashMap;

let mut words: HashMap<String, usize> = HashMap::new();
let source = ["poneyland", "horseyland", "poneyland", "poneyland"];
for (i, &s) in source.iter().enumerate() {
    let counter = words.entry_ref(s).or_insert(0);
    *counter += 1;
}

assert_eq!(words["poneyland"], 3);
assert_eq!(words["horseyland"], 1);
Source

pub fn get<Q>(&self, k: &Q) -> Option<&V>
where Q: Hash + Equivalent<K> + ?Sized,

Returns a reference to the value corresponding to the key.

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type.

§Examples
use hashbrown::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.get(&1), Some(&"a"));
assert_eq!(map.get(&2), None);
Source

pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
where Q: Hash + Equivalent<K> + ?Sized,

Returns the key-value pair corresponding to the supplied key.

The supplied key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type.

§Examples
use hashbrown::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
assert_eq!(map.get_key_value(&2), None);
Source

pub fn get_key_value_mut<Q>(&mut self, k: &Q) -> Option<(&K, &mut V)>
where Q: Hash + Equivalent<K> + ?Sized,

Returns the key-value pair corresponding to the supplied key, with a mutable reference to value.

The supplied key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type.

§Examples
use hashbrown::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
let (k, v) = map.get_key_value_mut(&1).unwrap();
assert_eq!(k, &1);
assert_eq!(v, &mut "a");
*v = "b";
assert_eq!(map.get_key_value_mut(&1), Some((&1, &mut "b")));
assert_eq!(map.get_key_value_mut(&2), None);
Source

pub fn contains_key<Q>(&self, k: &Q) -> bool
where Q: Hash + Equivalent<K> + ?Sized,

Returns true if the map contains a value for the specified key.

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type.

§Examples
use hashbrown::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.contains_key(&1), true);
assert_eq!(map.contains_key(&2), false);
Source

pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
where Q: Hash + Equivalent<K> + ?Sized,

Returns a mutable reference to the value corresponding to the key.

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type.

§Examples
use hashbrown::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
if let Some(x) = map.get_mut(&1) {
    *x = "b";
}
assert_eq!(map[&1], "b");

assert_eq!(map.get_mut(&2), None);
Source

pub fn get_disjoint_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N]
where Q: Hash + Equivalent<K> + ?Sized,

Attempts to get mutable references to N values in the map at once.

Returns an array of length N with the results of each query. For soundness, at most one mutable reference will be returned to any value. None will be used if the key is missing.

§Panics

Panics if any keys are overlapping.

§Examples
use hashbrown::HashMap;

let mut libraries = HashMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Athenæum".to_string(), 1807);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
libraries.insert("Library of Congress".to_string(), 1800);

// Get Athenæum and Bodleian Library
let [Some(a), Some(b)] = libraries.get_disjoint_mut([
    "Athenæum",
    "Bodleian Library",
]) else { panic!() };

// Assert values of Athenæum and Library of Congress
let got = libraries.get_disjoint_mut([
    "Athenæum",
    "Library of Congress",
]);
assert_eq!(
    got,
    [
        Some(&mut 1807),
        Some(&mut 1800),
    ],
);

// Missing keys result in None
let got = libraries.get_disjoint_mut([
    "Athenæum",
    "New York Public Library",
]);
assert_eq!(
    got,
    [
        Some(&mut 1807),
        None
    ]
);
ⓘ
use hashbrown::HashMap;

let mut libraries = HashMap::new();
libraries.insert("Athenæum".to_string(), 1807);

// Duplicate keys panic!
let got = libraries.get_disjoint_mut([
    "Athenæum",
    "Athenæum",
]);
Source

pub fn get_many_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N]
where Q: Hash + Equivalent<K> + ?Sized,

👎Deprecated:

use get_disjoint_mut instead

Attempts to get mutable references to N values in the map at once.

Source

pub unsafe fn get_disjoint_unchecked_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N]
where Q: Hash + Equivalent<K> + ?Sized,

Attempts to get mutable references to N values in the map at once, without validating that the values are unique.

Returns an array of length N with the results of each query. None will be used if the key is missing.

For a safe alternative see get_disjoint_mut.

§Safety

Calling this method with overlapping keys is undefined behavior even if the resulting references are not used.

§Examples
use hashbrown::HashMap;

let mut libraries = HashMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Athenæum".to_string(), 1807);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
libraries.insert("Library of Congress".to_string(), 1800);

// SAFETY: The keys do not overlap.
let [Some(a), Some(b)] = (unsafe { libraries.get_disjoint_unchecked_mut([
    "Athenæum",
    "Bodleian Library",
]) }) else { panic!() };

// SAFETY: The keys do not overlap.
let got = unsafe { libraries.get_disjoint_unchecked_mut([
    "Athenæum",
    "Library of Congress",
]) };
assert_eq!(
    got,
    [
        Some(&mut 1807),
        Some(&mut 1800),
    ],
);

// SAFETY: The keys do not overlap.
let got = unsafe { libraries.get_disjoint_unchecked_mut([
    "Athenæum",
    "New York Public Library",
]) };
// Missing keys result in None
assert_eq!(got, [Some(&mut 1807), None]);
Source

pub unsafe fn get_many_unchecked_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N]
where Q: Hash + Equivalent<K> + ?Sized,

👎Deprecated:

use get_disjoint_unchecked_mut instead

Attempts to get mutable references to N values in the map at once, without validating that the values are unique.

Source

pub fn get_disjoint_key_value_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<(&K, &mut V)>; N]
where Q: Hash + Equivalent<K> + ?Sized,

Attempts to get mutable references to N values in the map at once, with immutable references to the corresponding keys.

Returns an array of length N with the results of each query. For soundness, at most one mutable reference will be returned to any value. None will be used if the key is missing.

§Panics

Panics if any keys are overlapping.

§Examples
use hashbrown::HashMap;

let mut libraries = HashMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Athenæum".to_string(), 1807);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
libraries.insert("Library of Congress".to_string(), 1800);

let got = libraries.get_disjoint_key_value_mut([
    "Bodleian Library",
    "Herzogin-Anna-Amalia-Bibliothek",
]);
assert_eq!(
    got,
    [
        Some((&"Bodleian Library".to_string(), &mut 1602)),
        Some((&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691)),
    ],
);
// Missing keys result in None
let got = libraries.get_disjoint_key_value_mut([
    "Bodleian Library",
    "Gewandhaus",
]);
assert_eq!(got, [Some((&"Bodleian Library".to_string(), &mut 1602)), None]);
ⓘ
use hashbrown::HashMap;

let mut libraries = HashMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);

// Duplicate keys result in panic!
let got = libraries.get_disjoint_key_value_mut([
    "Bodleian Library",
    "Herzogin-Anna-Amalia-Bibliothek",
    "Herzogin-Anna-Amalia-Bibliothek",
]);
Source

pub fn get_many_key_value_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<(&K, &mut V)>; N]
where Q: Hash + Equivalent<K> + ?Sized,

👎Deprecated:

use get_disjoint_key_value_mut instead

Attempts to get mutable references to N values in the map at once, with immutable references to the corresponding keys.

Source

pub unsafe fn get_disjoint_key_value_unchecked_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<(&K, &mut V)>; N]
where Q: Hash + Equivalent<K> + ?Sized,

Attempts to get mutable references to N values in the map at once, with immutable references to the corresponding keys, without validating that the values are unique.

Returns an array of length N with the results of each query. None will be returned if any of the keys are missing.

For a safe alternative see get_disjoint_key_value_mut.

§Safety

Calling this method with overlapping keys is undefined behavior even if the resulting references are not used.

§Examples
use hashbrown::HashMap;

let mut libraries = HashMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Athenæum".to_string(), 1807);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
libraries.insert("Library of Congress".to_string(), 1800);

let got = libraries.get_disjoint_key_value_mut([
    "Bodleian Library",
    "Herzogin-Anna-Amalia-Bibliothek",
]);
assert_eq!(
    got,
    [
        Some((&"Bodleian Library".to_string(), &mut 1602)),
        Some((&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691)),
    ],
);
// Missing keys result in None
let got = libraries.get_disjoint_key_value_mut([
    "Bodleian Library",
    "Gewandhaus",
]);
assert_eq!(
    got,
    [
        Some((&"Bodleian Library".to_string(), &mut 1602)),
        None,
    ],
);
Source

pub unsafe fn get_many_key_value_unchecked_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<(&K, &mut V)>; N]
where Q: Hash + Equivalent<K> + ?Sized,

👎Deprecated:

use get_disjoint_key_value_unchecked_mut instead

Attempts to get mutable references to N values in the map at once, with immutable references to the corresponding keys, without validating that the values are unique.

Source

pub fn insert(&mut self, k: K, v: V) -> Option<V>

Inserts a key-value pair into the map.

If the map did not have this key present, None is returned.

If the map did have this key present, the value is updated, and the old value is returned. The key is not updated, though; this matters for types that can be == without being identical. See the std::collections module-level documentation for more.

§Examples
use hashbrown::HashMap;

let mut map = HashMap::new();
assert_eq!(map.insert(37, "a"), None);
assert_eq!(map.is_empty(), false);

map.insert(37, "b");
assert_eq!(map.insert(37, "c"), Some("b"));
assert_eq!(map[&37], "c");
Source

pub unsafe fn insert_unique_unchecked(&mut self, k: K, v: V) -> (&K, &mut V)

Insert a key-value pair into the map without checking if the key already exists in the map.

This operation is faster than regular insert, because it does not perform lookup before insertion.

This operation is useful during initial population of the map. For example, when constructing a map from another map, we know that keys are unique.

Returns a reference to the key and value just inserted.

§Safety

This operation is safe if a key does not exist in the map.

However, if a key exists in the map already, the behavior is unspecified: this operation may panic, loop forever, or any following operation with the map may panic, loop forever or return arbitrary result.

That said, this operation (and following operations) are guaranteed to not violate memory safety.

However this operation is still unsafe because the resulting HashMap may be passed to unsafe code which does expect the map to behave correctly, and would cause unsoundness as a result.

§Examples
use hashbrown::HashMap;

let mut map1 = HashMap::new();
assert_eq!(map1.insert(1, "a"), None);
assert_eq!(map1.insert(2, "b"), None);
assert_eq!(map1.insert(3, "c"), None);
assert_eq!(map1.len(), 3);

let mut map2 = HashMap::new();

for (key, value) in map1.into_iter() {
    unsafe {
        map2.insert_unique_unchecked(key, value);
    }
}

let (key, value) = unsafe { map2.insert_unique_unchecked(4, "d") };
assert_eq!(key, &4);
assert_eq!(value, &mut "d");
*value = "e";

assert_eq!(map2[&1], "a");
assert_eq!(map2[&2], "b");
assert_eq!(map2[&3], "c");
assert_eq!(map2[&4], "e");
assert_eq!(map2.len(), 4);
Source

pub fn try_insert( &mut self, key: K, value: V, ) -> Result<&mut V, OccupiedError<'_, K, V, S, A>>

Tries to insert a key-value pair into the map, and returns a mutable reference to the value in the entry.

§Errors

If the map already had this key present, nothing is updated, and an error containing the occupied entry and the value is returned.

§Examples

Basic usage:

use hashbrown::HashMap;
use hashbrown::hash_map::OccupiedError;

let mut map = HashMap::new();
assert_eq!(map.try_insert(37, "a").unwrap(), &"a");

match map.try_insert(37, "b") {
    Err(OccupiedError { entry, value }) => {
        assert_eq!(entry.key(), &37);
        assert_eq!(entry.get(), &"a");
        assert_eq!(value, "b");
    }
    _ => panic!()
}
Source

pub fn remove<Q>(&mut self, k: &Q) -> Option<V>
where Q: Hash + Equivalent<K> + ?Sized,

Removes a key from the map, returning the value at the key if the key was previously in the map. Keeps the allocated memory for reuse.

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type.

§Examples
use hashbrown::HashMap;

let mut map = HashMap::new();
// The map is empty
assert!(map.is_empty() && map.capacity() == 0);

map.insert(1, "a");

assert_eq!(map.remove(&1), Some("a"));
assert_eq!(map.remove(&1), None);

// Now map holds none elements
assert!(map.is_empty());
Source

pub fn remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>
where Q: Hash + Equivalent<K> + ?Sized,

Removes a key from the map, returning the stored key and value if the key was previously in the map. Keeps the allocated memory for reuse.

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type.

§Examples
use hashbrown::HashMap;

let mut map = HashMap::new();
// The map is empty
assert!(map.is_empty() && map.capacity() == 0);

map.insert(1, "a");

assert_eq!(map.remove_entry(&1), Some((1, "a")));
assert_eq!(map.remove(&1), None);

// Now map hold none elements
assert!(map.is_empty());
Source

pub fn allocation_size(&self) -> usize

Returns the total amount of memory allocated internally by the hash set, in bytes.

The returned number is informational only. It is intended to be primarily used for memory profiling.

Source

pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S, A>

Creates a raw entry builder for the HashMap.

Raw entries provide the lowest level of control for searching and manipulating a map. They must be manually initialized with a hash and then manually searched. After this, insertions into a vacant entry still require an owned key to be provided.

Raw entries are useful for such exotic situations as:

  • Hash memoization
  • Deferring the creation of an owned key until it is known to be required
  • Using a search key that doesn’t work with the Borrow trait
  • Using custom comparison logic without newtype wrappers

Because raw entries provide much more low-level control, it’s much easier to put the HashMap into an inconsistent state which, while memory-safe, will cause the map to produce seemingly random results. Higher-level and more foolproof APIs like entry should be preferred when possible.

In particular, the hash used to initialized the raw entry must still be consistent with the hash of the key that is ultimately stored in the entry. This is because implementations of HashMap may need to recompute hashes when resizing, at which point only the keys are available.

Raw entries give mutable access to the keys. This must not be used to modify how the key would compare or hash, as the map will not re-evaluate where the key should go, meaning the keys may become “lost” if their location does not reflect their state. For instance, if you change a key so that the map now contains keys which compare equal, search may start acting erratically, with two keys randomly masking each other. Implementations are free to assume this doesn’t happen (within the limits of memory-safety).

§Examples
use core::hash::{BuildHasher, Hash};
use hashbrown::hash_map::{HashMap, RawEntryMut};

let mut map = HashMap::new();
map.extend([("a", 100), ("b", 200), ("c", 300)]);

fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
    use core::hash::Hasher;
    let mut state = hash_builder.build_hasher();
    key.hash(&mut state);
    state.finish()
}

// Existing key (insert and update)
match map.raw_entry_mut().from_key(&"a") {
    RawEntryMut::Vacant(_) => unreachable!(),
    RawEntryMut::Occupied(mut view) => {
        assert_eq!(view.get(), &100);
        let v = view.get_mut();
        let new_v = (*v) * 10;
        *v = new_v;
        assert_eq!(view.insert(1111), 1000);
    }
}

assert_eq!(map[&"a"], 1111);
assert_eq!(map.len(), 3);

// Existing key (take)
let hash = compute_hash(map.hasher(), &"c");
match map.raw_entry_mut().from_key_hashed_nocheck(hash, &"c") {
    RawEntryMut::Vacant(_) => unreachable!(),
    RawEntryMut::Occupied(view) => {
        assert_eq!(view.remove_entry(), ("c", 300));
    }
}
assert_eq!(map.raw_entry().from_key(&"c"), None);
assert_eq!(map.len(), 2);

// Nonexistent key (insert and update)
let key = "d";
let hash = compute_hash(map.hasher(), &key);
match map.raw_entry_mut().from_hash(hash, |q| *q == key) {
    RawEntryMut::Occupied(_) => unreachable!(),
    RawEntryMut::Vacant(view) => {
        let (k, value) = view.insert("d", 4000);
        assert_eq!((*k, *value), ("d", 4000));
        *value = 40000;
    }
}
assert_eq!(map[&"d"], 40000);
assert_eq!(map.len(), 3);

match map.raw_entry_mut().from_hash(hash, |q| *q == key) {
    RawEntryMut::Vacant(_) => unreachable!(),
    RawEntryMut::Occupied(view) => {
        assert_eq!(view.remove_entry(), ("d", 40000));
    }
}
assert_eq!(map.get(&"d"), None);
assert_eq!(map.len(), 2);
Source

pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S, A>

Creates a raw immutable entry builder for the HashMap.

Raw entries provide the lowest level of control for searching and manipulating a map. They must be manually initialized with a hash and then manually searched.

This is useful for

  • Hash memoization
  • Using a search key that doesn’t work with the Borrow trait
  • Using custom comparison logic without newtype wrappers

Unless you are in such a situation, higher-level and more foolproof APIs like get should be preferred.

Immutable raw entries have very limited use; you might instead want raw_entry_mut.

§Examples
use core::hash::{BuildHasher, Hash};
use hashbrown::HashMap;

let mut map = HashMap::new();
map.extend([("a", 100), ("b", 200), ("c", 300)]);

fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
    use core::hash::Hasher;
    let mut state = hash_builder.build_hasher();
    key.hash(&mut state);
    state.finish()
}

for k in ["a", "b", "c", "d", "e", "f"] {
    let hash = compute_hash(map.hasher(), k);
    let v = map.get(&k).cloned();
    let kv = v.as_ref().map(|v| (&k, v));

    println!("Key: {} and value: {:?}", k, v);

    assert_eq!(map.raw_entry().from_key(&k), kv);
    assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
    assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
}

Trait Implementations§

Source§

impl Component for FallbackImageFormatMsaaCache

Source§

const STORAGE_TYPE: StorageType = bevy_ecs::component::StorageType::SparseSet

A constant indicating the storage type used for this component.
Source§

type Mutability = Mutable

A marker type to assist Bevy with determining if this component is mutable, or immutable. Mutable components will have Component<Mutability = Mutable>, while immutable components will instead have Component<Mutability = Immutable>. Read more
Source§

fn register_required_components( _requiree: ComponentId, required_components: &mut RequiredComponentsRegistrator<'_, '_>, )

Registers required components. Read more
Source§

fn clone_behavior() -> ComponentCloneBehavior

Called when registering this component, allowing to override clone function (or disable cloning altogether) for this component. Read more
Source§

fn relationship_accessor() -> Option<ComponentRelationshipAccessor<FallbackImageFormatMsaaCache>>

Returns ComponentRelationshipAccessor required for working with relationships in dynamic contexts. Read more
Source§

fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_add ComponentHook for this Component if one is defined.
Source§

fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_insert ComponentHook for this Component if one is defined.
Source§

fn on_discard() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_discard ComponentHook for this Component if one is defined.
Source§

fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_remove ComponentHook for this Component if one is defined.
Source§

fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_despawn ComponentHook for this Component if one is defined.
Source§

fn map_entities<E>(_this: &mut Self, _mapper: &mut E)
where E: EntityMapper,

Maps the entities on this component using the given EntityMapper. This is used to remap entities in contexts like scenes and entity cloning. When deriving Component, this is populated by annotating fields containing entities with #[entities] Read more
Source§

const HAS_SUMMARY_TICK: bool = false

Set this constant to true if the component should track a summary tick. Read more
Source§

impl Default for FallbackImageFormatMsaaCache

Source§

fn default() -> FallbackImageFormatMsaaCache

Returns the “default value” for a type. Read more
Source§

impl Deref for FallbackImageFormatMsaaCache

Source§

type Target = HashMap<(u32, TextureFormat), GpuImage>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &<FallbackImageFormatMsaaCache as Deref>::Target

Dereferences the value.
Source§

impl DerefMut for FallbackImageFormatMsaaCache

Source§

fn deref_mut(&mut self) -> &mut <FallbackImageFormatMsaaCache as Deref>::Target

Mutably dereferences the value.
Source§

impl Resource for FallbackImageFormatMsaaCache

Auto Trait Implementations§

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<C> Bundle for C
where C: Component,

Source§

fn component_ids( components: &mut ComponentsRegistrator<'_>, ) -> impl Iterator<Item = ComponentId> + use<C>

Source§

fn get_component_ids( components: &Components, ) -> impl Iterator<Item = Option<ComponentId>>

Returns an iterator over this Bundle’s component ids. This will be None if the component has not been registered.
Source§

impl<C> BundleFromComponents for C
where C: Component,

Source§

unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> C
where F: for<'a> FnMut(&'a mut T) -> OwningPtr<'a>, C: Sized,

Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

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

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 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<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<C> DynamicBundle for C
where C: Component,

Source§

type Effect = ()

An operation on the entity that happens after inserting this bundle.
Source§

unsafe fn get_components( ptr: MovingPtr<'_, C>, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect

Moves the components out of the bundle. Read more
Source§

unsafe fn apply_effect( _ptr: MovingPtr<'_, MaybeUninit<C>>, _entity: &mut EntityWorldMut<'_>, )

Applies the after-effects of spawning this bundle. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

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> FromWorld for T
where T: Default,

Source§

fn from_world(_world: &mut World) -> T

Creates Self using default().

Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

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

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T> InitializeFromFunction<T> for T

Source§

fn initialize_from_function(f: fn() -> T) -> T

Create an instance of this type from an initialization function
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<T> IntoResult<T> for T

Source§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
Source§

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

Source§

fn into_sample(self) -> T

Source§

impl<A> Is for A
where A: Any,

Source§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
Source§

impl<T> NoneValue for T
where T: Default,

Source§

type NoneType = T

Source§

fn null_value() -> T

The none-equivalent value.
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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
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> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<C> SceneEffect for C
where C: Component,

Source§

fn apply( self, context: &mut TemplateContext<'_, '_>, bundle_writer: &mut BundleWriter<'_>, )

Applies the scene effect to the current context.
Source§

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

Source§

impl<Ret> SpawnIfAsync<(), Ret> for Ret

Source§

fn spawn(self) -> Ret

Spawn the value into the dioxus runtime if it is an async block
Source§

impl<T, O> SuperFrom<T> for O
where O: From<T>,

Source§

fn super_from(input: T) -> O

Convert from a type to another type.
Source§

impl<T, O, M> SuperInto<O, M> for T
where O: SuperFrom<T, M>,

Source§

fn super_into(self) -> O

Convert from a type to another type.
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 = !

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

fn try_from(value: U) -> Result<T, !>

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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

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

Source§

impl<T> WasmNotSendSync for T

Source§

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

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