From dffe1f1793765c240e98c63b0b76e0ecd4e2a870 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 10 Aug 2021 01:46:34 -0400 Subject: [PATCH] Return a texture by the surface --- CHANGELOG.md | 2 +- player/src/lib.rs | 4 +- wgpu-core/src/binding_model.rs | 2 - wgpu-core/src/command/clear.rs | 4 +- wgpu-core/src/command/render.rs | 95 ++++----------- wgpu-core/src/command/transfer.rs | 16 +-- wgpu-core/src/device/life.rs | 35 +++--- wgpu-core/src/device/mod.rs | 139 +++++++++------------- wgpu-core/src/device/queue.rs | 18 ++- wgpu-core/src/device/trace.rs | 2 +- wgpu-core/src/hub.rs | 20 ++-- wgpu-core/src/instance.rs | 7 +- wgpu-core/src/present.rs | 166 ++++++++++++--------------- wgpu-core/src/resource.rs | 39 +++++-- wgpu-core/src/track/mod.rs | 2 +- wgpu/examples/framework.rs | 3 +- wgpu/examples/hello-triangle/main.rs | 3 +- wgpu/examples/hello-windows/main.rs | 3 +- wgpu/src/backend/direct.rs | 17 +-- wgpu/src/lib.rs | 22 ++-- 20 files changed, 251 insertions(+), 348 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b1f4c7604..2e09667ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ - processing SPIR-V inputs for later translation now requires `spirv` compile feature enabled - new `Features::SPIRV_SHADER_PASSTHROUGH` run-time feature allows providing pass-through SPIR-V (orthogonal to the compile feature) - several bitflag names are renamed to plural: `TextureUsage`, `BufferUsage`, `ColorWrite`. - - the `SwapChain` is merged into `Surface`. + - the `SwapChain` is merged into `Surface`. Returned frames are `Texture` instead of `TextureView`. - renamed `TextureUsage` bits: `SAMPLED` -> `TEXTURE_BINDING`, `STORAGE` -> `STORAGE_BINDING`. - renamed `InputStepMode` to `VertexStepMode` - Implemented `Rgb9e5Ufloat` format. diff --git a/player/src/lib.rs b/player/src/lib.rs index 87c21e2f6..e7d8502a9 100644 --- a/player/src/lib.rs +++ b/player/src/lib.rs @@ -204,9 +204,9 @@ impl GlobalPlay for wgc::hub::Global { } Action::GetSurfaceTexture { id, parent_id } => { self.device_maintain_ids::(device).unwrap(); - self.surface_get_current_texture_view::(parent_id, id) + self.surface_get_current_texture::(parent_id, id) .unwrap() - .view_id + .texture_id .unwrap(); } Action::CreateBindGroupLayout(id, desc) => { diff --git a/wgpu-core/src/binding_model.rs b/wgpu-core/src/binding_model.rs index ab932e50d..86db06816 100644 --- a/wgpu-core/src/binding_model.rs +++ b/wgpu-core/src/binding_model.rs @@ -91,8 +91,6 @@ pub enum CreateBindGroupError { MissingTextureUsage(#[from] MissingTextureUsageError), #[error("binding declared as a single item, but bind group is using it as an array")] SingleBindingExpected, - #[error("unable to create a bind group with a surface image")] - SurfaceImage, #[error("buffer offset {0} does not respect `BIND_BUFFER_ALIGNMENT`")] UnalignedBufferOffset(wgt::BufferAddress), #[error( diff --git a/wgpu-core/src/command/clear.rs b/wgpu-core/src/command/clear.rs index b0fca96eb..129f0e029 100644 --- a/wgpu-core/src/command/clear.rs +++ b/wgpu-core/src/command/clear.rs @@ -233,8 +233,8 @@ impl Global { ) .map_err(ClearError::InvalidTexture)?; let _dst_raw = dst_texture - .raw - .as_ref() + .inner + .as_raw() .ok_or(ClearError::InvalidTexture(dst))?; if !dst_texture.desc.usage.contains(TextureUsages::COPY_DST) { return Err(ClearError::MissingCopyDstUsageFlag(None, Some(dst))); diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index f74840779..b40b2bb15 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -16,7 +16,7 @@ use crate::{ instance::Surface, memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction}, pipeline::PipelineFlags, - resource::{Texture, TextureView, TextureViewSource}, + resource::{Texture, TextureView}, track::{StatefulTrackerSubset, TextureSelector, UsageConflict}, validation::{ check_buffer_usage, check_texture_usage, MissingBufferUsageError, MissingTextureUsageError, @@ -513,6 +513,16 @@ struct RenderAttachment<'a> { usage: hal::TextureUses, } +impl TextureView { + fn to_render_attachment(&self, usage: hal::TextureUses) -> RenderAttachment { + RenderAttachment { + texture_id: &self.parent_id, + selector: &self.selector, + usage, + } + } +} + const MAX_TOTAL_ATTACHMENTS: usize = hal::MAX_COLOR_TARGETS + hal::MAX_COLOR_TARGETS + 1; type AttachmentDataVec = ArrayVec; @@ -533,7 +543,7 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> { depth_stencil_attachment: Option<&RenderPassDepthStencilAttachment>, cmd_buf: &mut CommandBuffer, view_guard: &'a Storage, id::TextureViewId>, - surface_guard: &'a Storage, + _surface_guard: &'a Storage, ) -> Result { profiling::scope!("start", "RenderPassInfo"); @@ -547,7 +557,8 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> { let mut attachment_type_name = ""; let mut extent = None; let mut sample_count = 0; - let mut used_surface = None::<(id::Valid, hal::TextureUses)>; + //TODO: remove this? + let used_surface = None::<(id::Valid, hal::TextureUses)>; let mut add_view = |view: &TextureView, type_name| { if let Some(ex) = extent { @@ -590,22 +601,13 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> { )); } - let source_id = match view.source { - TextureViewSource::Native(ref source_id) => source_id, - TextureViewSource::Surface(_) => unreachable!(), - }; - let usage = if at.is_read_only(ds_aspects)? { is_ds_read_only = true; hal::TextureUses::DEPTH_STENCIL_READ | hal::TextureUses::RESOURCE } else { hal::TextureUses::DEPTH_STENCIL_WRITE }; - render_attachments.push(RenderAttachment { - texture_id: source_id, - selector: &view.selector, - usage, - }); + render_attachments.push(view.to_render_attachment(usage)); depth_stencil = Some(hal::DepthStencilAttachment { target: hal::Attachment { @@ -636,24 +638,8 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> { )); } - match color_view.source { - TextureViewSource::Native(ref source_id) => { - render_attachments.push(RenderAttachment { - texture_id: source_id, - selector: &color_view.selector, - usage: hal::TextureUses::COLOR_TARGET, - }); - } - TextureViewSource::Surface(source_id) => { - //HACK: guess the start usage based on the load op - let start_usage = match at.channel.load_op { - LoadOp::Load => hal::TextureUses::empty(), - LoadOp::Clear => hal::TextureUses::UNINITIALIZED, - }; - assert!(used_surface.is_none()); - used_surface = Some((source_id, start_usage)); - } - }; + render_attachments + .push(color_view.to_render_attachment(hal::TextureUses::COLOR_TARGET)); let mut hal_resolve_target = None; if let Some(resolve_target) = at.resolve_target { @@ -675,21 +661,8 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> { return Err(RenderPassErrorInner::InvalidResolveTargetSampleCount); } - match resolve_view.source { - TextureViewSource::Native(ref source_id) => { - render_attachments.push(RenderAttachment { - texture_id: source_id, - selector: &resolve_view.selector, - usage: hal::TextureUses::COLOR_TARGET, - }); - } - TextureViewSource::Surface(source_id) => { - //HACK: guess the start usage - let start_usage = hal::TextureUses::UNINITIALIZED; - assert!(used_surface.is_none()); - used_surface = Some((source_id, start_usage)); - } - }; + render_attachments + .push(resolve_view.to_render_attachment(hal::TextureUses::COLOR_TARGET)); hal_resolve_target = Some(hal::Attachment { view: &resolve_view.raw, @@ -712,21 +685,6 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> { return Err(RenderPassErrorInner::InvalidSampleCount(sample_count)); } - if let Some((surface_id, start_usage)) = used_surface { - let suf_texture = A::get_surface(&surface_guard[surface_id]) - .acquired_texture - .as_ref() - .unwrap(); - let barrier = hal::TextureBarrier { - texture: std::borrow::Borrow::borrow(suf_texture), - usage: start_usage..hal::TextureUses::COLOR_TARGET, - range: wgt::ImageSubresourceRange::default(), - }; - unsafe { - cmd_buf.encoder.raw.transition_textures(iter::once(barrier)); - } - } - let view_data = AttachmentData { colors: color_attachments .iter() @@ -771,7 +729,7 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> { mut self, raw: &mut A::CommandEncoder, texture_guard: &Storage, id::TextureId>, - surface_guard: &Storage, + _surface_guard: &Storage, ) -> Result<(StatefulTrackerSubset, Option>), RenderPassErrorInner> { profiling::scope!("finish", "RenderPassInfo"); @@ -779,19 +737,6 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> { raw.end_render_pass(); } - if let Some(surface_id) = self.used_surface { - let suf = A::get_surface(&surface_guard[surface_id]); - let suf_texture = suf.acquired_texture.as_ref().unwrap(); - let barrier = hal::TextureBarrier { - texture: std::borrow::Borrow::borrow(suf_texture), - usage: hal::TextureUses::COLOR_TARGET..hal::TextureUses::empty(), - range: wgt::ImageSubresourceRange::default(), - }; - unsafe { - raw.transition_textures(iter::once(barrier)); - } - } - for ra in self.render_attachments { let texture = &texture_guard[ra.texture_id.value]; check_texture_usage(texture.desc.usage, TextureUsages::RENDER_ATTACHMENT)?; diff --git a/wgpu-core/src/command/transfer.rs b/wgpu-core/src/command/transfer.rs index ee945216d..c5db24cf6 100644 --- a/wgpu-core/src/command/transfer.rs +++ b/wgpu-core/src/command/transfer.rs @@ -555,8 +555,8 @@ impl Global { ) .unwrap(); let dst_raw = dst_texture - .raw - .as_ref() + .inner + .as_raw() .ok_or(TransferError::InvalidTexture(destination.texture))?; if !dst_texture.desc.usage.contains(TextureUsages::COPY_DST) { return Err( @@ -664,8 +664,8 @@ impl Global { ) .unwrap(); let src_raw = src_texture - .raw - .as_ref() + .inner + .as_raw() .ok_or(TransferError::InvalidTexture(source.texture))?; if !src_texture.desc.usage.contains(TextureUsages::COPY_SRC) { return Err(TransferError::MissingCopySrcUsageFlag.into()); @@ -801,8 +801,8 @@ impl Global { ) .unwrap(); let src_raw = src_texture - .raw - .as_ref() + .inner + .as_raw() .ok_or(TransferError::InvalidTexture(source.texture))?; if !src_texture.desc.usage.contains(TextureUsages::COPY_SRC) { return Err(TransferError::MissingCopySrcUsageFlag.into()); @@ -824,8 +824,8 @@ impl Global { ) .unwrap(); let dst_raw = dst_texture - .raw - .as_ref() + .inner + .as_raw() .ok_or(TransferError::InvalidTexture(destination.texture))?; if !dst_texture.desc.usage.contains(TextureUsages::COPY_DST) { return Err( diff --git a/wgpu-core/src/device/life.rs b/wgpu-core/src/device/life.rs index 99b70a2da..3f934b845 100644 --- a/wgpu-core/src/device/life.rs +++ b/wgpu-core/src/device/life.rs @@ -307,20 +307,6 @@ impl LifetimeTracker { } impl LifetimeTracker { - pub(super) fn schedule_texture_view_for_destruction( - &mut self, - id: id::Valid, - view: resource::TextureView, - ) { - let submit_index = view.life_guard.submission_index.load(Ordering::Acquire); - self.active - .iter_mut() - .find(|a| a.index == submit_index) - .map_or(&mut self.free_resources, |a| &mut a.last_resources) - .texture_views - .push((id, view.raw)); - } - pub(super) fn triage_suspected( &mut self, hub: &Hub, @@ -387,13 +373,14 @@ impl LifetimeTracker { } if let Some(res) = hub.texture_views.unregister_locked(id.0, &mut *guard) { - match res.source { - resource::TextureViewSource::Native(ref source_id) => { - self.suspected_resources.textures.push(source_id.value); - } - resource::TextureViewSource::Surface { .. } => {} - }; - self.schedule_texture_view_for_destruction(id, res); + self.suspected_resources.textures.push(res.parent_id.value); + let submit_index = res.life_guard.submission_index.load(Ordering::Acquire); + self.active + .iter_mut() + .find(|a| a.index == submit_index) + .map_or(&mut self.free_resources, |a| &mut a.last_resources) + .texture_views + .push((id, res.raw)); } } } @@ -413,12 +400,16 @@ impl LifetimeTracker { if let Some(res) = hub.textures.unregister_locked(id.0, &mut *guard) { let submit_index = res.life_guard.submission_index.load(Ordering::Acquire); + let raw = match res.inner { + resource::TextureInner::Native { raw: Some(raw) } => raw, + _ => continue, + }; self.active .iter_mut() .find(|a| a.index == submit_index) .map_or(&mut self.free_resources, |a| &mut a.last_resources) .textures - .extend(res.raw); + .push(raw); } } } diff --git a/wgpu-core/src/device/mod.rs b/wgpu-core/src/device/mod.rs index a0ba25dac..efe6b9c60 100644 --- a/wgpu-core/src/device/mod.rs +++ b/wgpu-core/src/device/mod.rs @@ -341,16 +341,6 @@ impl Device { self.life_tracker.lock() } - pub(crate) fn schedule_rogue_texture_view_for_destruction<'this, 'token: 'this>( - &'this self, - view_id: id::Valid, - view: resource::TextureView, - token: &mut Token<'token, Self>, - ) { - self.lock_life(token) - .schedule_texture_view_for_destruction(view_id, view); - } - fn maintain<'this, 'token: 'this, G: GlobalIdentityHandlerFactory>( &'this self, hub: &Hub, @@ -570,7 +560,9 @@ impl Device { } Ok(resource::Texture { - raw: Some(hal_texture), + inner: resource::TextureInner::Native { + raw: Some(hal_texture), + }, device_id: Stored { value: id::Valid(self_id), ref_count: self.life_guard.add_ref(), @@ -619,8 +611,8 @@ impl Device { desc: &resource::TextureViewDescriptor, ) -> Result, resource::CreateTextureViewError> { let texture_raw = texture - .raw - .as_ref() + .inner + .as_raw() .ok_or(resource::CreateTextureViewError::InvalidTexture)?; let view_dim = match desc.dimension { @@ -783,10 +775,10 @@ impl Device { Ok(resource::TextureView { raw, - source: resource::TextureViewSource::Native(Stored { + parent_id: Stored { value: id::Valid(texture_id), ref_count: texture.life_guard.add_ref(), - }), + }, desc: resource::HalTextureViewDescriptor { format: hal_desc.format, dimension: hal_desc.dimension, @@ -1433,25 +1425,18 @@ impl Device { "SampledTexture, ReadonlyStorageTexture or WriteonlyStorageTexture", )?; - match view.source { - resource::TextureViewSource::Native(ref source_id) => { - // Careful here: the texture may no longer have its own ref count, - // if it was deleted by the user. - let texture = &texture_guard[source_id.value]; - used.textures - .change_extend( - source_id.value, - &source_id.ref_count, - view.selector.clone(), - internal_use, - ) - .map_err(UsageConflict::from)?; - check_texture_usage(texture.desc.usage, pub_usage)?; - } - resource::TextureViewSource::Surface(_) => { - return Err(Error::SurfaceImage); - } - } + // Careful here: the texture may no longer have its own ref count, + // if it was deleted by the user. + used.textures + .change_extend( + view.parent_id.value, + &view.parent_id.ref_count, + view.selector.clone(), + internal_use, + ) + .map_err(UsageConflict::from)?; + let texture = &texture_guard[view.parent_id.value]; + check_texture_usage(texture.desc.usage, pub_usage)?; let res_index = hal_textures.len(); hal_textures.push(hal::TextureBinding { @@ -1480,30 +1465,23 @@ impl Device { .views .use_extend(&*texture_view_guard, id, (), ()) .map_err(|_| Error::InvalidTextureView(id))?; - let (pub_usage, internal_use) = - Self::texture_use_parameters(binding, decl, view, - "SampledTextureArray, ReadonlyStorageTextureArray or WriteonlyStorageTextureArray" -)?; + let (pub_usage, internal_use) = Self::texture_use_parameters( + binding, decl, view, + "SampledTextureArray, ReadonlyStorageTextureArray or WriteonlyStorageTextureArray" + )?; - match view.source { - resource::TextureViewSource::Native(ref source_id) => { - // Careful here: the texture may no longer have its own ref count, - // if it was deleted by the user. - let texture = &texture_guard[source_id.value]; - used.textures - .change_extend( - source_id.value, - &source_id.ref_count, - view.selector.clone(), - internal_use, - ) - .map_err(UsageConflict::from)?; - check_texture_usage(texture.desc.usage, pub_usage)?; - } - resource::TextureViewSource::Surface(_) => { - return Err(Error::SurfaceImage); - } - } + // Careful here: the texture may no longer have its own ref count, + // if it was deleted by the user. + used.textures + .change_extend( + view.parent_id.value, + &view.parent_id.ref_count, + view.selector.clone(), + internal_use, + ) + .map_err(UsageConflict::from)?; + let texture = &texture_guard[view.parent_id.value]; + check_texture_usage(texture.desc.usage, pub_usage)?; hal_textures.push(hal::TextureBinding { view: &view.raw, @@ -2450,14 +2428,6 @@ impl Device { } } - pub(crate) fn destroy_texture(&self, texture: resource::Texture) { - if let Some(raw) = texture.raw { - unsafe { - self.raw.destroy_texture(raw); - } - } - } - pub(crate) fn destroy_command_buffer(&self, cmd_buf: command::CommandBuffer) { let mut baked = cmd_buf.into_baked(); unsafe { @@ -3120,20 +3090,23 @@ impl Global { trace.lock().add(trace::Action::FreeTexture(texture_id)); } - let raw = texture - .raw - .take() - .ok_or(resource::DestroyError::AlreadyDestroyed)?; - let temp = queue::TempResource::Texture(raw); + match texture.inner { + resource::TextureInner::Native { ref mut raw } => { + let raw = raw.take().ok_or(resource::DestroyError::AlreadyDestroyed)?; + let temp = queue::TempResource::Texture(raw); - if device.pending_writes.dst_textures.contains(&texture_id) { - device.pending_writes.temp_resources.push(temp); - } else { - let last_submit_index = texture.life_guard.submission_index.load(Ordering::Acquire); - drop(texture_guard); - device - .lock_life(&mut token) - .schedule_resource_destruction(temp, last_submit_index); + if device.pending_writes.dst_textures.contains(&texture_id) { + device.pending_writes.temp_resources.push(temp); + } else { + let last_submit_index = + texture.life_guard.submission_index.load(Ordering::Acquire); + drop(texture_guard); + device + .lock_life(&mut token) + .schedule_resource_destruction(temp, last_submit_index); + } + } + resource::TextureInner::Surface { .. } => {} //TODO } Ok(()) @@ -3260,14 +3233,7 @@ impl Global { let _ref_count = view.life_guard.ref_count.take(); let last_submit_index = view.life_guard.submission_index.load(Ordering::Acquire); - let device_id = match view.source { - resource::TextureViewSource::Native(ref source_id) => { - texture_guard[source_id.value].device_id.value - } - resource::TextureViewSource::Surface(_) => { - return Err(resource::TextureViewDestroyError::SurfaceImage) - } - }; + let device_id = texture_guard[view.parent_id.value].device_id.value; (last_submit_index, device_id) } Err(InvalidId) => { @@ -4429,7 +4395,6 @@ impl Global { config: config.clone(), num_frames, acquired_texture: None, - active_submission_index: 0, }); return None; diff --git a/wgpu-core/src/device/queue.rs b/wgpu-core/src/device/queue.rs index e90ad2981..ac5800e2f 100644 --- a/wgpu-core/src/device/queue.rs +++ b/wgpu-core/src/device/queue.rs @@ -410,8 +410,8 @@ impl Global { ) .unwrap(); let dst_raw = dst - .raw - .as_ref() + .inner + .as_raw() .ok_or(TransferError::InvalidTexture(destination.texture))?; if !dst.desc.usage.contains(wgt::TextureUsages::COPY_DST) { @@ -569,15 +569,13 @@ impl Global { // optimize the tracked states cmdbuf.trackers.optimize(); + //TODO: do we need this code? for surface_id in cmdbuf.used_surfaces.drain(..) { - let surface = &mut surface_guard[surface_id]; - let suf = A::get_surface_mut(surface); - if suf.acquired_texture.is_none() { - return Err(QueueSubmitError::SurfaceOutputDropped); - } - match surface.presentation { + match surface_guard[surface_id].presentation { Some(ref mut present) => { - present.active_submission_index = submit_index; + if present.acquired_texture.is_none() { + return Err(QueueSubmitError::SurfaceOutputDropped); + } } None => return Err(QueueSubmitError::SurfaceUnconfigured), } @@ -608,7 +606,7 @@ impl Global { } for id in cmdbuf.trackers.textures.used() { let texture = &texture_guard[id]; - if texture.raw.is_none() { + if texture.inner.as_raw().is_none() { return Err(QueueSubmitError::DestroyedTexture(id.0)); } if !texture.life_guard.use_at(submit_index) { diff --git a/wgpu-core/src/device/trace.rs b/wgpu-core/src/device/trace.rs index 417b43e46..e00e077c4 100644 --- a/wgpu-core/src/device/trace.rs +++ b/wgpu-core/src/device/trace.rs @@ -55,7 +55,7 @@ pub enum Action<'a> { CreateSampler(id::SamplerId, crate::resource::SamplerDescriptor<'a>), DestroySampler(id::SamplerId), GetSurfaceTexture { - id: id::TextureViewId, + id: id::TextureId, parent_id: id::SurfaceId, }, Present(id::SurfaceId), diff --git a/wgpu-core/src/hub.rs b/wgpu-core/src/hub.rs index ba748fe7a..9ab42ce85 100644 --- a/wgpu-core/src/hub.rs +++ b/wgpu-core/src/hub.rs @@ -617,7 +617,7 @@ impl Hub { // we should have `clear_device(device_id)` that specifically destroys // everything related to a logical device. fn clear(&self, surface_guard: &mut Storage, with_adapters: bool) { - use crate::resource::TextureViewSource; + use crate::resource::TextureInner; use hal::{Device as _, Surface as _}; let mut devices = self.devices.data.write(); @@ -648,14 +648,9 @@ impl Hub { let textures = self.textures.data.read(); for element in self.texture_views.data.write().map.drain(..) { if let Element::Occupied(texture_view, _) = element { - match texture_view.source { - TextureViewSource::Native(source_id) => { - let device = &devices[textures[source_id.value].device_id.value]; - unsafe { - device.raw.destroy_texture_view(texture_view.raw); - } - } - TextureViewSource::Surface(_) => {} //TODO + let device = &devices[textures[texture_view.parent_id.value].device_id.value]; + unsafe { + device.raw.destroy_texture_view(texture_view.raw); } } } @@ -663,7 +658,12 @@ impl Hub { for element in self.textures.data.write().map.drain(..) { if let Element::Occupied(texture, _) = element { - devices[texture.device_id.value].destroy_texture(texture); + let device = &devices[texture.device_id.value]; + if let TextureInner::Native { raw: Some(raw) } = texture.inner { + unsafe { + device.raw.destroy_texture(raw); + } + } } } for element in self.buffers.data.write().map.drain(..) { diff --git a/wgpu-core/src/instance.rs b/wgpu-core/src/instance.rs index d821bcc12..397fe0423 100644 --- a/wgpu-core/src/instance.rs +++ b/wgpu-core/src/instance.rs @@ -13,9 +13,10 @@ use thiserror::Error; pub type RequestAdapterOptions = wgt::RequestAdapterOptions; type HalInstance = ::Instance; +//TODO: remove this pub struct HalSurface { pub raw: A::Surface, - pub acquired_texture: Option, + //pub acquired_texture: Option, } #[derive(Clone, Debug, Error)] @@ -449,7 +450,7 @@ impl Global { match inst.create_surface(handle) { Ok(raw) => Some(HalSurface { raw, - acquired_texture: None, + //acquired_texture: None, }), Err(e) => { log::warn!("Error: {:?}", e); @@ -494,7 +495,7 @@ impl Global { #[allow(clippy::transmute_ptr_to_ref)] inst.create_surface_from_layer(unsafe { std::mem::transmute(layer) }) }, - acquired_texture: None, + //acquired_texture: None, }), }; diff --git a/wgpu-core/src/present.rs b/wgpu-core/src/present.rs index 61bd630e7..508cba055 100644 --- a/wgpu-core/src/present.rs +++ b/wgpu-core/src/present.rs @@ -11,16 +11,16 @@ #[cfg(feature = "trace")] use crate::device::trace::Action; use crate::{ + conv, device::DeviceError, hub::{Global, GlobalIdentityHandlerFactory, HalApi, Input, Token}, - id::{DeviceId, SurfaceId, TextureViewId, Valid}, + id::{DeviceId, SurfaceId, TextureId, Valid}, resource, track::TextureSelector, - LifeGuard, Stored, SubmissionIndex, + LifeGuard, Stored, }; -use hal::{Device as _, Queue as _, Surface as _}; -use std::borrow::Borrow; +use hal::{Queue as _, Surface as _}; use thiserror::Error; use wgt::SurfaceStatus as Status; @@ -32,8 +32,7 @@ pub(crate) struct Presentation { pub(crate) device_id: Stored, pub(crate) config: wgt::SurfaceConfiguration, pub(crate) num_frames: u32, - pub(crate) acquired_texture: Option>, - pub(crate) active_submission_index: SubmissionIndex, + pub(crate) acquired_texture: Option>, } #[derive(Clone, Debug, Error)] @@ -75,20 +74,20 @@ pub enum ConfigureSurfaceError { #[derive(Debug)] pub struct SurfaceOutput { pub status: Status, - pub view_id: Option, + pub texture_id: Option, } impl Global { - pub fn surface_get_current_texture_view( + pub fn surface_get_current_texture( &self, surface_id: SurfaceId, - view_id_in: Input, + texture_id_in: Input, ) -> Result { profiling::scope!("get_next_texture", "SwapChain"); let hub = A::hub(self); let mut token = Token::root(); - let fid = hub.texture_views.prepare(view_id_in); + let fid = hub.textures.prepare(texture_id_in); let (mut surface_guard, mut token) = self.surfaces.write(&mut token); let surface = surface_guard @@ -96,8 +95,11 @@ impl Global { .map_err(|_| SurfaceError::Invalid)?; let (device_guard, mut token) = hub.devices.read(&mut token); - let device = match surface.presentation { - Some(ref present) => &device_guard[present.device_id.value], + let (device, config) = match surface.presentation { + Some(ref present) => { + let device = &device_guard[present.device_id.value]; + (device, present.config.clone()) + } None => return Err(SurfaceError::NotConfigured), }; @@ -108,17 +110,64 @@ impl Global { parent_id: surface_id, }); } + #[cfg(not(feature = "trace"))] + let _ = device; - let config = surface.presentation.as_ref().unwrap().config.clone(); let suf = A::get_surface_mut(surface); - let (texture, status) = match unsafe { suf.raw.acquire_texture(FRAME_TIMEOUT_MS) } { + let (texture_id, status) = match unsafe { suf.raw.acquire_texture(FRAME_TIMEOUT_MS) } { Ok(Some(ast)) => { + let present = surface.presentation.as_mut().unwrap(); + let texture = resource::Texture { + inner: resource::TextureInner::Surface { + raw: ast.texture, + parent_id: Valid(surface_id), + }, + device_id: present.device_id.clone(), + desc: wgt::TextureDescriptor { + label: (), + size: wgt::Extent3d { + width: config.width, + height: config.height, + depth_or_array_layers: 1, + }, + sample_count: 1, + mip_level_count: 1, + format: config.format, + dimension: wgt::TextureDimension::D2, + usage: config.usage, + }, + hal_usage: conv::map_texture_usage(config.usage, config.format.into()), + format_features: wgt::TextureFormatFeatures { + allowed_usages: wgt::TextureUsages::RENDER_ATTACHMENT, + flags: wgt::TextureFormatFeatureFlags::empty(), + filterable: false, + }, + full_range: TextureSelector { + layers: 0..1, + levels: 0..1, + }, + life_guard: LifeGuard::new(""), + }; + + let ref_count = texture.life_guard.add_ref(); + let id = fid.assign(texture, &mut token); + + //suf.acquired_texture = Some(suf_texture); + + if present.acquired_texture.is_some() { + return Err(SurfaceError::AlreadyAcquired); + } + present.acquired_texture = Some(Stored { + value: id, + ref_count, + }); + let status = if ast.suboptimal { Status::Suboptimal } else { Status::Good }; - (Some(ast.texture), status) + (Some(id.0), status) } Ok(None) => (None, Status::Timeout), Err(err) => ( @@ -137,69 +186,7 @@ impl Global { ), }; - let hal_desc = hal::TextureViewDescriptor { - label: Some("_Frame"), - format: config.format, - dimension: wgt::TextureViewDimension::D2, - usage: hal::TextureUses::COLOR_TARGET, - range: wgt::ImageSubresourceRange::default(), - }; - - let view_id = match texture { - Some(suf_texture) => { - let raw = unsafe { - device - .raw - .create_texture_view(suf_texture.borrow(), &hal_desc) - .map_err(DeviceError::from)? - }; - let view = resource::TextureView { - raw, - source: resource::TextureViewSource::Surface(Valid(surface_id)), - desc: resource::HalTextureViewDescriptor { - format: config.format, - dimension: wgt::TextureViewDimension::D2, - range: wgt::ImageSubresourceRange::default(), - }, - format_features: wgt::TextureFormatFeatures { - allowed_usages: wgt::TextureUsages::RENDER_ATTACHMENT, - flags: wgt::TextureFormatFeatureFlags::empty(), - filterable: false, - }, - extent: wgt::Extent3d { - width: config.width, - height: config.height, - depth_or_array_layers: 1, - }, - samples: 1, - sampled_internal_use: hal::TextureUses::empty(), - selector: TextureSelector { - layers: 0..1, - levels: 0..1, - }, - life_guard: LifeGuard::new(""), - }; - - let ref_count = view.life_guard.add_ref(); - let id = fid.assign(view, &mut token); - - suf.acquired_texture = Some(suf_texture); - - let present = surface.presentation.as_mut().unwrap(); - if present.acquired_texture.is_some() { - return Err(SurfaceError::AlreadyAcquired); - } - present.acquired_texture = Some(Stored { - value: id, - ref_count, - }); - - Some(id.0) - } - None => None, - }; - - Ok(SurfaceOutput { status, view_id }) + Ok(SurfaceOutput { status, texture_id }) } pub fn surface_present( @@ -230,23 +217,22 @@ impl Global { } let result = { - let view_id = present + let texture_id = present .acquired_texture .take() .ok_or(SurfaceError::AlreadyAcquired)?; - let suf = A::get_surface_mut(surface); - let suf_texture = suf.acquired_texture.take().unwrap(); - let result = unsafe { device.queue.present(&mut suf.raw, suf_texture) }; - - drop(surface_guard); - - let (view, _) = hub.texture_views.unregister(view_id.value.0, &mut token); - if let Some(view) = view { - device.schedule_rogue_texture_view_for_destruction(view_id.value, view, &mut token); + let (texture, _) = hub.textures.unregister(texture_id.value.0, &mut token); + if let Some(texture) = texture { + let suf_texture = match texture.inner { + resource::TextureInner::Surface { raw, .. } => raw, + resource::TextureInner::Native { .. } => unreachable!(), + }; + let suf = A::get_surface_mut(surface); + unsafe { device.queue.present(&mut suf.raw, suf_texture) } + } else { + Err(hal::SurfaceError::Outdated) //TODO? } - - result }; log::debug!("Presented. End of Frame"); diff --git a/wgpu-core/src/resource.rs b/wgpu-core/src/resource.rs index 4cc92b445..12afdeb16 100644 --- a/wgpu-core/src/resource.rs +++ b/wgpu-core/src/resource.rs @@ -156,9 +156,33 @@ impl Borrow<()> for Buffer { pub type TextureDescriptor<'a> = wgt::TextureDescriptor>; +#[derive(Debug)] +pub(crate) enum TextureInner { + Native { + raw: Option, + }, + Surface { + raw: A::SurfaceTexture, + parent_id: Valid, + }, +} + +impl TextureInner { + pub fn as_raw(&self) -> Option<&A::Texture> { + match *self { + TextureInner::Native { raw: Some(ref tex) } => Some(tex), + TextureInner::Native { raw: None } => None, + TextureInner::Surface { + ref raw, + parent_id: _, + } => Some(std::borrow::Borrow::borrow(raw)), + } + } +} + #[derive(Debug)] pub struct Texture { - pub(crate) raw: Option, + pub(crate) inner: TextureInner, pub(crate) device_id: Stored, pub(crate) desc: wgt::TextureDescriptor<()>, pub(crate) hal_usage: hal::TextureUses, @@ -237,12 +261,6 @@ pub struct TextureViewDescriptor<'a> { pub range: wgt::ImageSubresourceRange, } -#[derive(Debug)] -pub(crate) enum TextureViewSource { - Native(Stored), - Surface(Valid), -} - #[derive(Debug)] pub(crate) struct HalTextureViewDescriptor { pub format: wgt::TextureFormat, @@ -259,7 +277,7 @@ impl HalTextureViewDescriptor { #[derive(Debug)] pub struct TextureView { pub(crate) raw: A::TextureView, - pub(crate) source: TextureViewSource, + pub(crate) parent_id: Stored, //TODO: store device_id for quick access? pub(crate) desc: HalTextureViewDescriptor, pub(crate) format_features: wgt::TextureFormatFeatures, @@ -310,10 +328,7 @@ pub enum CreateTextureViewError { } #[derive(Clone, Debug, Error)] -pub enum TextureViewDestroyError { - #[error("cannot destroy a surface image")] - SurfaceImage, -} +pub enum TextureViewDestroyError {} impl Resource for TextureView { const TYPE: &'static str = "TextureView"; diff --git a/wgpu-core/src/track/mod.rs b/wgpu-core/src/track/mod.rs index ce5e70a85..818581e0a 100644 --- a/wgpu-core/src/track/mod.rs +++ b/wgpu-core/src/track/mod.rs @@ -145,7 +145,7 @@ impl PendingTransition { tex: &'a resource::Texture, ) -> hal::TextureBarrier<'a, A> { log::trace!("\ttexture -> {:?}", self); - let texture = tex.raw.as_ref().expect("Texture is destroyed"); + let texture = tex.inner.as_raw().expect("Texture is destroyed"); hal::TextureBarrier { texture, range: wgt::ImageSubresourceRange { diff --git a/wgpu/examples/framework.rs b/wgpu/examples/framework.rs index a2c01dc4a..9ed025085 100644 --- a/wgpu/examples/framework.rs +++ b/wgpu/examples/framework.rs @@ -296,8 +296,9 @@ fn start( .expect("Failed to acquire next surface texture!") } }; + let view = frame.output.texture.create_view(&wgpu::TextureViewDescriptor::default()); - example.render(&frame.output.view, &device, &queue, &spawner); + example.render(&view, &device, &queue, &spawner); } _ => {} } diff --git a/wgpu/examples/hello-triangle/main.rs b/wgpu/examples/hello-triangle/main.rs index bfc20da98..8a41b58a9 100644 --- a/wgpu/examples/hello-triangle/main.rs +++ b/wgpu/examples/hello-triangle/main.rs @@ -96,13 +96,14 @@ async fn run(event_loop: EventLoop<()>, window: Window) { .get_current_frame() .expect("Failed to acquire next swap chain texture") .output; + let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default()); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); { let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: None, color_attachments: &[wgpu::RenderPassColorAttachment { - view: &frame.view, + view: &view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::GREEN), diff --git a/wgpu/examples/hello-windows/main.rs b/wgpu/examples/hello-windows/main.rs index ad10c5b5d..f5db94451 100644 --- a/wgpu/examples/hello-windows/main.rs +++ b/wgpu/examples/hello-windows/main.rs @@ -112,13 +112,14 @@ async fn run(event_loop: EventLoop<()>, viewports: Vec<(Window, wgpu::Color)>) { Event::RedrawRequested(window_id) => { if let Some(viewport) = viewports.get_mut(&window_id) { let frame = viewport.get_current_frame(); + let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default()); let mut encoder = device .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); { let _rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: None, color_attachments: &[wgpu::RenderPassColorAttachment { - view: &frame.view, + view: &view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(viewport.desc.background), diff --git a/wgpu/src/backend/direct.rs b/wgpu/src/backend/direct.rs index aa1ca12c3..d203d2b05 100644 --- a/wgpu/src/backend/direct.rs +++ b/wgpu/src/backend/direct.rs @@ -893,11 +893,11 @@ impl crate::Context for Context { } } - fn surface_get_current_texture_view( + fn surface_get_current_texture( &self, surface: &Self::SurfaceId, ) -> ( - Option, + Option, SurfaceStatus, Self::SurfaceOutputDetail, ) { @@ -907,10 +907,13 @@ impl crate::Context for Context { .lock() .expect("Surface was not configured?"); match wgc::gfx_select!( - device_id => global.surface_get_current_texture_view(surface.id, PhantomData) + device_id => global.surface_get_current_texture(surface.id, PhantomData) ) { - Ok(wgc::present::SurfaceOutput { status, view_id }) => ( - view_id, + Ok(wgc::present::SurfaceOutput { status, texture_id }) => ( + texture_id.map(|id| Texture { + id, + error_sink: Arc::new(Mutex::new(ErrorSinkRaw::new())), + }), status, SurfaceOutputDetail { surface_id: surface.id, @@ -920,9 +923,9 @@ impl crate::Context for Context { } } - fn surface_present(&self, view: &Self::TextureViewId, detail: &Self::SurfaceOutputDetail) { + fn surface_present(&self, texture: &Self::TextureId, detail: &Self::SurfaceOutputDetail) { let global = &self.0; - match wgc::gfx_select!(*view => global.surface_present(detail.surface_id)) { + match wgc::gfx_select!(texture.id => global.surface_present(detail.surface_id)) { Ok(_status) => (), Err(err) => self.handle_error_fatal(err, "Surface::present"), } diff --git a/wgpu/src/lib.rs b/wgpu/src/lib.rs index e104416d6..8ca3e65f3 100644 --- a/wgpu/src/lib.rs +++ b/wgpu/src/lib.rs @@ -224,15 +224,15 @@ trait Context: Debug + Send + Sized + Sync { device: &Self::DeviceId, config: &SurfaceConfiguration, ); - fn surface_get_current_texture_view( + fn surface_get_current_texture( &self, surface: &Self::SurfaceId, ) -> ( - Option, + Option, SurfaceStatus, Self::SurfaceOutputDetail, ); - fn surface_present(&self, view: &Self::TextureViewId, detail: &Self::SurfaceOutputDetail); + fn surface_present(&self, texture: &Self::TextureId, detail: &Self::SurfaceOutputDetail); fn device_features(&self, device: &Self::DeviceId) -> Features; fn device_limits(&self, device: &Self::DeviceId) -> Limits; @@ -630,7 +630,6 @@ pub struct Texture { pub struct TextureView { context: Arc, id: ::TextureViewId, - owned: bool, } /// Handle to a sampler. @@ -1331,7 +1330,7 @@ pub struct RenderBundleEncoderDescriptor<'a> { #[derive(Debug)] pub struct SurfaceTexture { /// Accessible view of the frame. - pub view: TextureView, + pub texture: Texture, detail: ::SurfaceOutputDetail, } @@ -2075,7 +2074,6 @@ impl Texture { TextureView { context: Arc::clone(&self.context), id: Context::texture_create_view(&*self.context, &self.id, desc), - owned: true, } } @@ -2105,7 +2103,7 @@ impl Drop for Texture { impl Drop for TextureView { fn drop(&mut self) { - if self.owned && !thread::panicking() { + if !thread::panicking() { self.context.texture_view_drop(&self.id); } } @@ -3056,7 +3054,7 @@ impl Queue { impl Drop for SurfaceTexture { fn drop(&mut self) { if !thread::panicking() { - Context::surface_present(&*self.view.context, &self.view.id, &self.detail); + Context::surface_present(&*self.texture.context, &self.texture.id, &self.detail); } } } @@ -3087,10 +3085,10 @@ impl Surface { /// If a SurfaceFrame referencing this surface is alive when the swapchain is recreated, /// recreating the swapchain will panic. pub fn get_current_frame(&self) -> Result { - let (view_id, status, detail) = - Context::surface_get_current_texture_view(&*self.context, &self.id); - let output = view_id.map(|id| SurfaceTexture { - view: TextureView { + let (texture_id, status, detail) = + Context::surface_get_current_texture(&*self.context, &self.id); + let output = texture_id.map(|id| SurfaceTexture { + texture: Texture { context: Arc::clone(&self.context), id, owned: false,