Use EntityHashMap whenever possible (#11353)

# Objective

Fixes #11352

## Solution

- Use `EntityHashMap<Entity, T>` instead of `HashMap<Entity, T>`

---

## Changelog

Changed
- Use `EntityHashMap<Entity, T>` instead of `HashMap<Entity, T>`
whenever possible

## Migration Guide

TODO
This commit is contained in:
vero 2024-01-15 07:51:17 -08:00 committed by GitHub
parent 3d628a8191
commit 4695b82f6b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 30 additions and 30 deletions

View file

@ -33,7 +33,7 @@ use bevy_scene::Scene;
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
use bevy_tasks::IoTaskPool; use bevy_tasks::IoTaskPool;
use bevy_transform::components::Transform; use bevy_transform::components::Transform;
use bevy_utils::{HashMap, HashSet}; use bevy_utils::{EntityHashMap, HashMap, HashSet};
use gltf::{ use gltf::{
accessor::Iter, accessor::Iter,
mesh::{util::ReadIndices, Mode}, mesh::{util::ReadIndices, Mode},
@ -586,7 +586,7 @@ async fn load_gltf<'a, 'b, 'c>(
let mut err = None; let mut err = None;
let mut world = World::default(); let mut world = World::default();
let mut node_index_to_entity_map = HashMap::new(); let mut node_index_to_entity_map = HashMap::new();
let mut entity_to_skin_index_map = HashMap::new(); let mut entity_to_skin_index_map = EntityHashMap::default();
let mut scene_load_context = load_context.begin_labeled_asset(); let mut scene_load_context = load_context.begin_labeled_asset();
world world
.spawn(SpatialBundle::INHERITED_IDENTITY) .spawn(SpatialBundle::INHERITED_IDENTITY)
@ -912,7 +912,7 @@ fn load_node(
load_context: &mut LoadContext, load_context: &mut LoadContext,
settings: &GltfLoaderSettings, settings: &GltfLoaderSettings,
node_index_to_entity_map: &mut HashMap<usize, Entity>, node_index_to_entity_map: &mut HashMap<usize, Entity>,
entity_to_skin_index_map: &mut HashMap<Entity, usize>, entity_to_skin_index_map: &mut EntityHashMap<Entity, usize>,
active_camera_found: &mut bool, active_camera_found: &mut bool,
parent_transform: &Transform, parent_transform: &Transform,
) -> Result<(), GltfError> { ) -> Result<(), GltfError> {

View file

@ -11,7 +11,7 @@ use bevy_render::{
view::{InheritedVisibility, ViewVisibility, Visibility, VisibleEntities}, view::{InheritedVisibility, ViewVisibility, Visibility, VisibleEntities},
}; };
use bevy_transform::components::{GlobalTransform, Transform}; use bevy_transform::components::{GlobalTransform, Transform};
use bevy_utils::HashMap; use bevy_utils::EntityHashMap;
/// A component bundle for PBR entities with a [`Mesh`] and a [`StandardMaterial`]. /// A component bundle for PBR entities with a [`Mesh`] and a [`StandardMaterial`].
pub type PbrBundle = MaterialMeshBundle<StandardMaterial>; pub type PbrBundle = MaterialMeshBundle<StandardMaterial>;
@ -75,7 +75,7 @@ impl CubemapVisibleEntities {
pub struct CascadesVisibleEntities { pub struct CascadesVisibleEntities {
/// Map of view entity to the visible entities for each cascade frustum. /// Map of view entity to the visible entities for each cascade frustum.
#[reflect(ignore)] #[reflect(ignore)]
pub entities: HashMap<Entity, Vec<VisibleEntities>>, pub entities: EntityHashMap<Entity, Vec<VisibleEntities>>,
} }
/// A component bundle for [`PointLight`] entities. /// A component bundle for [`PointLight`] entities.

View file

@ -16,7 +16,7 @@ use bevy_render::{
view::{InheritedVisibility, RenderLayers, ViewVisibility, VisibleEntities}, view::{InheritedVisibility, RenderLayers, ViewVisibility, VisibleEntities},
}; };
use bevy_transform::components::{GlobalTransform, Transform}; use bevy_transform::components::{GlobalTransform, Transform};
use bevy_utils::{tracing::warn, HashMap}; use bevy_utils::{tracing::warn, EntityHashMap};
use crate::*; use crate::*;
@ -381,7 +381,7 @@ impl From<CascadeShadowConfigBuilder> for CascadeShadowConfig {
#[reflect(Component)] #[reflect(Component)]
pub struct Cascades { pub struct Cascades {
/// Map from a view to the configuration of each of its [`Cascade`]s. /// Map from a view to the configuration of each of its [`Cascade`]s.
pub(crate) cascades: HashMap<Entity, Vec<Cascade>>, pub(crate) cascades: EntityHashMap<Entity, Vec<Cascade>>,
} }
#[derive(Clone, Debug, Default, Reflect)] #[derive(Clone, Debug, Default, Reflect)]

View file

@ -18,7 +18,7 @@ use bevy_transform::{components::GlobalTransform, prelude::Transform};
use bevy_utils::{ use bevy_utils::{
nonmax::NonMaxU32, nonmax::NonMaxU32,
tracing::{error, warn}, tracing::{error, warn},
HashMap, EntityHashMap,
}; };
use std::{hash::Hash, num::NonZeroU64, ops::Range}; use std::{hash::Hash, num::NonZeroU64, ops::Range};
@ -47,7 +47,7 @@ pub struct ExtractedDirectionalLight {
shadow_depth_bias: f32, shadow_depth_bias: f32,
shadow_normal_bias: f32, shadow_normal_bias: f32,
cascade_shadow_config: CascadeShadowConfig, cascade_shadow_config: CascadeShadowConfig,
cascades: HashMap<Entity, Vec<Cascade>>, cascades: EntityHashMap<Entity, Vec<Cascade>>,
render_layers: RenderLayers, render_layers: RenderLayers,
} }
@ -550,7 +550,7 @@ pub const CLUSTERED_FORWARD_STORAGE_BUFFER_COUNT: u32 = 3;
#[derive(Resource)] #[derive(Resource)]
pub struct GlobalLightMeta { pub struct GlobalLightMeta {
pub gpu_point_lights: GpuPointLights, pub gpu_point_lights: GpuPointLights,
pub entity_to_index: HashMap<Entity, usize>, pub entity_to_index: EntityHashMap<Entity, usize>,
} }
impl FromWorld for GlobalLightMeta { impl FromWorld for GlobalLightMeta {
@ -567,7 +567,7 @@ impl GlobalLightMeta {
pub fn new(buffer_binding_type: BufferBindingType) -> Self { pub fn new(buffer_binding_type: BufferBindingType) -> Self {
Self { Self {
gpu_point_lights: GpuPointLights::new(buffer_binding_type), gpu_point_lights: GpuPointLights::new(buffer_binding_type),
entity_to_index: HashMap::default(), entity_to_index: EntityHashMap::default(),
} }
} }
} }

View file

@ -3,7 +3,7 @@ use std::borrow::Borrow;
use bevy_ecs::{component::Component, prelude::Entity, reflect::ReflectComponent}; use bevy_ecs::{component::Component, prelude::Entity, reflect::ReflectComponent};
use bevy_math::{Affine3A, Mat3A, Mat4, Vec3, Vec3A, Vec4, Vec4Swizzles}; use bevy_math::{Affine3A, Mat3A, Mat4, Vec3, Vec3A, Vec4, Vec4Swizzles};
use bevy_reflect::Reflect; use bevy_reflect::Reflect;
use bevy_utils::HashMap; use bevy_utils::EntityHashMap;
/// An axis-aligned bounding box, defined by: /// An axis-aligned bounding box, defined by:
/// - a center, /// - a center,
@ -323,7 +323,7 @@ impl CubemapFrusta {
#[reflect(Component)] #[reflect(Component)]
pub struct CascadesFrusta { pub struct CascadesFrusta {
#[reflect(ignore)] #[reflect(ignore)]
pub frusta: HashMap<Entity, Vec<Frustum>>, pub frusta: EntityHashMap<Entity, Vec<Frustum>>,
} }
#[cfg(test)] #[cfg(test)]

View file

@ -8,7 +8,7 @@ use crate::{
}; };
use bevy_app::{App, Plugin}; use bevy_app::{App, Plugin};
use bevy_ecs::prelude::*; use bevy_ecs::prelude::*;
use bevy_utils::{default, tracing::debug, HashMap, HashSet}; use bevy_utils::{default, tracing::debug, EntityHashMap, HashSet};
use bevy_window::{ use bevy_window::{
CompositeAlphaMode, PresentMode, PrimaryWindow, RawHandleWrapper, Window, WindowClosed, CompositeAlphaMode, PresentMode, PrimaryWindow, RawHandleWrapper, Window, WindowClosed,
}; };
@ -89,11 +89,11 @@ impl ExtractedWindow {
#[derive(Default, Resource)] #[derive(Default, Resource)]
pub struct ExtractedWindows { pub struct ExtractedWindows {
pub primary: Option<Entity>, pub primary: Option<Entity>,
pub windows: HashMap<Entity, ExtractedWindow>, pub windows: EntityHashMap<Entity, ExtractedWindow>,
} }
impl Deref for ExtractedWindows { impl Deref for ExtractedWindows {
type Target = HashMap<Entity, ExtractedWindow>; type Target = EntityHashMap<Entity, ExtractedWindow>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.windows &self.windows
@ -199,7 +199,7 @@ struct SurfaceData {
#[derive(Resource, Default)] #[derive(Resource, Default)]
pub struct WindowSurfaces { pub struct WindowSurfaces {
surfaces: HashMap<Entity, SurfaceData>, surfaces: EntityHashMap<Entity, SurfaceData>,
/// List of windows that we have already called the initial `configure_surface` for /// List of windows that we have already called the initial `configure_surface` for
configured_windows: HashSet<Entity>, configured_windows: HashSet<Entity>,
} }

View file

@ -5,7 +5,7 @@ use bevy_asset::{load_internal_asset, Handle};
use bevy_ecs::prelude::*; use bevy_ecs::prelude::*;
use bevy_log::{error, info, info_span}; use bevy_log::{error, info, info_span};
use bevy_tasks::AsyncComputeTaskPool; use bevy_tasks::AsyncComputeTaskPool;
use bevy_utils::HashMap; use bevy_utils::EntityHashMap;
use std::sync::Mutex; use std::sync::Mutex;
use thiserror::Error; use thiserror::Error;
use wgpu::{ use wgpu::{
@ -33,7 +33,7 @@ pub type ScreenshotFn = Box<dyn FnOnce(Image) + Send + Sync>;
#[derive(Resource, Default)] #[derive(Resource, Default)]
pub struct ScreenshotManager { pub struct ScreenshotManager {
// this is in a mutex to enable extraction with only an immutable reference // this is in a mutex to enable extraction with only an immutable reference
pub(crate) callbacks: Mutex<HashMap<Entity, ScreenshotFn>>, pub(crate) callbacks: Mutex<EntityHashMap<Entity, ScreenshotFn>>,
} }
#[derive(Error, Debug)] #[derive(Error, Debug)]

View file

@ -15,7 +15,7 @@ use bevy_hierarchy::{Children, Parent};
use bevy_log::warn; use bevy_log::warn;
use bevy_math::Vec2; use bevy_math::Vec2;
use bevy_transform::components::Transform; use bevy_transform::components::Transform;
use bevy_utils::{default, HashMap}; use bevy_utils::{default, EntityHashMap};
use bevy_window::{PrimaryWindow, Window, WindowResolution, WindowScaleFactorChanged}; use bevy_window::{PrimaryWindow, Window, WindowResolution, WindowScaleFactorChanged};
use std::fmt; use std::fmt;
use taffy::Taffy; use taffy::Taffy;
@ -50,14 +50,14 @@ struct RootNodePair {
#[derive(Resource)] #[derive(Resource)]
pub struct UiSurface { pub struct UiSurface {
entity_to_taffy: HashMap<Entity, taffy::node::Node>, entity_to_taffy: EntityHashMap<Entity, taffy::node::Node>,
window_roots: HashMap<Entity, Vec<RootNodePair>>, window_roots: EntityHashMap<Entity, Vec<RootNodePair>>,
taffy: Taffy, taffy: Taffy,
} }
fn _assert_send_sync_ui_surface_impl_safe() { fn _assert_send_sync_ui_surface_impl_safe() {
fn _assert_send_sync<T: Send + Sync>() {} fn _assert_send_sync<T: Send + Sync>() {}
_assert_send_sync::<HashMap<Entity, taffy::node::Node>>(); _assert_send_sync::<EntityHashMap<Entity, taffy::node::Node>>();
_assert_send_sync::<Taffy>(); _assert_send_sync::<Taffy>();
_assert_send_sync::<UiSurface>(); _assert_send_sync::<UiSurface>();
} }

View file

@ -22,16 +22,16 @@ use bevy_ecs::{
system::{NonSend, NonSendMut, Query, Res, ResMut, Resource}, system::{NonSend, NonSendMut, Query, Res, ResMut, Resource},
}; };
use bevy_hierarchy::{Children, Parent}; use bevy_hierarchy::{Children, Parent};
use bevy_utils::HashMap; use bevy_utils::EntityHashMap;
use bevy_window::{PrimaryWindow, Window, WindowClosed}; use bevy_window::{PrimaryWindow, Window, WindowClosed};
/// Maps window entities to their `AccessKit` [`Adapter`]s. /// Maps window entities to their `AccessKit` [`Adapter`]s.
#[derive(Default, Deref, DerefMut)] #[derive(Default, Deref, DerefMut)]
pub struct AccessKitAdapters(pub HashMap<Entity, Adapter>); pub struct AccessKitAdapters(pub EntityHashMap<Entity, Adapter>);
/// Maps window entities to their respective [`WinitActionHandler`]s. /// Maps window entities to their respective [`WinitActionHandler`]s.
#[derive(Resource, Default, Deref, DerefMut)] #[derive(Resource, Default, Deref, DerefMut)]
pub struct WinitActionHandlers(pub HashMap<Entity, WinitActionHandler>); pub struct WinitActionHandlers(pub EntityHashMap<Entity, WinitActionHandler>);
/// Forwards `AccessKit` [`ActionRequest`]s from winit to an event channel. /// Forwards `AccessKit` [`ActionRequest`]s from winit to an event channel.
#[derive(Clone, Default, Deref, DerefMut)] #[derive(Clone, Default, Deref, DerefMut)]

View file

@ -9,7 +9,7 @@ use bevy_ecs::{
}; };
use bevy_utils::{ use bevy_utils::{
tracing::{error, info, warn}, tracing::{error, info, warn},
HashMap, EntityHashMap,
}; };
use bevy_window::{RawHandleWrapper, Window, WindowClosed, WindowCreated}; use bevy_window::{RawHandleWrapper, Window, WindowClosed, WindowCreated};
use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle}; use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle};
@ -87,7 +87,7 @@ pub(crate) fn create_windows<'a>(
/// Cache for closing windows so we can get better debug information. /// Cache for closing windows so we can get better debug information.
#[derive(Debug, Clone, Resource)] #[derive(Debug, Clone, Resource)]
pub struct WindowTitleCache(HashMap<Entity, String>); pub struct WindowTitleCache(EntityHashMap<Entity, String>);
pub(crate) fn despawn_windows( pub(crate) fn despawn_windows(
mut closed: RemovedComponents<Window>, mut closed: RemovedComponents<Window>,

View file

@ -7,7 +7,7 @@ use bevy_a11y::{
}; };
use bevy_ecs::entity::Entity; use bevy_ecs::entity::Entity;
use bevy_utils::{tracing::warn, HashMap}; use bevy_utils::{tracing::warn, EntityHashMap, HashMap};
use bevy_window::{CursorGrabMode, Window, WindowMode, WindowPosition, WindowResolution}; use bevy_window::{CursorGrabMode, Window, WindowMode, WindowPosition, WindowResolution};
use winit::{ use winit::{
@ -27,7 +27,7 @@ pub struct WinitWindows {
/// Stores [`winit`] windows by window identifier. /// Stores [`winit`] windows by window identifier.
pub windows: HashMap<winit::window::WindowId, winit::window::Window>, pub windows: HashMap<winit::window::WindowId, winit::window::Window>,
/// Maps entities to `winit` window identifiers. /// Maps entities to `winit` window identifiers.
pub entity_to_winit: HashMap<Entity, winit::window::WindowId>, pub entity_to_winit: EntityHashMap<Entity, winit::window::WindowId>,
/// Maps `winit` window identifiers to entities. /// Maps `winit` window identifiers to entities.
pub winit_to_entity: HashMap<winit::window::WindowId, Entity>, pub winit_to_entity: HashMap<winit::window::WindowId, Entity>,
// Many `winit` window functions (e.g. `set_window_icon`) can only be called on the main thread. // Many `winit` window functions (e.g. `set_window_icon`) can only be called on the main thread.