diff --git a/wgpu-core/src/binding_model.rs b/wgpu-core/src/binding_model.rs index 70d6f7fa5..886b03683 100644 --- a/wgpu-core/src/binding_model.rs +++ b/wgpu-core/src/binding_model.rs @@ -820,7 +820,10 @@ pub struct BindGroupLayout { } impl Drop for BindGroupLayout { + #[allow(trivial_casts)] fn drop(&mut self) { + profiling::scope!("BindGroupLayout::drop"); + api_log!("BindGroupLayout::drop {:?}", self as *const _); #[cfg(feature = "trace")] { let mut t = self.device.trace.lock(); @@ -897,7 +900,7 @@ impl BindGroupLayout { }) } - pub(crate) fn invalid(device: &Arc, label: String) -> Arc { + pub fn invalid(device: &Arc, label: String) -> Arc { Arc::new(Self { state: ResourceState::Invalid, device: device.clone(), @@ -1039,7 +1042,10 @@ pub struct PipelineLayout { } impl Drop for PipelineLayout { + #[allow(trivial_casts)] fn drop(&mut self) { + profiling::scope!("PipelineLayout::drop"); + api_log!("PipelineLayout::drop {:?}", self as *const _); resource_log!("Destroy raw {}", self.error_ident()); if let ResourceState::Valid(raw) = core::mem::replace(&mut self.raw, ResourceState::Invalid) { diff --git a/wgpu-core/src/command/bundle.rs b/wgpu-core/src/command/bundle.rs index 46353260d..6405108ab 100644 --- a/wgpu-core/src/command/bundle.rs +++ b/wgpu-core/src/command/bundle.rs @@ -1371,7 +1371,7 @@ impl RenderBundle { self.state().map(|_| ()) } - pub(crate) fn invalid(device: Arc, desc: &RenderBundleDescriptor) -> Arc { + pub fn invalid(device: Arc, desc: &RenderBundleDescriptor) -> Arc { Arc::new(RenderBundle { state: ResourceState::Invalid, base: BasePass { diff --git a/wgpu-core/src/command/mod.rs b/wgpu-core/src/command/mod.rs index 171312ae1..7fd7c158e 100644 --- a/wgpu-core/src/command/mod.rs +++ b/wgpu-core/src/command/mod.rs @@ -534,7 +534,10 @@ crate::impl_parent_device!(CommandEncoder); crate::impl_storage_item!(CommandEncoder); impl Drop for CommandEncoder { + #[allow(trivial_casts)] fn drop(&mut self) { + profiling::scope!("CommandEncoder::drop"); + api_log!("CommandEncoder::drop {:?}", self as *const _); resource_log!("Drop {}", self.error_ident()); } } @@ -902,7 +905,10 @@ pub struct CommandBuffer { } impl Drop for CommandBuffer { + #[allow(trivial_casts)] fn drop(&mut self) { + profiling::scope!("CommandBuffer::drop"); + api_log!("CommandBuffer::drop {:?}", self as *const _); resource_log!("Drop {}", self.error_ident()); } } @@ -955,12 +961,12 @@ impl CommandEncoder { device: &Arc, label: &Label, err: CommandEncoderError, - ) -> Self { - CommandEncoder { + ) -> Arc { + Arc::new(CommandEncoder { device: device.clone(), label: label.to_string(), data: Mutex::new(rank::COMMAND_BUFFER_DATA, make_error_state(err)), - } + }) } pub(crate) fn validate_pass_timestamp_writes( @@ -1395,7 +1401,8 @@ impl CommandBuffer { /// entrypoints provide. #[doc(hidden)] pub fn from_trace(device: &Arc, commands: Vec>) -> Arc { - let encoder = device.create_command_encoder(&None).unwrap(); + let (encoder, _error) = + device.create_command_encoder(&wgt::CommandEncoderDescriptor { label: None }); let mut cmd_enc_status = encoder.data.lock(); cmd_enc_status.replay(commands); drop(cmd_enc_status); diff --git a/wgpu-core/src/device/global.rs b/wgpu-core/src/device/global.rs index b0e593026..e5e86faff 100644 --- a/wgpu-core/src/device/global.rs +++ b/wgpu-core/src/device/global.rs @@ -1,16 +1,15 @@ use alloc::{borrow::Cow, boxed::Box, sync::Arc, vec::Vec}; -use core::{ptr::NonNull, sync::atomic::Ordering}; +use core::ptr::NonNull; #[cfg(feature = "trace")] -use crate::device::trace::{self, IntoTrace}; +use crate::device::trace; use crate::{ api_log, binding_model::{ self, BindGroupEntry, BindingResource, BufferBinding, ResolvedBindGroupDescriptor, ResolvedBindGroupEntry, ResolvedBindingResource, ResolvedBufferBinding, }, - command::{self, CommandEncoder}, - conv, + command, device::{life::WaitIdleError, DeviceError, DeviceLostClosure}, global::Global, id::{self, AdapterId, DeviceId, QueueId, SurfaceId}, @@ -30,7 +29,7 @@ use crate::{ use wgt::{BufferAddress, TextureFormat}; -use super::{surface_config, UserClosures}; +use super::UserClosures; impl Global { pub fn adapter_is_surface_supported( @@ -48,34 +47,8 @@ impl Global { surface_id: SurfaceId, adapter_id: AdapterId, ) -> Result { - profiling::scope!("Surface::get_capabilities"); self.fetch_adapter_and_surface::<_, _>(surface_id, adapter_id, |adapter, surface| { - let mut hal_caps = surface.get_capabilities(adapter)?; - - hal_caps.formats.sort_by_key(|fc| !fc.format.is_srgb()); - - let usages = conv::map_texture_usage_from_hal(hal_caps.usage); - - // `SurfaceCapabilities::formats` lists only the formats a - // color-space-unaware application can configure via - // `SurfaceColorSpace::Auto`, i.e. those for which `Auto` resolves to a - // concrete color space. (The full `format_capabilities` still reports - // every color space, including HDR ones, for explicit opt-in.) - Ok(wgt::SurfaceCapabilities { - formats: hal_caps - .formats - .iter() - .filter(|fc| { - surface_config::resolve_auto_color_space(fc.format, fc.color_spaces) - .is_some() - }) - .map(|fc| fc.format) - .collect(), - format_capabilities: hal_caps.formats, - present_modes: hal_caps.present_modes, - alpha_modes: hal_caps.composite_alpha_modes, - usages, - }) + surface.get_capabilities(adapter) }) } @@ -93,7 +66,6 @@ impl Global { surface_id: SurfaceId, adapter_id: AdapterId, ) -> wgt::DisplayHdrInfo { - profiling::scope!("Surface::display_hdr_info"); self.fetch_adapter_and_surface(surface_id, adapter_id, |adapter, surface| { surface.display_hdr_info(adapter) }) @@ -112,12 +84,12 @@ impl Global { pub fn device_features(&self, device_id: DeviceId) -> wgt::Features { let device = self.hub.devices.get(device_id); - device.features + *device.features() } pub fn device_limits(&self, device_id: DeviceId) -> wgt::Limits { let device = self.hub.devices.get(device_id); - device.limits.clone() + device.limits().clone() } pub fn device_adapter_info(&self, device_id: DeviceId) -> wgt::AdapterInfo { @@ -127,7 +99,7 @@ impl Global { pub fn device_downlevel_properties(&self, device_id: DeviceId) -> wgt::DownlevelCapabilities { let device = self.hub.devices.get(device_id); - device.downlevel.clone() + device.downlevel().clone() } pub fn device_create_buffer( @@ -136,8 +108,6 @@ impl Global { desc: &resource::BufferDescriptor, id_in: Option, ) -> (id::BufferId, Option) { - profiling::scope!("Device::create_buffer"); - let hub = &self.hub; let fid = hub.buffers.prepare(id_in); @@ -255,9 +225,6 @@ impl Global { } pub fn buffer_destroy(&self, buffer_id: id::BufferId) { - profiling::scope!("Buffer::destroy"); - api_log!("Buffer::destroy {buffer_id:?}"); - let hub = &self.hub; let buffer = hub.buffers.get(buffer_id); @@ -266,9 +233,6 @@ impl Global { } pub fn buffer_drop(&self, buffer_id: id::BufferId) { - profiling::scope!("Buffer::drop"); - api_log!("Buffer::drop {buffer_id:?}"); - let hub = &self.hub; let _buffer = hub.buffers.remove(buffer_id); @@ -280,8 +244,6 @@ impl Global { desc: &resource::TextureDescriptor, id_in: Option, ) -> (id::TextureId, Option) { - profiling::scope!("Device::create_texture"); - let hub = &self.hub; let fid = hub.textures.prepare(id_in); @@ -318,30 +280,11 @@ impl Global { let device = self.hub.devices.get(device_id); - let error = 'error: { - let texture = match device.create_texture_from_hal(hal_texture, desc, initial_state) { - Ok(texture) => texture, - Err(error) => break 'error error, - }; + let (texture, error) = + unsafe { device.create_texture_from_hal(hal_texture, desc, initial_state) }; - // NB: Any change done through the raw texture handle will not be - // recorded in the replay - #[cfg(feature = "trace")] - if let Some(ref mut trace) = *device.trace.lock() { - trace.add(trace::Action::CreateTexture( - texture.to_trace(), - desc.clone(), - )); - } - - let id = fid.assign(texture); - api_log!("Device::create_texture({desc:?}) -> {id:?}"); - - return (id, None); - }; - - let id = fid.assign(Arc::new(resource::Texture::invalid(&device, desc))); - (id, Some(error)) + let id = fid.assign(texture); + (id, error) } /// # Safety @@ -372,25 +315,14 @@ impl Global { } pub fn texture_destroy(&self, texture_id: id::TextureId) { - profiling::scope!("Texture::destroy"); - api_log!("Texture::destroy {texture_id:?}"); - let hub = &self.hub; let texture = hub.textures.get(texture_id); - #[cfg(feature = "trace")] - if let Some(trace) = texture.device.trace.lock().as_mut() { - trace.add(trace::Action::DestroyTexture(texture.to_trace())); - } - texture.destroy(); } pub fn texture_drop(&self, texture_id: id::TextureId) { - profiling::scope!("Texture::drop"); - api_log!("Texture::drop {texture_id:?}"); - let hub = &self.hub; hub.textures.remove(texture_id); @@ -402,8 +334,6 @@ impl Global { desc: &resource::TextureViewDescriptor, id_in: Option, ) -> (id::TextureViewId, Option) { - profiling::scope!("Texture::create_view"); - let hub = &self.hub; let fid = hub.texture_views.prepare(id_in); @@ -434,8 +364,6 @@ impl Global { id::ExternalTextureId, Option, ) { - profiling::scope!("Device::create_external_texture"); - let hub = &self.hub; let fid = hub.external_textures.prepare(id_in); @@ -455,9 +383,6 @@ impl Global { } pub fn external_texture_destroy(&self, external_texture_id: id::ExternalTextureId) { - profiling::scope!("ExternalTexture::destroy"); - api_log!("ExternalTexture::destroy {external_texture_id:?}"); - let hub = &self.hub; let external_texture = hub.external_textures.get(external_texture_id); @@ -466,9 +391,6 @@ impl Global { } pub fn external_texture_drop(&self, external_texture_id: id::ExternalTextureId) { - profiling::scope!("ExternalTexture::drop"); - api_log!("ExternalTexture::drop {external_texture_id:?}"); - let hub = &self.hub; let _external_texture = hub.external_textures.remove(external_texture_id); @@ -507,8 +429,6 @@ impl Global { id::BindGroupLayoutId, Option, ) { - profiling::scope!("Device::create_bind_group_layout"); - let hub = &self.hub; let fid = hub.bind_group_layouts.prepare(id_in); @@ -518,15 +438,10 @@ impl Global { let id = fid.assign(bgl); - api_log!("Device::create_bind_group_layout -> {id:?}"); - (id, error) } pub fn bind_group_layout_drop(&self, bind_group_layout_id: id::BindGroupLayoutId) { - profiling::scope!("BindGroupLayout::drop"); - api_log!("BindGroupLayout::drop {bind_group_layout_id:?}"); - let hub = &self.hub; let _layout = hub.bind_group_layouts.remove(bind_group_layout_id); @@ -541,8 +456,6 @@ impl Global { id::PipelineLayoutId, Option, ) { - profiling::scope!("Device::create_pipeline_layout"); - let hub = &self.hub; let fid = hub.pipeline_layouts.prepare(id_in); @@ -568,9 +481,6 @@ impl Global { } pub fn pipeline_layout_drop(&self, pipeline_layout_id: id::PipelineLayoutId) { - profiling::scope!("PipelineLayout::drop"); - api_log!("PipelineLayout::drop {pipeline_layout_id:?}"); - let hub = &self.hub; let _layout = hub.pipeline_layouts.remove(pipeline_layout_id); @@ -582,8 +492,6 @@ impl Global { desc: &binding_model::BindGroupDescriptor, id_in: Option, ) -> (id::BindGroupId, Option) { - profiling::scope!("Device::create_bind_group"); - let hub = &self.hub; let fid = hub.bind_groups.prepare(id_in); @@ -715,8 +623,6 @@ impl Global { id::ShaderModuleId, Option, ) { - profiling::scope!("Device::create_shader_module"); - let hub = &self.hub; let fid = hub.shader_modules.prepare(id_in); @@ -755,9 +661,6 @@ impl Global { } pub fn shader_module_drop(&self, shader_module_id: id::ShaderModuleId) { - profiling::scope!("ShaderModule::drop"); - api_log!("ShaderModule::drop {shader_module_id:?}"); - let hub = &self.hub; let _shader_module = hub.shader_modules.remove(shader_module_id); @@ -776,34 +679,17 @@ impl Global { let device = self.hub.devices.get(device_id); - let error = 'error: { - let cmd_enc = match device.create_command_encoder(&desc.label) { - Ok(cmd_enc) => cmd_enc, - Err(e) => break 'error e, - }; + let (cmd_enc, error) = device.create_command_encoder(desc); - let id = fid.assign(cmd_enc); - api_log!("Device::create_command_encoder -> {id:?}"); - return (id, None); - }; - - let id = fid.assign(Arc::new(CommandEncoder::new_invalid( - &device, - &desc.label, - error.clone().into(), - ))); - (id, Some(error)) + let id = fid.assign(cmd_enc); + (id, error) } pub fn command_encoder_drop(&self, command_encoder_id: id::CommandEncoderId) { - profiling::scope!("CommandEncoder::drop"); - api_log!("CommandEncoder::drop {command_encoder_id:?}"); let _cmd_enc = self.hub.command_encoders.remove(command_encoder_id); } pub fn command_buffer_drop(&self, command_buffer_id: id::CommandBufferId) { - profiling::scope!("CommandBuffer::drop"); - api_log!("CommandBuffer::drop {command_buffer_id:?}"); let _cmd_buf = self.hub.command_buffers.remove(command_buffer_id); } @@ -907,8 +793,6 @@ impl Global { desc: &resource::QuerySetDescriptor, id_in: Option, ) -> (id::QuerySetId, Option) { - profiling::scope!("Device::create_query_set"); - let hub = &self.hub; let fid = hub.query_sets.prepare(id_in); @@ -930,9 +814,6 @@ impl Global { } pub fn query_set_drop(&self, query_set_id: id::QuerySetId) { - profiling::scope!("QuerySet::drop"); - api_log!("QuerySet::drop {query_set_id:?}"); - let hub = &self.hub; let _query_set = hub.query_sets.remove(query_set_id); @@ -947,8 +828,6 @@ impl Global { id::RenderPipelineId, Option, ) { - profiling::scope!("Device::create_render_pipeline"); - let hub = &self.hub; let fid = hub.render_pipelines.prepare(id_in); @@ -984,112 +863,90 @@ impl Global { id::RenderPipelineId, Option, ) { - profiling::scope!("Device::create_general_render_pipeline"); - let hub = &self.hub; - // eventually there will be no error handling here only id to object mapping - let error = 'error: { - // until then we also need this - if let Err(e) = device.check_is_valid() { - break 'error e.into(); - } + let layout = desc.layout.map(|layout| hub.pipeline_layouts.get(layout)); - let layout = desc.layout.map(|layout| hub.pipeline_layouts.get(layout)); - - let cache = desc.cache.map(|cache| hub.pipeline_caches.get(cache)); - - let vertex = match desc.vertex { - RenderPipelineVertexProcessor::Vertex(ref vertex) => { - let module = hub.shader_modules.get(vertex.stage.module); - let stage = ResolvedProgrammableStageDescriptor { - module, - entry_point: vertex.stage.entry_point.clone(), - constants: vertex.stage.constants.clone(), - zero_initialize_workgroup_memory: vertex - .stage - .zero_initialize_workgroup_memory, - }; - RenderPipelineVertexProcessor::Vertex(ResolvedVertexState { - stage, - buffers: vertex.buffers.clone(), - }) - } - RenderPipelineVertexProcessor::Mesh(ref task, ref mesh) => { - let task_module = if let Some(task) = task { - let module = hub.shader_modules.get(task.stage.module); - - let state = ResolvedProgrammableStageDescriptor { - module, - entry_point: task.stage.entry_point.clone(), - constants: task.stage.constants.clone(), - zero_initialize_workgroup_memory: task - .stage - .zero_initialize_workgroup_memory, - }; - Some(ResolvedTaskState { stage: state }) - } else { - None - }; - let mesh_module = hub.shader_modules.get(mesh.stage.module); - let mesh_stage = ResolvedProgrammableStageDescriptor { - module: mesh_module, - entry_point: mesh.stage.entry_point.clone(), - constants: mesh.stage.constants.clone(), - zero_initialize_workgroup_memory: mesh - .stage - .zero_initialize_workgroup_memory, - }; - RenderPipelineVertexProcessor::Mesh( - task_module, - ResolvedMeshState { stage: mesh_stage }, - ) - } - }; - - let fragment = if let Some(ref state) = desc.fragment { - let module = hub.shader_modules.get(state.stage.module); + let cache = desc.cache.map(|cache| hub.pipeline_caches.get(cache)); + let vertex = match desc.vertex { + RenderPipelineVertexProcessor::Vertex(ref vertex) => { + let module = hub.shader_modules.get(vertex.stage.module); let stage = ResolvedProgrammableStageDescriptor { module, - entry_point: state.stage.entry_point.clone(), - constants: state.stage.constants.clone(), - zero_initialize_workgroup_memory: state.stage.zero_initialize_workgroup_memory, + entry_point: vertex.stage.entry_point.clone(), + constants: vertex.stage.constants.clone(), + zero_initialize_workgroup_memory: vertex.stage.zero_initialize_workgroup_memory, }; - Some(ResolvedFragmentState { + RenderPipelineVertexProcessor::Vertex(ResolvedVertexState { stage, - targets: state.targets.clone(), + buffers: vertex.buffers.clone(), }) - } else { - None - }; + } + RenderPipelineVertexProcessor::Mesh(ref task, ref mesh) => { + let task_module = if let Some(task) = task { + let module = hub.shader_modules.get(task.stage.module); - let desc = ResolvedGeneralRenderPipelineDescriptor { - label: desc.label.clone(), - layout, - vertex, - primitive: desc.primitive, - depth_stencil: desc.depth_stencil.clone(), - multisample: desc.multisample, - fragment, - multiview_mask: desc.multiview_mask, - cache, - }; - - let (pipeline, error) = device.create_render_pipeline(desc); - - let id = fid.assign(pipeline); - api_log!("Device::create_render_pipeline -> {id:?}"); - - return (id, error); + let state = ResolvedProgrammableStageDescriptor { + module, + entry_point: task.stage.entry_point.clone(), + constants: task.stage.constants.clone(), + zero_initialize_workgroup_memory: task + .stage + .zero_initialize_workgroup_memory, + }; + Some(ResolvedTaskState { stage: state }) + } else { + None + }; + let mesh_module = hub.shader_modules.get(mesh.stage.module); + let mesh_stage = ResolvedProgrammableStageDescriptor { + module: mesh_module, + entry_point: mesh.stage.entry_point.clone(), + constants: mesh.stage.constants.clone(), + zero_initialize_workgroup_memory: mesh.stage.zero_initialize_workgroup_memory, + }; + RenderPipelineVertexProcessor::Mesh( + task_module, + ResolvedMeshState { stage: mesh_stage }, + ) + } }; - let id = fid.assign(pipeline::RenderPipeline::invalid( - device.clone(), - desc.label.to_string(), - )); + let fragment = if let Some(ref state) = desc.fragment { + let module = hub.shader_modules.get(state.stage.module); - (id, Some(error)) + let stage = ResolvedProgrammableStageDescriptor { + module, + entry_point: state.stage.entry_point.clone(), + constants: state.stage.constants.clone(), + zero_initialize_workgroup_memory: state.stage.zero_initialize_workgroup_memory, + }; + Some(ResolvedFragmentState { + stage, + targets: state.targets.clone(), + }) + } else { + None + }; + + let desc = ResolvedGeneralRenderPipelineDescriptor { + label: desc.label.clone(), + layout, + vertex, + primitive: desc.primitive, + depth_stencil: desc.depth_stencil.clone(), + multisample: desc.multisample, + fragment, + multiview_mask: desc.multiview_mask, + cache, + }; + + let (pipeline, error) = device.create_render_pipeline(desc); + + let id = fid.assign(pipeline); + + (id, error) } /// Get an ID of one of the bind group layouts. The ID adds a refcount, @@ -1117,9 +974,6 @@ impl Global { } pub fn render_pipeline_drop(&self, render_pipeline_id: id::RenderPipelineId) { - profiling::scope!("RenderPipeline::drop"); - api_log!("RenderPipeline::drop {render_pipeline_id:?}"); - let hub = &self.hub; let _pipeline = hub.render_pipelines.remove(render_pipeline_id); @@ -1134,55 +988,37 @@ impl Global { id::ComputePipelineId, Option, ) { - profiling::scope!("Device::create_compute_pipeline"); - let hub = &self.hub; let fid = hub.compute_pipelines.prepare(id_in); let device = self.hub.devices.get(device_id); - // eventually there will be no error handling here only id to object mapping - let error = 'error: { - // until then we also need this - if let Err(e) = device.check_is_valid() { - break 'error e.into(); - } + let layout = desc.layout.map(|layout| hub.pipeline_layouts.get(layout)); - let layout = desc.layout.map(|layout| hub.pipeline_layouts.get(layout)); + let cache = desc.cache.map(|cache| hub.pipeline_caches.get(cache)); - let cache = desc.cache.map(|cache| hub.pipeline_caches.get(cache)); + let module = hub.shader_modules.get(desc.stage.module); - let module = hub.shader_modules.get(desc.stage.module); - - let stage = ResolvedProgrammableStageDescriptor { - module, - entry_point: desc.stage.entry_point.clone(), - constants: desc.stage.constants.clone(), - zero_initialize_workgroup_memory: desc.stage.zero_initialize_workgroup_memory, - }; - - let desc = ResolvedComputePipelineDescriptor { - label: desc.label.clone(), - layout, - stage, - cache, - }; - - let (pipeline, error) = device.create_compute_pipeline(desc); - - let id = fid.assign(pipeline); - api_log!("Device::create_compute_pipeline -> {id:?}"); - - return (id, error); + let stage = ResolvedProgrammableStageDescriptor { + module, + entry_point: desc.stage.entry_point.clone(), + constants: desc.stage.constants.clone(), + zero_initialize_workgroup_memory: desc.stage.zero_initialize_workgroup_memory, }; - let id = fid.assign(pipeline::ComputePipeline::invalid( - device, - desc.label.to_string(), - )); + let desc = ResolvedComputePipelineDescriptor { + label: desc.label.clone(), + layout, + stage, + cache, + }; - (id, Some(error)) + let (pipeline, error) = device.create_compute_pipeline(desc); + + let id = fid.assign(pipeline); + + (id, error) } /// Get an ID of one of the bind group layouts. The ID adds a refcount, @@ -1210,9 +1046,6 @@ impl Global { } pub fn compute_pipeline_drop(&self, compute_pipeline_id: id::ComputePipelineId) { - profiling::scope!("ComputePipeline::drop"); - api_log!("ComputePipeline::drop {compute_pipeline_id:?}"); - let hub = &self.hub; let _pipeline = hub.compute_pipelines.remove(compute_pipeline_id); @@ -1230,8 +1063,6 @@ impl Global { id::PipelineCacheId, Option, ) { - profiling::scope!("Device::create_pipeline_cache"); - let hub = &self.hub; let fid = hub.pipeline_caches.prepare(id_in); @@ -1259,14 +1090,6 @@ impl Global { let device = self.hub.devices.get(device_id); let surface = self.surfaces.get(surface_id); - #[cfg(feature = "trace")] - if let Some(ref mut trace) = *device.trace.lock() { - trace.add(trace::Action::ConfigureSurface( - surface.to_trace(), - config.clone(), - )); - } - device.configure_surface(&surface, config) } @@ -1278,15 +1101,9 @@ impl Global { device_id: DeviceId, poll_type: wgt::PollType, ) -> Result { - api_log!("Device::poll {poll_type:?}"); - let device = self.hub.devices.get(device_id); - let (closures, result) = device.poll_and_return_closures(poll_type); - - closures.fire(); - - result + device.poll(poll_type) } /// Poll all devices belonging to the specified backend. @@ -1379,9 +1196,6 @@ impl Global { } pub fn device_drop(&self, device_id: DeviceId) { - profiling::scope!("Device::drop"); - api_log!("Device::drop {device_id:?}"); - self.hub.devices.remove(device_id); } @@ -1393,42 +1207,17 @@ impl Global { ) { let device = self.hub.devices.get(device_id); - device - .device_lost_closure - .lock() - .replace(device_lost_closure); + device.set_device_lost_closure(device_lost_closure); } pub fn device_destroy(&self, device_id: DeviceId) { - api_log!("Device::destroy {device_id:?}"); - let device = self.hub.devices.get(device_id); - - // Follow the steps at - // https://gpuweb.github.io/gpuweb/#dom-gpudevice-destroy. - // It's legal to call destroy multiple times, but if the device - // is already invalid, there's nothing more to do. There's also - // no need to return an error. - if !device.is_valid() { - return; - } - - // The last part of destroy is to lose the device. The spec says - // delay that until all "currently-enqueued operations on any - // queue on this device are completed." This is accomplished by - // setting valid to false, and then relying upon maintain to - // check for empty queues and a DeviceLostClosure. At that time, - // the DeviceLostClosure will be called with "destroyed" as the - // reason. - device.valid.store(false, Ordering::Release); + device.destroy(); } pub fn device_get_internal_counters(&self, device_id: DeviceId) -> wgt::InternalCounters { let device = self.hub.devices.get(device_id); - wgt::InternalCounters { - hal: device.get_hal_counters(), - core: wgt::CoreCounters {}, - } + device.get_internal_counters() } pub fn device_generate_allocator_report( @@ -1449,9 +1238,6 @@ impl Global { } pub fn queue_drop(&self, queue_id: QueueId) { - profiling::scope!("Queue::drop"); - api_log!("Queue::drop {queue_id:?}"); - self.hub.queues.remove(queue_id); } @@ -1463,9 +1249,6 @@ impl Global { size: Option, op: BufferMapOperation, ) -> Result { - profiling::scope!("Buffer::map_async"); - api_log!("Buffer::map_async {buffer_id:?} offset {offset:?} size {size:?} op: {op:?}"); - let hub = &self.hub; let buffer = hub.buffers.get(buffer_id); @@ -1487,9 +1270,6 @@ impl Global { } pub fn buffer_unmap(&self, buffer_id: id::BufferId) -> BufferAccessResult { - profiling::scope!("unmap", "Buffer"); - api_log!("Buffer::unmap {buffer_id:?}"); - let hub = &self.hub; let buffer = hub.buffers.get(buffer_id); diff --git a/wgpu-core/src/device/mod.rs b/wgpu-core/src/device/mod.rs index a38020d85..2d333a310 100644 --- a/wgpu-core/src/device/mod.rs +++ b/wgpu-core/src/device/mod.rs @@ -26,7 +26,7 @@ mod life; pub mod queue; pub mod ray_tracing; pub mod resource; -mod surface_config; +pub(crate) mod surface_config; #[cfg(any(feature = "trace", feature = "replay"))] pub mod trace; pub use {life::WaitIdleError, resource::Device}; diff --git a/wgpu-core/src/device/queue.rs b/wgpu-core/src/device/queue.rs index a25741165..6dbe49d63 100644 --- a/wgpu-core/src/device/queue.rs +++ b/wgpu-core/src/device/queue.rs @@ -275,7 +275,10 @@ crate::impl_parent_device!(Queue); crate::impl_storage_item!(Queue); impl Drop for Queue { + #[allow(trivial_casts)] fn drop(&mut self) { + profiling::scope!("Queue::drop"); + api_log!("Queue::drop {:?}", self as *const _); resource_log!("Drop {}", self.error_ident()); // On Vulkan, pending presents are not tracked by fences. diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index f7dbc49c8..6fd429f66 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -326,7 +326,10 @@ impl fmt::Debug for Device { } impl Drop for Device { + #[allow(trivial_casts)] fn drop(&mut self) { + profiling::scope!("Device::drop"); + api_log!("Device::drop {:?}", self as *const _); resource_log!("Drop {}", self.error_ident()); // SAFETY: We are in the Drop impl and we don't use self.zero_buffer anymore after this @@ -356,6 +359,20 @@ impl Drop for Device { } } +impl Device { + pub fn features(&self) -> &wgt::Features { + &self.features + } + + pub fn limits(&self) -> &wgt::Limits { + &self.limits + } + + pub fn downlevel(&self) -> &wgt::DownlevelCapabilities { + &self.downlevel + } +} + impl Device { pub(crate) fn raw(&self) -> &dyn hal::DynDevice { self.raw.as_ref() @@ -806,10 +823,14 @@ impl Device { assert!(self.queue.set(Arc::downgrade(queue)).is_ok()); } + /// Check device for freeable resources and completed buffer mappings. + /// + /// Return `queue_empty` indicating whether there are more queue submissions still in flight. pub fn poll( &self, poll_type: wgt::PollType, ) -> Result { + api_log!("Device::poll {poll_type:?}"); let (user_closures, result) = self.poll_and_return_closures(poll_type); user_closures.fire(); result @@ -1220,6 +1241,8 @@ impl Device { self: &Arc, desc: &resource::BufferDescriptor, ) -> (Arc, Option) { + profiling::scope!("Device::create_buffer"); + let (buffer, error) = match self.create_buffer_inner(desc) { Ok(buffer) => (buffer, None), Err(e) => (Buffer::invalid(Arc::clone(self), desc), Some(e)), @@ -1308,7 +1331,46 @@ impl Device { Ok(()) } - pub(crate) fn create_texture_from_hal( + /// # Safety + /// + /// - `hal_texture` must be created from `device_id` corresponding raw handle. + /// - `hal_texture` must be created respecting `desc` + /// - `hal_texture` must be initialized + /// - The `initial_state` must match the actual driver-side state of + /// the wrapped resource at the moment of wrap. + pub unsafe fn create_texture_from_hal( + self: &Arc, + hal_texture: Box, + desc: &resource::TextureDescriptor, + initial_state: wgt::TextureUses, + ) -> (Arc, Option) { + profiling::scope!("Device::create_texture_from_hal"); + + let (texture, error) = + match self.create_texture_from_hal_inner(hal_texture, desc, initial_state) { + Ok(texture) => (texture, None), + Err(e) => (Texture::invalid(self, desc), Some(e)), + }; + + // NB: Any change done through the raw texture handle will not be + // recorded in the replay + #[cfg(feature = "trace")] + if let Some(ref mut trace) = *self.trace.lock() { + trace.add(trace::Action::CreateTexture( + texture.to_trace(), + desc.clone(), + )); + } + + api_log!( + "Device::create_texture({desc:?}) -> {:?}", + Arc::as_ptr(&texture) + ); + + (texture, error) + } + + pub(crate) fn create_texture_from_hal_inner( self: &Arc, hal_texture: Box, desc: &resource::TextureDescriptor, @@ -1837,11 +1899,12 @@ impl Device { self: &Arc, desc: &resource::TextureDescriptor, ) -> (Arc, Option) { + profiling::scope!("Device::create_texture"); let (texture, error) = match self.create_texture_inner(desc) { Ok(texture) => (texture, None), Err(e) => { let texture = Texture::invalid(self, desc); - (Arc::new(texture), Some(e)) + (texture, Some(e)) } }; api_log!( @@ -1866,7 +1929,7 @@ impl Device { self: &Arc, desc: &resource::TextureDescriptor, ) -> Arc { - let texture = Arc::new(Texture::invalid(self, desc)); + let texture = Texture::invalid(self, desc); #[cfg(feature = "trace")] if let Some(ref mut trace) = *self.trace.lock() { use crate::device::trace::IntoTrace as _; @@ -2245,6 +2308,8 @@ impl Device { texture: &Arc, desc: &resource::TextureViewDescriptor, ) -> (Arc, Option) { + profiling::scope!("Texture::create_view"); + let (view, error) = match self.create_texture_view_inner(texture, desc) { Ok(view) => (view, None), Err(e) => (TextureView::invalid(self, texture, desc), Some(e)), @@ -2278,6 +2343,8 @@ impl Device { Arc, Option, ) { + profiling::scope!("Device::create_external_texture"); + let (external_texture, error) = match self.create_external_texture_inner(desc, planes) { Ok(external_texture) => (external_texture, None), Err(e) => (ExternalTexture::invalid(Arc::clone(self), desc), Some(e)), @@ -2545,6 +2612,7 @@ impl Device { Arc, Option, ) { + profiling::scope!("Device::create_shader_module"); #[cfg(feature = "trace")] let data = self.trace.lock().as_mut().map(|trace| { use crate::device::trace::DataKind; @@ -2895,7 +2963,29 @@ impl Device { Ok(Arc::new(module)) } - pub(crate) fn create_command_encoder( + pub fn create_command_encoder( + self: &Arc, + desc: &wgt::CommandEncoderDescriptor, + ) -> (Arc, Option) { + profiling::scope!("Device::create_command_encoder"); + + let (cmd_enc, error) = match self.create_command_encoder_inner(&desc.label) { + Ok(cmd_enc) => (cmd_enc, None), + Err(e) => ( + command::CommandEncoder::new_invalid(self, &desc.label, e.clone().into()), + Some(e), + ), + }; + + api_log!( + "Device::create_command_encoder -> {:?}", + Arc::as_ptr(&cmd_enc) + ); + + (cmd_enc, error) + } + + pub(crate) fn create_command_encoder_inner( self: &Arc, label: &crate::Label, ) -> Result, DeviceError> { @@ -2961,6 +3051,8 @@ impl Device { self: &Arc, desc: &binding_model::BindGroupLayoutDescriptor, ) -> (Arc, Option) { + profiling::scope!("Device::create_bind_group_layout"); + let (bgl, error) = match self.create_bind_group_layout_inner(desc) { Ok(layout) => (layout, None), Err(e) => ( @@ -2977,6 +3069,10 @@ impl Device { desc.clone(), )); } + api_log!( + "Device::create_bind_group_layout -> {:?}", + Arc::as_ptr(&bgl) + ); (bgl, error) } @@ -3674,6 +3770,7 @@ impl Device { self: &Arc, desc: &binding_model::ResolvedBindGroupDescriptor, ) -> (Arc, Option) { + profiling::scope!("Device::create_bind_group"); #[cfg(feature = "trace")] let trace_desc = (&desc).to_trace(); @@ -4162,6 +4259,7 @@ impl Device { Arc, Option, ) { + profiling::scope!("Device::create_pipeline_layout"); let (layout, error) = match self.create_pipeline_layout_impl(desc, false) { Ok(layout) => (layout, None), Err(e) => ( @@ -4355,6 +4453,7 @@ impl Device { Arc, Option, ) { + profiling::scope!("Device::create_compute_pipeline"); let (compute_pipeline, error) = match self.create_compute_pipeline_inner(desc.clone()) { Ok(compute_pipeline) => (compute_pipeline, None), Err(error) => ( @@ -4371,6 +4470,10 @@ impl Device { desc: desc.to_trace(), }); } + api_log!( + "Device::create_compute_pipeline -> {:?}", + Arc::as_ptr(&compute_pipeline) + ); (compute_pipeline, error) } @@ -4537,6 +4640,7 @@ impl Device { Arc, Option, ) { + profiling::scope!("Device::create_render_pipeline"); let (render_pipeline, error) = match self.create_render_pipeline_inner(desc.clone()) { Ok(pipeline) => (pipeline, None), Err(e) => ( @@ -4552,6 +4656,10 @@ impl Device { desc: desc.to_trace(), }); } + api_log!( + "Device::create_render_pipeline -> {:?}", + Arc::as_ptr(&render_pipeline) + ); (render_pipeline, error) } @@ -5493,6 +5601,7 @@ impl Device { Arc, Option, ) { + profiling::scope!("Device::create_pipeline_cache"); let (cache, error) = match unsafe { self.create_pipeline_cache_inner(desc) } { Ok(cache) => (cache, None), Err(e) => ( @@ -5627,6 +5736,7 @@ impl Device { self: &Arc, desc: &resource::QuerySetDescriptor, ) -> (Arc, Option) { + profiling::scope!("Device::create_query_set"); let (query_set, error) = match self.create_query_set_inner(desc) { Ok(query_set) => (query_set, None), Err(e) => (QuerySet::invalid(Arc::clone(self), desc), Some(e)), @@ -5698,12 +5808,22 @@ impl Device { pub fn configure_surface( self: &Arc, - surface: &crate::instance::Surface, + surface: &Arc, config: &wgt::SurfaceConfiguration>, ) -> Option { use present::ConfigureSurfaceError as E; profiling::scope!("surface_configure"); + #[cfg(feature = "trace")] + if let Some(ref mut trace) = *self.trace.lock() { + use trace::IntoTrace; + + trace.add(trace::Action::ConfigureSurface( + surface.to_trace(), + config.clone(), + )); + } + log::debug!("configuring surface with {config:?}"); let error = 'error: { @@ -5714,7 +5834,7 @@ impl Device { break 'error e.into(); } - let caps = match surface.get_capabilities(&self.adapter) { + let caps = match surface.get_hal_capabilities(&self.adapter) { Ok(caps) => caps, Err(_) => break 'error E::UnsupportedQueueFamily, }; @@ -5907,6 +6027,40 @@ impl Device { ) } + /// `device_lost_closure` might never be called. + pub fn set_device_lost_closure(&self, device_lost_closure: DeviceLostClosure) { + self.device_lost_closure.lock().replace(device_lost_closure); + } + + pub fn destroy(self: &Arc) { + api_log!("Device::destroy {:?}", Arc::as_ptr(self)); + + // Follow the steps at + // https://gpuweb.github.io/gpuweb/#dom-gpudevice-destroy. + // It's legal to call destroy multiple times, but if the device + // is already invalid, there's nothing more to do. There's also + // no need to return an error. + if !self.is_valid() { + return; + } + + // The last part of destroy is to lose the device. The spec says + // delay that until all "currently-enqueued operations on any + // queue on this device are completed." This is accomplished by + // setting valid to false, and then relying upon maintain to + // check for empty queues and a DeviceLostClosure. At that time, + // the DeviceLostClosure will be called with "destroyed" as the + // reason. + self.valid.store(false, Ordering::Release); + } + + pub fn get_internal_counters(&self) -> wgt::InternalCounters { + wgt::InternalCounters { + hal: self.get_hal_counters(), + core: wgt::CoreCounters {}, + } + } + pub fn get_hal_counters(&self) -> wgt::HalCounters { self.raw().get_internal_counters() } diff --git a/wgpu-core/src/instance.rs b/wgpu-core/src/instance.rs index 26a3050a4..6ae04e929 100644 --- a/wgpu-core/src/instance.rs +++ b/wgpu-core/src/instance.rs @@ -671,6 +671,42 @@ impl Surface { pub fn get_capabilities( &self, adapter: &Adapter, + ) -> Result { + profiling::scope!("Surface::get_capabilities"); + let mut hal_caps = self.get_hal_capabilities(adapter)?; + + hal_caps.formats.sort_by_key(|fc| !fc.format.is_srgb()); + + let usages = crate::conv::map_texture_usage_from_hal(hal_caps.usage); + + // `SurfaceCapabilities::formats` lists only the formats a + // color-space-unaware application can configure via + // `SurfaceColorSpace::Auto`, i.e. those for which `Auto` resolves to a + // concrete color space. (The full `format_capabilities` still reports + // every color space, including HDR ones, for explicit opt-in.) + Ok(wgt::SurfaceCapabilities { + formats: hal_caps + .formats + .iter() + .filter(|fc| { + crate::device::surface_config::resolve_auto_color_space( + fc.format, + fc.color_spaces, + ) + .is_some() + }) + .map(|fc| fc.format) + .collect(), + format_capabilities: hal_caps.formats, + present_modes: hal_caps.present_modes, + alpha_modes: hal_caps.composite_alpha_modes, + usages, + }) + } + + pub fn get_hal_capabilities( + &self, + adapter: &Adapter, ) -> Result { self.get_capabilities_with_raw(&adapter.raw) } @@ -695,6 +731,7 @@ impl Surface { /// Falls back to [`wgt::DisplayHdrInfo::default`] (all fields `None`) when the /// surface is not on `adapter`'s backend or the backend reports nothing. pub fn display_hdr_info(&self, adapter: &Adapter) -> wgt::DisplayHdrInfo { + profiling::scope!("Surface::display_hdr_info"); self.display_hdr_info_with_raw(&adapter.raw) } @@ -748,7 +785,7 @@ impl Adapter { // // This could occur if the user is running their app on Wayland but Vulkan does not support // VK_KHR_wayland_surface. - surface.get_capabilities(self).is_ok() + surface.get_hal_capabilities(self).is_ok() } pub fn get_info(&self) -> wgt::AdapterInfo { diff --git a/wgpu-core/src/pipeline.rs b/wgpu-core/src/pipeline.rs index 5d5aeae75..9f635a422 100644 --- a/wgpu-core/src/pipeline.rs +++ b/wgpu-core/src/pipeline.rs @@ -82,7 +82,10 @@ pub struct ShaderModule { } impl Drop for ShaderModule { + #[allow(trivial_casts)] fn drop(&mut self) { + profiling::scope!("ShaderModule::drop"); + api_log!("ShaderModule::drop {:?}", self as *const _); resource_log!("Destroy raw {}", self.error_ident()); #[cfg(feature = "trace")] if let Some(t) = self.device.trace.lock().as_mut() { @@ -347,7 +350,10 @@ pub struct ComputePipeline { } impl Drop for ComputePipeline { + #[allow(trivial_casts)] fn drop(&mut self) { + profiling::scope!("ComputePipeline::drop"); + api_log!("ComputePipeline::drop {:?}", self as *const _); resource_log!("Destroy raw {}", self.error_ident()); #[cfg(feature = "trace")] { @@ -1015,7 +1021,10 @@ pub struct RenderPipeline { } impl Drop for RenderPipeline { + #[allow(trivial_casts)] fn drop(&mut self) { + profiling::scope!("RenderPipeline::drop"); + api_log!("RenderPipeline::drop {:?}", self as *const _); resource_log!("Destroy raw {}", self.error_ident()); #[cfg(feature = "trace")] { diff --git a/wgpu-core/src/resource.rs b/wgpu-core/src/resource.rs index d174d9813..7053127a6 100644 --- a/wgpu-core/src/resource.rs +++ b/wgpu-core/src/resource.rs @@ -464,7 +464,10 @@ pub struct Buffer { } impl Drop for Buffer { + #[allow(trivial_casts)] fn drop(&mut self) { + profiling::scope!("Buffer::drop"); + api_log!("Buffer::drop {:?}", self as *const _); #[cfg(feature = "trace")] if let Some(t) = self.device.trace.lock().as_mut() { t.add(trace::Action::DropBuffer(unsafe { trace::to_trace(self) })); @@ -568,7 +571,7 @@ impl Buffer { self.state().map(|_| ()) } - pub(crate) fn invalid(device: Arc, desc: &BufferDescriptor) -> Arc { + pub fn invalid(device: Arc, desc: &BufferDescriptor) -> Arc { Arc::new(Buffer { state: ResourceState::Invalid, usage: desc.usage, @@ -672,6 +675,12 @@ impl Buffer { size: Option, op: BufferMapOperation, ) -> Result { + profiling::scope!("Buffer::map_async"); + api_log!( + "Buffer::map_async {:?} offset {offset:?} size {size:?} op: {op:?}", + Arc::as_ptr(self) + ); + self.try_map_async(offset, size, op) .map_err(|(mut operation, err)| { if let Some(callback) = operation.callback.take() { @@ -986,6 +995,8 @@ impl Buffer { // Note: This must not be called while holding a lock. pub fn unmap(self: &Arc) -> Result<(), BufferAccessError> { + profiling::scope!("unmap", "Buffer"); + api_log!("Buffer::unmap {:?}", Arc::as_ptr(self)); if let Some((mut operation, status)) = self.unmap_inner()? { if let Some(callback) = operation.callback.take() { callback(status); @@ -1097,6 +1108,9 @@ impl Buffer { } pub fn destroy(self: &Arc) { + profiling::scope!("Buffer::destroy"); + api_log!("Buffer::destroy {:?}", Arc::as_ptr(self)); + let device = &self.device; #[cfg(feature = "trace")] @@ -1514,8 +1528,8 @@ impl Texture { } } - pub(crate) fn invalid(device: &Arc, desc: &TextureDescriptor) -> Self { - Texture { + pub fn invalid(device: &Arc, desc: &TextureDescriptor) -> Arc { + Arc::new(Texture { state: ResourceState::Invalid, device: device.clone(), desc: desc.map_label(|label| label.to_string()), @@ -1536,7 +1550,7 @@ impl Texture { clear_mode: RwLock::new(rank::TEXTURE_CLEAR_MODE, TextureClearMode::None), views: Mutex::new(rank::TEXTURE_VIEWS, WeakVec::new()), bind_groups: Mutex::new(rank::TEXTURE_BIND_GROUPS, WeakVec::new()), - } + }) } /// Checks that the given texture usage contains the required texture usage, @@ -1558,7 +1572,11 @@ impl Texture { } impl Drop for Texture { + #[allow(trivial_casts)] fn drop(&mut self) { + profiling::scope!("Texture::drop"); + api_log!("Texture::drop {:?}", self as *const _); + #[cfg(feature = "trace")] { let mut t = self.device.trace.lock(); @@ -1683,6 +1701,16 @@ impl Texture { } pub fn destroy(self: &Arc) { + profiling::scope!("Texture::destroy"); + api_log!("Texture::destroy {:?}", Arc::as_ptr(self)); + + #[cfg(feature = "trace")] + if let Some(trace) = self.device.trace.lock().as_mut() { + use crate::device::trace::IntoTrace as _; + + trace.add(trace::Action::DestroyTexture(self.to_trace())); + } + let device = &self.device; let ResourceState::Valid(state) = &self.state else { @@ -2278,7 +2306,11 @@ pub struct ExternalTexture { } impl Drop for ExternalTexture { + #[allow(trivial_casts)] fn drop(&mut self) { + profiling::scope!("ExternalTexture::drop"); + api_log!("ExternalTexture::drop {:?}", self as *const _); + resource_log!("Destroy raw {}", self.error_ident()); #[cfg(feature = "trace")] if let Some(t) = self.device.trace.lock().as_mut() { @@ -2298,6 +2330,9 @@ impl ExternalTexture { } pub fn destroy(self: &Arc) { + profiling::scope!("ExternalTexture::destroy"); + api_log!("ExternalTexture::destroy {:?}", Arc::as_ptr(self)); + #[cfg(feature = "trace")] if let Some(trace) = self.device.trace.lock().as_mut() { use crate::device::trace::IntoTrace as _; @@ -2661,7 +2696,10 @@ impl QuerySet { } impl Drop for QuerySet { + #[allow(trivial_casts)] fn drop(&mut self) { + profiling::scope!("QuerySet::drop"); + api_log!("QuerySet::drop {:?}", self as *const _); resource_log!("Destroy raw {}", self.error_ident()); #[cfg(feature = "trace")] if let Some(trace) = self.device.trace.lock().as_mut() {