Skip to content

use handleid in renderer instead of a weak handle #4016

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions crates/bevy_asset/src/asset_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ use crate::{
use anyhow::Result;
use bevy_ecs::system::{Res, ResMut};
use bevy_log::warn;
use bevy_reflect::UniqueAssetId;
use bevy_tasks::TaskPool;
use bevy_utils::{Entry, HashMap, Uuid};
use bevy_utils::{Entry, HashMap};
use crossbeam_channel::TryRecvError;
use parking_lot::{Mutex, RwLock};
use std::{path::Path, sync::Arc};
Expand Down Expand Up @@ -52,7 +53,7 @@ pub struct AssetServerInternal {
pub(crate) asset_io: Box<dyn AssetIo>,
pub(crate) asset_ref_counter: AssetRefCounter,
pub(crate) asset_sources: Arc<RwLock<HashMap<SourcePathId, SourceInfo>>>,
pub(crate) asset_lifecycles: Arc<RwLock<HashMap<Uuid, Box<dyn AssetLifecycle>>>>,
pub(crate) asset_lifecycles: Arc<RwLock<HashMap<UniqueAssetId, Box<dyn AssetLifecycle>>>>,
loaders: RwLock<Vec<Arc<dyn AssetLoader>>>,
extension_to_loader_index: RwLock<HashMap<String, usize>>,
handle_to_path: Arc<RwLock<HashMap<HandleId, AssetPath<'static>>>>,
Expand Down Expand Up @@ -880,7 +881,7 @@ mod test {
assert!(server.get_handle_path(&handle).is_none());

// invalid HandleId
let invalid_id = HandleId::new(Uuid::new_v4(), 42);
let invalid_id = HandleId::new(0, 42);
assert!(server.get_handle_path(invalid_id).is_none());

// invalid AssetPath
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::{Asset, Assets};
use bevy_app::prelude::*;
use bevy_diagnostic::{Diagnostic, DiagnosticId, Diagnostics, MAX_DIAGNOSTIC_NAME_WIDTH};
use bevy_ecs::system::{Res, ResMut};
use bevy_reflect::Uuid;

/// Adds "asset count" diagnostic to an App
pub struct AssetCountDiagnosticsPlugin<T: Asset> {
Expand All @@ -25,7 +26,7 @@ impl<T: Asset> Plugin for AssetCountDiagnosticsPlugin<T> {

impl<T: Asset> AssetCountDiagnosticsPlugin<T> {
pub fn diagnostic_id() -> DiagnosticId {
DiagnosticId(T::TYPE_UUID)
DiagnosticId(Uuid::from_u128(T::TYPE_UUID as u128))
}

pub fn setup_system(mut diagnostics: ResMut<Diagnostics>) {
Expand Down
9 changes: 4 additions & 5 deletions crates/bevy_asset/src/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ use crate::{
Asset, Assets,
};
use bevy_ecs::{component::Component, reflect::ReflectComponent};
use bevy_reflect::{FromReflect, Reflect, ReflectDeserialize};
use bevy_utils::Uuid;
use bevy_reflect::{FromReflect, Reflect, ReflectDeserialize, UniqueAssetId};
use crossbeam_channel::{Receiver, Sender};
use serde::{Deserialize, Serialize};

Expand All @@ -32,7 +31,7 @@ use serde::{Deserialize, Serialize};
)]
#[reflect_value(Serialize, Deserialize, PartialEq, Hash)]
pub enum HandleId {
Id(Uuid, u64),
Id(UniqueAssetId, u64),
AssetPathId(AssetPathId),
}

Expand Down Expand Up @@ -60,7 +59,7 @@ impl HandleId {
}

#[inline]
pub const fn new(type_uuid: Uuid, id: u64) -> Self {
pub const fn new(type_uuid: UniqueAssetId, id: u64) -> Self {
HandleId::Id(type_uuid, id)
}
}
Expand Down Expand Up @@ -306,7 +305,7 @@ pub struct HandleUntyped {
}

impl HandleUntyped {
pub const fn weak_from_u64(uuid: Uuid, id: u64) -> Self {
pub const fn weak_from_u64(uuid: UniqueAssetId, id: u64) -> Self {
Self {
id: HandleId::new(uuid, id),
handle_type: HandleType::Weak,
Expand Down
9 changes: 5 additions & 4 deletions crates/bevy_asset/src/info.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::{path::AssetPath, LabelId};
use bevy_utils::{HashMap, HashSet, Uuid};
use bevy_reflect::UniqueAssetId;
use bevy_utils::{HashMap, HashSet};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

Expand All @@ -12,15 +13,15 @@ pub struct SourceMeta {
pub struct AssetMeta {
pub label: Option<String>,
pub dependencies: Vec<AssetPath<'static>>,
pub type_uuid: Uuid,
pub type_uuid: UniqueAssetId,
}

/// Info about a specific asset, such as its path and its current load state
#[derive(Clone, Debug)]
pub struct SourceInfo {
pub meta: Option<SourceMeta>,
pub path: PathBuf,
pub asset_types: HashMap<LabelId, Uuid>,
pub asset_types: HashMap<LabelId, UniqueAssetId>,
pub load_state: LoadState,
pub committed_assets: HashSet<LabelId>,
pub version: usize,
Expand All @@ -33,7 +34,7 @@ impl SourceInfo {
})
}

pub fn get_asset_type(&self, label_id: LabelId) -> Option<Uuid> {
pub fn get_asset_type(&self, label_id: LabelId) -> Option<UniqueAssetId> {
self.asset_types.get(&label_id).cloned()
}
}
Expand Down
6 changes: 3 additions & 3 deletions crates/bevy_pbr/src/material.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ impl<M: SpecializedMaterial, const I: usize> EntityRenderCommand for SetMaterial
pass: &mut TrackedRenderPass<'w>,
) -> RenderCommandResult {
let material_handle = query.get(item).unwrap();
let material = materials.into_inner().get(material_handle).unwrap();
let material = materials.into_inner().get(&material_handle.id).unwrap();
pass.set_bind_group(
I,
M::bind_group(material),
Expand Down Expand Up @@ -344,8 +344,8 @@ pub fn queue_material_meshes<M: SpecializedMaterial>(
if let Ok((material_handle, mesh_handle, mesh_uniform)) =
material_meshes.get(*visible_entity)
{
if let Some(material) = render_materials.get(material_handle) {
if let Some(mesh) = render_meshes.get(mesh_handle) {
if let Some(material) = render_materials.get(&material_handle.id) {
if let Some(mesh) = render_meshes.get(&mesh_handle.id) {
let mut mesh_key =
MeshPipelineKey::from_primitive_topology(mesh.primitive_topology)
| msaa_key;
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_pbr/src/render/light.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1070,7 +1070,7 @@ pub fn queue_shadows(
// so no meshes will be queued
for entity in visible_entities.iter().copied() {
if let Ok(mesh_handle) = casting_meshes.get(entity) {
if let Some(mesh) = render_meshes.get(mesh_handle) {
if let Some(mesh) = render_meshes.get(&mesh_handle.id) {
let key =
ShadowPipelineKey::from_primitive_topology(mesh.primitive_topology);
let pipeline_id = pipelines.specialize(
Expand Down
4 changes: 2 additions & 2 deletions crates/bevy_pbr/src/render/mesh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ impl MeshPipeline {
handle_option: &Option<Handle<Image>>,
) -> Option<(&'a TextureView, &'a Sampler)> {
if let Some(handle) = handle_option {
let gpu_image = gpu_images.get(handle)?;
let gpu_image = gpu_images.get(&handle.id)?;
Some((&gpu_image.texture_view, &gpu_image.sampler))
} else {
Some((
Expand Down Expand Up @@ -669,7 +669,7 @@ impl EntityRenderCommand for DrawMesh {
pass: &mut TrackedRenderPass<'w>,
) -> RenderCommandResult {
let mesh_handle = mesh_query.get(item).unwrap();
if let Some(gpu_mesh) = meshes.into_inner().get(mesh_handle) {
if let Some(gpu_mesh) = meshes.into_inner().get(&mesh_handle.id) {
pass.set_vertex_buffer(0, gpu_mesh.vertex_buffer.slice(..));
match &gpu_mesh.buffer_info {
GpuBufferInfo::Indexed {
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_pbr/src/wireframe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ fn queue_wireframes(

let add_render_phase =
|(entity, mesh_handle, mesh_uniform): (Entity, &Handle<Mesh>, &MeshUniform)| {
if let Some(mesh) = render_meshes.get(mesh_handle) {
if let Some(mesh) = render_meshes.get(&mesh_handle.id) {
let key = msaa_key
| MeshPipelineKey::from_primitive_topology(mesh.primitive_topology);
let pipeline_id = specialized_pipelines.specialize(
Expand Down
15 changes: 7 additions & 8 deletions crates/bevy_reflect/bevy_reflect_derive/src/type_uuid.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
extern crate proc_macro;

use std::{collections::hash_map::DefaultHasher, hash::Hasher};

use bevy_macro_utils::BevyManifest;
use quote::{quote, ToTokens};
use syn::*;
Expand Down Expand Up @@ -50,17 +52,14 @@ pub fn type_uuid_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStre

let uuid =
uuid.expect("No `#[uuid = \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"` attribute found.");
let bytes = uuid
.as_bytes()
.iter()
.map(|byte| format!("{:#X}", byte))
.map(|byte_str| syn::parse_str::<LitInt>(&byte_str).unwrap());

let mut s = DefaultHasher::new();
std::hash::Hash::hash(&uuid, &mut s);
let unique_id = s.finish();

let gen = quote! {
impl #bevy_reflect_path::TypeUuid for #name {
const TYPE_UUID: #bevy_reflect_path::Uuid = #bevy_reflect_path::Uuid::from_bytes([
#( #bytes ),*
]);
const TYPE_UUID: #bevy_reflect_path::UniqueAssetId = #unique_id;
}
};
gen.into()
Expand Down
8 changes: 5 additions & 3 deletions crates/bevy_reflect/src/type_uuid.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
pub use bevy_reflect_derive::TypeUuid;
pub use bevy_utils::Uuid;

pub type UniqueAssetId = u64;

/// A trait for types with a statically associated UUID.
pub trait TypeUuid {
const TYPE_UUID: Uuid;
const TYPE_UUID: UniqueAssetId;
}

/// A trait for types with an associated UUID.
pub trait TypeUuidDynamic {
fn type_uuid(&self) -> Uuid;
fn type_uuid(&self) -> UniqueAssetId;
fn type_name(&self) -> &'static str;
}

Expand All @@ -17,7 +19,7 @@ where
T: TypeUuid,
{
/// Returns the UUID associated with this value's type.
fn type_uuid(&self) -> Uuid {
fn type_uuid(&self) -> UniqueAssetId {
Self::TYPE_UUID
}

Expand Down
6 changes: 3 additions & 3 deletions crates/bevy_render/src/camera/camera.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ impl RenderTarget {
RenderTarget::Window(window_id) => windows
.get(window_id)
.and_then(|window| window.swap_chain_texture.as_ref()),
RenderTarget::Image(image_handle) => {
images.get(image_handle).map(|image| &image.texture_view)
}
RenderTarget::Image(image_handle) => images
.get(&image_handle.id)
.map(|image| &image.texture_view),
}
}
pub fn get_physical_size(&self, windows: &Windows, images: &Assets<Image>) -> Option<UVec2> {
Expand Down
22 changes: 11 additions & 11 deletions crates/bevy_render/src/render_asset.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{RenderApp, RenderStage};
use bevy_app::{App, Plugin};
use bevy_asset::{Asset, AssetEvent, Assets, Handle};
use bevy_asset::{Asset, AssetEvent, Assets, HandleId};
use bevy_ecs::{
prelude::*,
system::{lifetimeless::*, RunSystem, SystemParam, SystemParamItem},
Expand Down Expand Up @@ -68,8 +68,8 @@ impl<A: RenderAsset> Plugin for RenderAssetPlugin<A> {

/// Temporarily stores the extracted and removed assets of the current frame.
pub struct ExtractedAssets<A: RenderAsset> {
extracted: Vec<(Handle<A>, A::ExtractedAsset)>,
removed: Vec<Handle<A>>,
extracted: Vec<(HandleId, A::ExtractedAsset)>,
removed: Vec<HandleId>,
}

impl<A: RenderAsset> Default for ExtractedAssets<A> {
Expand All @@ -83,7 +83,7 @@ impl<A: RenderAsset> Default for ExtractedAssets<A> {

/// Stores all GPU representations ([`RenderAsset::PreparedAssets`](RenderAsset::PreparedAsset))
/// of [`RenderAssets`](RenderAsset) as long as they exist.
pub type RenderAssets<A> = HashMap<Handle<A>, <A as RenderAsset>::PreparedAsset>;
pub type RenderAssets<A> = HashMap<HandleId, <A as RenderAsset>::PreparedAsset>;

/// This system extracts all crated or modified assets of the corresponding [`RenderAsset`] type
/// into the "render world".
Expand All @@ -97,26 +97,26 @@ fn extract_render_asset<A: RenderAsset>(
for event in events.iter() {
match event {
AssetEvent::Created { handle } => {
changed_assets.insert(handle);
changed_assets.insert(handle.id);
}
AssetEvent::Modified { handle } => {
changed_assets.insert(handle);
changed_assets.insert(handle.id);
}
AssetEvent::Removed { handle } => {
changed_assets.remove(handle);
removed.push(handle.clone_weak());
changed_assets.remove(&handle.id);
removed.push(handle.id);
}
}
}

let mut extracted_assets = Vec::new();
for handle in changed_assets.drain() {
if let Some(asset) = assets.get(handle) {
extracted_assets.push((handle.clone_weak(), asset.extract_asset()));
extracted_assets.push((handle, asset.extract_asset()));
}
}

commands.insert_resource(ExtractedAssets {
commands.insert_resource(ExtractedAssets::<A> {
extracted: extracted_assets,
removed,
});
Expand All @@ -133,7 +133,7 @@ pub type RenderAssetParams<R> = (
// TODO: consider storing inside system?
/// All assets that should be prepared next frame.
pub struct PrepareNextFrameAssets<A: RenderAsset> {
assets: Vec<(Handle<A>, A::ExtractedAsset)>,
assets: Vec<(HandleId, A::ExtractedAsset)>,
}

impl<A: RenderAsset> Default for PrepareNextFrameAssets<A> {
Expand Down
6 changes: 3 additions & 3 deletions crates/bevy_sprite/src/mesh2d/material.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ impl<M: SpecializedMaterial2d, const I: usize> EntityRenderCommand
pass: &mut TrackedRenderPass<'w>,
) -> RenderCommandResult {
let material2d_handle = query.get(item).unwrap();
let material2d = materials.into_inner().get(material2d_handle).unwrap();
let material2d = materials.into_inner().get(&material2d_handle.id).unwrap();
pass.set_bind_group(
I,
M::bind_group(material2d),
Expand Down Expand Up @@ -313,8 +313,8 @@ pub fn queue_material2d_meshes<M: SpecializedMaterial2d>(
if let Ok((material2d_handle, mesh2d_handle, mesh2d_uniform)) =
material2d_meshes.get(*visible_entity)
{
if let Some(material2d) = render_materials.get(material2d_handle) {
if let Some(mesh) = render_meshes.get(&mesh2d_handle.0) {
if let Some(material2d) = render_materials.get(&material2d_handle.id) {
if let Some(mesh) = render_meshes.get(&mesh2d_handle.0.id) {
let mesh_key = msaa_key
| Mesh2dPipelineKey::from_primitive_topology(mesh.primitive_topology);

Expand Down
4 changes: 2 additions & 2 deletions crates/bevy_sprite/src/mesh2d/mesh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ impl Mesh2dPipeline {
handle_option: &Option<Handle<Image>>,
) -> Option<(&'a TextureView, &'a Sampler)> {
if let Some(handle) = handle_option {
let gpu_image = gpu_images.get(handle)?;
let gpu_image = gpu_images.get(&handle.id)?;
Some((&gpu_image.texture_view, &gpu_image.sampler))
} else {
Some((
Expand Down Expand Up @@ -441,7 +441,7 @@ impl EntityRenderCommand for DrawMesh2d {
pass: &mut TrackedRenderPass<'w>,
) -> RenderCommandResult {
let mesh_handle = &mesh2d_query.get(item).unwrap().0;
if let Some(gpu_mesh) = meshes.into_inner().get(mesh_handle) {
if let Some(gpu_mesh) = meshes.into_inner().get(&mesh_handle.id) {
pass.set_vertex_buffer(0, gpu_mesh.vertex_buffer.slice(..));
match &gpu_mesh.buffer_info {
GpuBufferInfo::Indexed {
Expand Down
7 changes: 2 additions & 5 deletions crates/bevy_sprite/src/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use bevy_ecs::{
system::{lifetimeless::*, SystemParamItem},
};
use bevy_math::{const_vec2, Vec2};
use bevy_reflect::Uuid;
use bevy_render::{
color::Color,
render_asset::RenderAssets,
Expand Down Expand Up @@ -409,7 +408,7 @@ pub fn queue_sprites(

// Impossible starting values that will be replaced on the first iteration
let mut current_batch = SpriteBatch {
image_handle_id: HandleId::Id(Uuid::nil(), u64::MAX),
image_handle_id: HandleId::Id(u64::MAX, u64::MAX),
colored: false,
};
let mut current_batch_entity = Entity::from_raw(u32::MAX);
Expand All @@ -426,9 +425,7 @@ pub fn queue_sprites(
};
if new_batch != current_batch {
// Set-up a new possible batch
if let Some(gpu_image) =
gpu_images.get(&Handle::weak(new_batch.image_handle_id))
{
if let Some(gpu_image) = gpu_images.get(&new_batch.image_handle_id) {
current_batch = new_batch;
current_image_size = Vec2::new(gpu_image.size.width, gpu_image.size.height);
current_batch_entity = commands.spawn_bundle((current_batch,)).id();
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_ui/src/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,7 @@ pub fn queue_uinodes(
.values
.entry(batch.image.clone_weak())
.or_insert_with(|| {
let gpu_image = gpu_images.get(&batch.image).unwrap();
let gpu_image = gpu_images.get(&batch.image.id).unwrap();
render_device.create_bind_group(&BindGroupDescriptor {
entries: &[
BindGroupEntry {
Expand Down
2 changes: 1 addition & 1 deletion examples/2d/mesh2d_manual.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ pub fn queue_colored_mesh2d(
if let Ok((mesh2d_handle, mesh2d_uniform)) = colored_mesh2d.get(*visible_entity) {
// Get our specialized pipeline
let mut mesh2d_key = mesh_key;
if let Some(mesh) = render_meshes.get(&mesh2d_handle.0) {
if let Some(mesh) = render_meshes.get(&mesh2d_handle.0.id) {
mesh2d_key |=
Mesh2dPipelineKey::from_primitive_topology(mesh.primitive_topology);
}
Expand Down
Loading