From 2a8304eef3348007dc12f045e673bfef38e73e94 Mon Sep 17 00:00:00 2001 From: sagudev <16504129+sagudev@users.noreply.github.com> Date: Mon, 6 Jul 2026 14:36:06 +0200 Subject: [PATCH] [core] Move validity into `Arc` Signed-off-by: sagudev <16504129+sagudev@users.noreply.github.com> --- player/src/lib.rs | 4 +- wgpu-core/src/binding_model.rs | 65 +++++++-- wgpu-core/src/command/bundle.rs | 22 ++- wgpu-core/src/command/compute.rs | 22 ++- wgpu-core/src/command/draw.rs | 4 + wgpu-core/src/command/pass.rs | 8 +- wgpu-core/src/command/render.rs | 27 ++-- wgpu-core/src/device/global.rs | 223 ++++++++++++------------------- wgpu-core/src/device/resource.rs | 59 ++++++-- wgpu-core/src/hub.rs | 5 +- 10 files changed, 257 insertions(+), 182 deletions(-) diff --git a/player/src/lib.rs b/player/src/lib.rs index f7ca36636..47d1c5d56 100644 --- a/player/src/lib.rs +++ b/player/src/lib.rs @@ -229,9 +229,7 @@ impl Player { } Action::CreateBindGroup(id, desc) => { let resolved_desc = self.resolve_bind_group_descriptor(desc); - let bind_group = device - .create_bind_group(resolved_desc) - .expect("create_bind_group error"); + let (bind_group, _error) = device.create_bind_group(&resolved_desc); self.bind_groups.insert(id, bind_group); } Action::DropBindGroup(id) => { diff --git a/wgpu-core/src/binding_model.rs b/wgpu-core/src/binding_model.rs index 576357d25..70d6f7fa5 100644 --- a/wgpu-core/src/binding_model.rs +++ b/wgpu-core/src/binding_model.rs @@ -18,14 +18,16 @@ use serde::Serialize; use wgt::error::{ErrorType, WebGpuError}; use crate::{ + api_log, device::{bgl, Device, DeviceError, MissingDownlevelFlags, MissingFeatures}, id::{BindGroupLayoutId, BufferId, ExternalTextureId, SamplerId, TextureViewId, TlasId}, init_tracker::{BufferInitTrackerAction, TextureInitTrackerAction}, pipeline::{ComputePipeline, RenderPipeline}, resource::{ - Buffer, DestroyedResourceError, ExternalTexture, InvalidResourceError, Labeled, - MissingBufferUsageError, MissingTextureUsageError, RawResourceAccess, ResourceErrorIdent, - ResourceState, Sampler, TextureView, Tlas, TrackingData, + Buffer, DestroyedResourceError, ExternalTexture, InvalidOrDestroyedResourceError, + InvalidResourceError, Labeled, MissingBufferUsageError, MissingTextureUsageError, + RawResourceAccess, ResourceErrorIdent, ResourceState, Sampler, TextureView, Tlas, + TrackingData, }, resource_log, snatch::{SnatchGuard, Snatchable}, @@ -1334,8 +1336,13 @@ pub(crate) struct BindGroupLateBufferBindingInfo { } #[derive(Debug)] -pub struct BindGroup { +pub(crate) struct BindGroupState { pub(crate) raw: Snatchable>, +} + +#[derive(Debug)] +pub struct BindGroup { + pub(crate) state: ResourceState, pub(crate) device: Arc, pub(crate) layout: Arc, /// The `label` from the descriptor used to create the resource. @@ -1352,8 +1359,19 @@ pub struct BindGroup { } impl Drop for BindGroup { + #[allow(trivial_casts)] fn drop(&mut self) { - if let Some(raw) = self.raw.take() { + profiling::scope!("BindGroup::drop"); + api_log!("BindGroup::drop {:?}", self as *const _); + #[cfg(feature = "trace")] + if let Some(t) = self.device.trace.lock().as_mut() { + use crate::device::trace::{to_trace, Action}; + t.add(Action::DropBindGroup(unsafe { to_trace(self) })); + } + let ResourceState::Valid(state) = &mut self.state else { + return; + }; + if let Some(raw) = state.raw.take() { resource_log!("Destroy raw {}", self.error_ident()); unsafe { self.device.raw().destroy_bind_group(raw); @@ -1366,7 +1384,7 @@ impl BindGroup { pub(crate) fn try_raw<'a>( &'a self, guard: &'a SnatchGuard, - ) -> Result<&'a dyn hal::DynBindGroup, DestroyedResourceError> { + ) -> Result<&'a dyn hal::DynBindGroup, InvalidOrDestroyedResourceError> { for buffer in self.used.buffers.used_resources() { buffer.try_raw(guard)?; } @@ -1374,10 +1392,41 @@ impl BindGroup { texture.try_raw(guard)?; } - self.raw + self.state()? + .raw .get(guard) .map(|raw| raw.as_ref()) - .ok_or_else(|| DestroyedResourceError(self.error_ident())) + .ok_or_else(|| DestroyedResourceError(self.error_ident()).into()) + } + + pub(crate) fn state(&self) -> Result<&BindGroupState, InvalidResourceError> { + let ResourceState::Valid(state) = &self.state else { + return Err(InvalidResourceError(self.error_ident())); + }; + Ok(state) + } + + pub(crate) fn check_is_valid(&self) -> Result<(), InvalidResourceError> { + self.state().map(|_| ()) + } + + pub(crate) fn invalid( + device: Arc, + label: String, + layout: Arc, + ) -> Arc { + Arc::new(Self { + state: ResourceState::Invalid, + layout, + label, + tracking_data: TrackingData::new(device.tracker_indices.bind_groups.clone()), + used: BindGroupStates::new(), + buffer_init_actions: Vec::new(), + texture_init_actions: Vec::new(), + dynamic_binding_info: Vec::new(), + late_buffer_binding_infos: Vec::new(), + device, + }) } pub(crate) fn validate_dynamic_bindings( diff --git a/wgpu-core/src/command/bundle.rs b/wgpu-core/src/command/bundle.rs index ab82a6633..ddd38824e 100644 --- a/wgpu-core/src/command/bundle.rs +++ b/wgpu-core/src/command/bundle.rs @@ -117,8 +117,8 @@ use crate::{ init_tracker::{BufferInitTrackerAction, MemoryInitKind, TextureInitTrackerAction}, pipeline::{PipelineFlags, RenderPipeline}, resource::{ - Buffer, DestroyedResourceError, Fallible, InvalidResourceError, Labeled, ParentDevice, - RawResourceAccess, ResourceState, TrackingData, + Buffer, DestroyedResourceError, InvalidOrDestroyedResourceError, InvalidResourceError, + Labeled, ParentDevice, RawResourceAccess, ResourceState, TrackingData, }, resource_log, snatch::SnatchGuard, @@ -842,7 +842,7 @@ impl RenderBundleEncoder { fn set_bind_group( state: &mut State, - bind_group_guard: &crate::storage::Storage>, + bind_group_guard: &crate::storage::Storage>, dynamic_offsets: &[u32], index: u32, num_dynamic_offsets: usize, @@ -867,7 +867,7 @@ fn set_bind_group( let bind_group = bind_group_id.map(|id| bind_group_guard.get(id)); if let Some(bind_group) = bind_group { - let bind_group = bind_group.get()?; + bind_group.check_is_valid()?; bind_group.same_device(&state.device)?; bind_group.validate_dynamic_bindings(index, offsets)?; @@ -1295,10 +1295,21 @@ pub enum ExecutionError { Device(#[from] DeviceError), #[error(transparent)] DestroyedResource(#[from] DestroyedResourceError), + #[error(transparent)] + InvalidResource(#[from] InvalidResourceError), #[error("Using {0} in a render bundle is not implemented")] Unimplemented(&'static str), } +impl From for ExecutionError { + fn from(e: InvalidOrDestroyedResourceError) -> Self { + match e { + InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e), + InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e), + } + } +} + pub type RenderBundleDescriptor<'a> = wgt::RenderBundleDescriptor>; #[derive(Debug)] @@ -1866,8 +1877,6 @@ pub enum RenderBundleErrorInner { MissingDownlevelFlags(#[from] MissingDownlevelFlags), #[error(transparent)] Bind(#[from] BindError), - #[error(transparent)] - InvalidResource(#[from] InvalidResourceError), #[error("Render bundle encoder has already ended")] Ended, } @@ -1900,7 +1909,6 @@ impl WebGpuError for RenderBundleError { RenderBundleErrorInner::Draw(e) => e.webgpu_error_type(), RenderBundleErrorInner::MissingDownlevelFlags(e) => e.webgpu_error_type(), RenderBundleErrorInner::Bind(e) => e.webgpu_error_type(), - RenderBundleErrorInner::InvalidResource(e) => e.webgpu_error_type(), RenderBundleErrorInner::Ended => ErrorType::Validation, } } diff --git a/wgpu-core/src/command/compute.rs b/wgpu-core/src/command/compute.rs index 42046f3d4..1f9820a4c 100644 --- a/wgpu-core/src/command/compute.rs +++ b/wgpu-core/src/command/compute.rs @@ -33,8 +33,9 @@ use crate::{ init_tracker::MemoryInitKind, pipeline::ComputePipeline, resource::{ - self, Buffer, DestroyedResourceError, InvalidResourceError, Labeled, - MissingBufferUsageError, ParentDevice, RawResourceAccess, TextureView, Trackable, + self, Buffer, DestroyedResourceError, InvalidOrDestroyedResourceError, + InvalidResourceError, Labeled, MissingBufferUsageError, ParentDevice, RawResourceAccess, + TextureView, Trackable, }, track::{ResourceUsageCompatibilityError, TextureViewBindGroupState, Tracker}, Label, @@ -204,6 +205,15 @@ pub enum ComputePassErrorInner { InvalidValuesOffset(#[from] pass::InvalidValuesOffset), } +impl From for ComputePassErrorInner { + fn from(value: InvalidOrDestroyedResourceError) -> Self { + match value { + InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e), + InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e), + } + } +} + /// Error encountered when performing a compute pass, stored for later reporting /// when encoding ends. #[derive(Clone, Debug, Error)] @@ -1269,11 +1279,9 @@ impl Global { let mut bind_group = None; if let Some(bind_group_id) = bind_group_id { let hub = &self.hub; - bind_group = Some(pass_try!( - base, - scope, - hub.bind_groups.get(bind_group_id).get(), - )); + let bg = hub.bind_groups.get(bind_group_id); + pass_try!(base, scope, bg.check_is_valid()); + bind_group = Some(bg); } base.commands.push(ArcComputeCommand::SetBindGroup { diff --git a/wgpu-core/src/command/draw.rs b/wgpu-core/src/command/draw.rs index 1e7f28145..0977a0066 100644 --- a/wgpu-core/src/command/draw.rs +++ b/wgpu-core/src/command/draw.rs @@ -6,6 +6,7 @@ use wgt::error::{ErrorType, WebGpuError}; use super::bind::BinderError; use crate::command::pass; +use crate::resource::InvalidResourceError; use crate::validation::InvalidWorkgroupSizeError; use crate::{ binding_model::{BindingError, ImmediateUploadError, LateMinBufferBindingSizeMismatch}, @@ -110,6 +111,8 @@ pub enum RenderCommandError { #[error(transparent)] DestroyedResource(#[from] DestroyedResourceError), #[error(transparent)] + InvalidResource(#[from] InvalidResourceError), + #[error(transparent)] MissingBufferUsage(#[from] MissingBufferUsageError), #[error(transparent)] MissingTextureUsage(#[from] MissingTextureUsageError), @@ -135,6 +138,7 @@ impl WebGpuError for RenderCommandError { Self::IncompatiblePipelineTargets(e) => e.webgpu_error_type(), Self::ResourceUsageCompatibility(e) => e.webgpu_error_type(), Self::DestroyedResource(e) => e.webgpu_error_type(), + Self::InvalidResource(e) => e.webgpu_error_type(), Self::MissingBufferUsage(e) => e.webgpu_error_type(), Self::MissingTextureUsage(e) => e.webgpu_error_type(), Self::ImmediateData(e) => e.webgpu_error_type(), diff --git a/wgpu-core/src/command/pass.rs b/wgpu-core/src/command/pass.rs index fd90492b1..da432a5e9 100644 --- a/wgpu-core/src/command/pass.rs +++ b/wgpu-core/src/command/pass.rs @@ -8,7 +8,9 @@ use crate::command::{ }; use crate::device::{Device, DeviceError, MissingFeatures}; use crate::pipeline::LateSizedBufferGroup; -use crate::resource::{DestroyedResourceError, Labeled, ParentDevice, QuerySet}; +use crate::resource::{ + DestroyedResourceError, InvalidOrDestroyedResourceError, Labeled, ParentDevice, QuerySet, +}; use crate::track::{ResourceUsageCompatibilityError, UsageScope}; use crate::{api_log, binding_model}; use alloc::sync::Arc; @@ -141,7 +143,9 @@ where /// /// See the compute pass version of `State::flush_bindings` for an explanation /// of some differences in handling the two types of passes. -pub(super) fn flush_bindings_helper(state: &mut PassState) -> Result<(), DestroyedResourceError> { +pub(super) fn flush_bindings_helper( + state: &mut PassState, +) -> Result<(), InvalidOrDestroyedResourceError> { let start = state.binder.take_rebind_start_index(); let entries = state.binder.list_valid_with_start(start); let pipeline_layout = state.binder.pipeline_layout.as_ref().unwrap(); diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index 749d1103d..1f6005758 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -40,9 +40,10 @@ use crate::{ init_tracker::{MemoryInitKind, TextureInitRange, TextureInitTrackerAction}, pipeline::{PipelineFlags, RenderPipeline, VertexStep}, resource::{ - Buffer, DestroyedResourceError, InvalidResourceError, Labeled, MissingBufferUsageError, - MissingTextureUsageError, ParentDevice, QuerySet, RawResourceAccess, ResourceErrorIdent, - Texture, TextureView, TextureViewNotRenderableReason, + Buffer, DestroyedResourceError, InvalidOrDestroyedResourceError, InvalidResourceError, + Labeled, MissingBufferUsageError, MissingTextureUsageError, ParentDevice, QuerySet, + RawResourceAccess, ResourceErrorIdent, Texture, TextureView, + TextureViewNotRenderableReason, }, snatch::SnatchGuard, track::{ResourceUsageCompatibilityError, Tracker, UsageScope}, @@ -1025,6 +1026,15 @@ pub enum RenderPassErrorInner { TimestampWrites(#[from] TimestampWritesError), } +impl From for RenderPassErrorInner { + fn from(error: InvalidOrDestroyedResourceError) -> Self { + match error { + InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e), + InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e), + } + } +} + impl From for RenderPassErrorInner { fn from(error: MissingBufferUsageError) -> Self { Self::RenderCommand(error.into()) @@ -3619,6 +3629,9 @@ fn execute_bundle( ExecutionError::DestroyedResource(e) => { RenderPassErrorInner::RenderCommand(RenderCommandError::DestroyedResource(e)) } + ExecutionError::InvalidResource(e) => { + RenderPassErrorInner::RenderCommand(RenderCommandError::InvalidResource(e)) + } ExecutionError::Unimplemented(what) => { RenderPassErrorInner::RenderCommand(RenderCommandError::Unimplemented(what)) } @@ -3670,11 +3683,9 @@ impl Global { let mut bind_group = None; if let Some(bind_group_id) = bind_group_id { let hub = &self.hub; - bind_group = Some(pass_try!( - base, - scope, - hub.bind_groups.get(bind_group_id).get(), - )); + let bg = hub.bind_groups.get(bind_group_id); + pass_try!(base, scope, bg.check_is_valid()); + bind_group = Some(bg); } base.commands.push(ArcRenderCommand::SetBindGroup { diff --git a/wgpu-core/src/device/global.rs b/wgpu-core/src/device/global.rs index 9e43db5a1..1e62c4eba 100644 --- a/wgpu-core/src/device/global.rs +++ b/wgpu-core/src/device/global.rs @@ -23,7 +23,6 @@ use crate::{ present, resource::{ self, BufferAccessError, BufferAccessResult, BufferMapOperation, CreateBufferError, - Fallible, }, storage::Storage, Label, LabelHelpers, @@ -590,152 +589,108 @@ impl Global { let hub = &self.hub; let fid = hub.bind_groups.prepare(id_in); - let error = 'error: { - let device = self.hub.devices.get(device_id); + let device = hub.devices.get(device_id); - if let Err(e) = device.check_is_valid() { - break 'error e.into(); + let layout = hub.bind_group_layouts.get(desc.layout); + + fn resolve_entry<'a>( + e: &BindGroupEntry<'a>, + buffer_storage: &Storage>, + sampler_storage: &Storage>, + texture_view_storage: &Storage>, + tlas_storage: &Storage>, + external_texture_storage: &Storage>, + ) -> ResolvedBindGroupEntry<'a> { + let resolve_buffer = |bb: &BufferBinding| { + let buffer = buffer_storage.get(bb.buffer); + ResolvedBufferBinding { + buffer, + offset: bb.offset, + size: bb.size, + } + }; + let resolve_sampler = |id: &id::SamplerId| sampler_storage.get(*id); + let resolve_view = |id: &id::TextureViewId| texture_view_storage.get(*id); + let resolve_tlas = |id: &id::TlasId| tlas_storage.get(*id); + let resolve_external_texture = + |id: &id::ExternalTextureId| external_texture_storage.get(*id); + let resource = match e.resource { + BindingResource::Buffer(ref buffer) => { + ResolvedBindingResource::Buffer(resolve_buffer(buffer)) + } + BindingResource::BufferArray(ref buffers) => { + let buffers = buffers.iter().map(resolve_buffer).collect::>(); + ResolvedBindingResource::BufferArray(Cow::Owned(buffers)) + } + BindingResource::Sampler(ref sampler) => { + ResolvedBindingResource::Sampler(resolve_sampler(sampler)) + } + BindingResource::SamplerArray(ref samplers) => { + let samplers = samplers.iter().map(resolve_sampler).collect::>(); + ResolvedBindingResource::SamplerArray(Cow::Owned(samplers)) + } + BindingResource::TextureView(ref view) => { + ResolvedBindingResource::TextureView(resolve_view(view)) + } + BindingResource::TextureViewArray(ref views) => { + let views = views.iter().map(resolve_view).collect::>(); + ResolvedBindingResource::TextureViewArray(Cow::Owned(views)) + } + BindingResource::AccelerationStructure(ref tlas) => { + ResolvedBindingResource::AccelerationStructure(resolve_tlas(tlas)) + } + BindingResource::AccelerationStructureArray(ref tlas_array) => { + let tlas_array = tlas_array.iter().map(resolve_tlas).collect::>(); + ResolvedBindingResource::AccelerationStructureArray(Cow::Owned(tlas_array)) + } + BindingResource::ExternalTexture(ref et) => { + ResolvedBindingResource::ExternalTexture(resolve_external_texture(et)) + } + }; + ResolvedBindGroupEntry { + binding: e.binding, + resource, } + } - let layout = hub.bind_group_layouts.get(desc.layout); - - fn resolve_entry<'a>( - e: &BindGroupEntry<'a>, - buffer_storage: &Storage>, - sampler_storage: &Storage>, - texture_view_storage: &Storage>, - tlas_storage: &Storage>, - external_texture_storage: &Storage>, - ) -> Result, binding_model::CreateBindGroupError> - { - let resolve_buffer = - |bb: &BufferBinding| -> Result<_, binding_model::CreateBindGroupError> { - let buffer = buffer_storage.get(bb.buffer); - buffer.check_is_valid()?; - Ok(ResolvedBufferBinding { - buffer, - offset: bb.offset, - size: bb.size, - }) - }; - let resolve_sampler = |id: &id::SamplerId| sampler_storage.get(*id); - let resolve_view = |id: &id::TextureViewId| texture_view_storage.get(*id); - let resolve_tlas = |id: &id::TlasId| tlas_storage.get(*id); - let resolve_external_texture = - |id: &id::ExternalTextureId| external_texture_storage.get(*id); - let resource = match e.resource { - BindingResource::Buffer(ref buffer) => { - ResolvedBindingResource::Buffer(resolve_buffer(buffer)?) - } - BindingResource::BufferArray(ref buffers) => { - let buffers = buffers - .iter() - .map(resolve_buffer) - .collect::, _>>()?; - ResolvedBindingResource::BufferArray(Cow::Owned(buffers)) - } - BindingResource::Sampler(ref sampler) => { - ResolvedBindingResource::Sampler(resolve_sampler(sampler)) - } - BindingResource::SamplerArray(ref samplers) => { - let samplers = samplers.iter().map(resolve_sampler).collect::>(); - ResolvedBindingResource::SamplerArray(Cow::Owned(samplers)) - } - BindingResource::TextureView(ref view) => { - ResolvedBindingResource::TextureView(resolve_view(view)) - } - BindingResource::TextureViewArray(ref views) => { - let views = views.iter().map(resolve_view).collect::>(); - ResolvedBindingResource::TextureViewArray(Cow::Owned(views)) - } - BindingResource::AccelerationStructure(ref tlas) => { - ResolvedBindingResource::AccelerationStructure(resolve_tlas(tlas)) - } - BindingResource::AccelerationStructureArray(ref tlas_array) => { - let tlas_array = tlas_array.iter().map(resolve_tlas).collect::>(); - ResolvedBindingResource::AccelerationStructureArray(Cow::Owned(tlas_array)) - } - BindingResource::ExternalTexture(ref et) => { - ResolvedBindingResource::ExternalTexture(resolve_external_texture(et)) - } - }; - Ok(ResolvedBindGroupEntry { - binding: e.binding, - resource, + let entries = { + let buffer_guard = hub.buffers.read(); + let texture_view_guard = hub.texture_views.read(); + let sampler_guard = hub.samplers.read(); + let tlas_guard = hub.tlas_s.read(); + let external_texture_guard = hub.external_textures.read(); + desc.entries + .iter() + .map(|e| { + resolve_entry( + e, + &buffer_guard, + &sampler_guard, + &texture_view_guard, + &tlas_guard, + &external_texture_guard, + ) }) - } + .collect::>() + }; + let entries = Cow::Owned(entries); - let entries = { - let buffer_guard = hub.buffers.read(); - let texture_view_guard = hub.texture_views.read(); - let sampler_guard = hub.samplers.read(); - let tlas_guard = hub.tlas_s.read(); - let external_texture_guard = hub.external_textures.read(); - desc.entries - .iter() - .map(|e| { - resolve_entry( - e, - &buffer_guard, - &sampler_guard, - &texture_view_guard, - &tlas_guard, - &external_texture_guard, - ) - }) - .collect::, _>>() - }; - let entries = match entries { - Ok(entries) => Cow::Owned(entries), - Err(e) => break 'error e, - }; - - let desc = ResolvedBindGroupDescriptor { - label: desc.label.clone(), - layout, - entries, - }; - #[cfg(feature = "trace")] - let trace_desc = (&desc).to_trace(); - - let bind_group = match device.create_bind_group(desc) { - Ok(bind_group) => bind_group, - Err(e) => break 'error e, - }; - - #[cfg(feature = "trace")] - if let Some(ref mut trace) = *device.trace.lock() { - trace.add(trace::Action::CreateBindGroup( - bind_group.to_trace(), - trace_desc, - )); - } - - let id = fid.assign(Fallible::Valid(bind_group)); - - api_log!("Device::create_bind_group -> {id:?}"); - - return (id, None); + let desc = ResolvedBindGroupDescriptor { + label: desc.label.clone(), + layout, + entries, }; - let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string()))); - (id, Some(error)) + let (bind_group, error) = device.create_bind_group(&desc); + + let id = fid.assign(bind_group); + (id, error) } pub fn bind_group_drop(&self, bind_group_id: id::BindGroupId) { - profiling::scope!("BindGroup::drop"); - api_log!("BindGroup::drop {bind_group_id:?}"); - let hub = &self.hub; let _bind_group = hub.bind_groups.remove(bind_group_id); - - #[cfg(feature = "trace")] - if let Ok(bind_group) = _bind_group.get() { - if let Some(t) = bind_group.device.trace.lock().as_mut() { - t.add(trace::Action::DropBindGroup(bind_group.to_trace())); - } - } } /// Create a shader module with the given `source`. diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index f804d6493..2b10dcd2c 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -22,12 +22,12 @@ use wgt::{ }; #[cfg(feature = "trace")] -use crate::device::trace; +use crate::device::trace::{self, IntoTrace as _}; use crate::{ api_log, binding_model::{ self, BindGroup, BindGroupLateBufferBindingInfo, BindGroupLayout, - BindGroupLayoutEntryError, BindGroupLayoutState, CreateBindGroupError, + BindGroupLayoutEntryError, BindGroupLayoutState, BindGroupState, CreateBindGroupError, CreateBindGroupLayoutError, }, command, conv, @@ -754,8 +754,12 @@ impl Device { let Some(bind_group) = bind_group.upgrade() else { continue; }; - let Some(raw_bind_group) = - bind_group.raw.snatch(&mut self.snatchable_lock.write()) + let Ok(bind_group_state) = bind_group.state() else { + continue; + }; + let Some(raw_bind_group) = bind_group_state + .raw + .snatch(&mut self.snatchable_lock.write()) else { continue; }; @@ -3305,6 +3309,7 @@ impl Device { used.buffers.insert_single(buffer.clone(), internal_use); + buffer.check_is_valid()?; buffer.same_device(self)?; buffer.check_usage(pub_usage)?; @@ -3639,17 +3644,49 @@ impl Device { Ok(hal::ExternalTextureBinding { planes, params }) } - // This function expects the provided bind group layout to be resolved - // (not passing a duplicate) beforehand. pub fn create_bind_group( self: &Arc, - desc: binding_model::ResolvedBindGroupDescriptor, + desc: &binding_model::ResolvedBindGroupDescriptor, + ) -> (Arc, Option) { + #[cfg(feature = "trace")] + let trace_desc = (&desc).to_trace(); + + let (bind_group, error) = match self.create_bind_group_inner(desc) { + Ok(bind_group) => (bind_group, None), + Err(e) => ( + BindGroup::invalid(self.clone(), desc.label.to_string(), desc.layout.clone()), + Some(e), + ), + }; + + #[cfg(feature = "trace")] + if let Some(ref mut trace) = *self.trace.lock() { + trace.add(trace::Action::CreateBindGroup( + bind_group.to_trace(), + trace_desc, + )); + } + + api_log!( + "Device::create_bind_group -> {:?}", + Arc::as_ptr(&bind_group) + ); + + (bind_group, error) + } + + // This function expects the provided bind group layout to be resolved + // (not passing a duplicate) beforehand. + pub fn create_bind_group_inner( + self: &Arc, + desc: &binding_model::ResolvedBindGroupDescriptor, ) -> Result, CreateBindGroupError> { use crate::binding_model::{CreateBindGroupError as Error, ResolvedBindingResource as Br}; - let layout = desc.layout; - self.check_is_valid()?; + + let layout = desc.layout.clone(); + layout.same_device(self)?; layout.check_is_valid()?; @@ -3880,7 +3917,9 @@ impl Device { .collect(); let bind_group = BindGroup { - raw: Snatchable::new(raw), + state: ResourceState::Valid(BindGroupState { + raw: Snatchable::new(raw), + }), device: self.clone(), layout, label: desc.label.to_string(), diff --git a/wgpu-core/src/hub.rs b/wgpu-core/src/hub.rs index c1dbf2171..ce61538d0 100644 --- a/wgpu-core/src/hub.rs +++ b/wgpu-core/src/hub.rs @@ -130,8 +130,7 @@ use crate::{ pipeline::{ComputePipeline, PipelineCache, RenderPipeline, ShaderModule}, registry::{Registry, RegistryReport}, resource::{ - Blas, Buffer, ExternalTexture, Fallible, QuerySet, Sampler, StagingBuffer, Texture, - TextureView, Tlas, + Blas, Buffer, ExternalTexture, QuerySet, Sampler, StagingBuffer, Texture, TextureView, Tlas, }, }; @@ -197,7 +196,7 @@ pub struct Hub { pub(crate) pipeline_layouts: Registry>, pub(crate) shader_modules: Registry>, pub(crate) bind_group_layouts: Registry>, - pub(crate) bind_groups: Registry>, + pub(crate) bind_groups: Registry>, pub(crate) command_encoders: Registry>, pub(crate) command_buffers: Registry>, pub(crate) render_bundles: Registry>,