From 4a1ae0d7ecc54d0d0f617971113e3757b33e08fc Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 11 Aug 2021 00:06:51 -0400 Subject: [PATCH] Issue surface texture transitions --- wgpu-core/src/command/mod.rs | 3 - wgpu-core/src/command/render.rs | 20 +------ wgpu-core/src/device/queue.rs | 85 ++++++++++++++++++++++------ wgpu-core/src/hub.rs | 7 ++- wgpu-core/src/present.rs | 13 +++-- wgpu-core/src/track/mod.rs | 9 ++- wgpu-core/src/track/range.rs | 2 + wgpu/examples/framework.rs | 5 +- wgpu/examples/hello-triangle/main.rs | 4 +- wgpu/examples/hello-windows/main.rs | 4 +- wgpu/src/backend/web.rs | 10 ++-- 11 files changed, 107 insertions(+), 55 deletions(-) diff --git a/wgpu-core/src/command/mod.rs b/wgpu-core/src/command/mod.rs index 7236b8b3a..083db3ff6 100644 --- a/wgpu-core/src/command/mod.rs +++ b/wgpu-core/src/command/mod.rs @@ -25,7 +25,6 @@ use crate::{ }; use hal::CommandEncoder as _; -use smallvec::SmallVec; use thiserror::Error; const PUSH_CONSTANT_CLEAR_ARRAY: &[u32] = &[0_u32; 64]; @@ -141,7 +140,6 @@ pub struct CommandBuffer { status: CommandEncoderStatus, pub(crate) device_id: Stored, pub(crate) trackers: TrackerSet, - pub(crate) used_surfaces: SmallVec<[id::Valid; 1]>, buffer_memory_init_actions: Vec>, limits: wgt::Limits, support_fill_buffer_texture: bool, @@ -169,7 +167,6 @@ impl CommandBuffer { status: CommandEncoderStatus::Recording, device_id, trackers: TrackerSet::new(A::VARIANT), - used_surfaces: Default::default(), buffer_memory_init_actions: Default::default(), limits, support_fill_buffer_texture: features.contains(wgt::Features::CLEAR_COMMANDS), diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index b40b2bb15..526c842b6 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -13,7 +13,6 @@ use crate::{ error::{ErrorFormatter, PrettyError}, hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token}, id, - instance::Surface, memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction}, pipeline::PipelineFlags, resource::{Texture, TextureView}, @@ -530,7 +529,6 @@ struct RenderPassInfo<'a, A: hal::Api> { context: RenderPassContext, trackers: StatefulTrackerSubset, render_attachments: AttachmentDataVec>, - used_surface: Option>, is_ds_read_only: bool, extent: wgt::Extent3d, _phantom: PhantomData, @@ -543,7 +541,6 @@ 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, ) -> Result { profiling::scope!("start", "RenderPassInfo"); @@ -557,8 +554,6 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> { let mut attachment_type_name = ""; let mut extent = None; let mut sample_count = 0; - //TODO: remove this? - let used_surface = None::<(id::Valid, hal::TextureUses)>; let mut add_view = |view: &TextureView, type_name| { if let Some(ex) = extent { @@ -718,7 +713,6 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> { context, trackers: StatefulTrackerSubset::new(A::VARIANT), render_attachments, - used_surface: used_surface.map(|(sc_id, _)| sc_id), is_ds_read_only, extent, _phantom: PhantomData, @@ -729,9 +723,7 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> { mut self, raw: &mut A::CommandEncoder, texture_guard: &Storage, id::TextureId>, - _surface_guard: &Storage, - ) -> Result<(StatefulTrackerSubset, Option>), RenderPassErrorInner> - { + ) -> Result { profiling::scope!("finish", "RenderPassInfo"); unsafe { raw.end_render_pass(); @@ -753,7 +745,7 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> { .map_err(UsageConflict::from)?; } - Ok((self.trackers, self.used_surface)) + Ok(self.trackers) } } @@ -786,8 +778,6 @@ impl Global { let hub = A::hub(self); let mut token = Token::root(); - - let (surface_guard, mut token) = self.surfaces.read(&mut token); let (device_guard, mut token) = hub.devices.read(&mut token); let (pass_raw, trackers, query_reset_state) = { @@ -834,7 +824,6 @@ impl Global { depth_stencil_attachment, cmd_buf, &*view_guard, - &*surface_guard, ) .map_pass_err(scope)?; @@ -1701,9 +1690,7 @@ impl Global { } log::trace!("Merging {:?} with the render pass", encoder_id); - let (trackers, used_surface) = info - .finish(raw, &*texture_guard, &*surface_guard) - .map_pass_err(scope)?; + let trackers = info.finish(raw, &*texture_guard).map_pass_err(scope)?; let raw_cmd_buf = unsafe { raw.end_encoding() @@ -1711,7 +1698,6 @@ impl Global { .map_pass_err(scope)? }; cmd_buf.status = CommandEncoderStatus::Recording; - cmd_buf.used_surfaces.extend(used_surface); (raw_cmd_buf, trackers, query_reset_state) }; diff --git a/wgpu-core/src/device/queue.rs b/wgpu-core/src/device/queue.rs index ac5800e2f..daa0b0435 100644 --- a/wgpu-core/src/device/queue.rs +++ b/wgpu-core/src/device/queue.rs @@ -9,8 +9,8 @@ use crate::{ device::{DeviceError, WaitIdleError}, hub::{Global, GlobalIdentityHandlerFactory, HalApi, Token}, id, - resource::{BufferAccessError, BufferMapState}, - FastHashSet, + resource::{BufferAccessError, BufferMapState, TextureInner}, + track, FastHashSet, }; use hal::{CommandEncoder as _, Device as _, Queue as _}; @@ -511,7 +511,6 @@ impl Global { let mut token = Token::root(); let callbacks = { - let (mut surface_guard, mut token) = self.surfaces.write(&mut token); let (mut device_guard, mut token) = hub.devices.write(&mut token); let device = device_guard .get_mut(queue_id) @@ -520,6 +519,7 @@ impl Global { device.active_submission_index += 1; let submit_index = device.active_submission_index; let mut active_executions = Vec::new(); + let mut used_surface_textures = track::ResourceTracker::new(A::VARIANT); { let (mut command_buffer_guard, mut token) = hub.command_buffers.write(&mut token); @@ -569,18 +569,6 @@ impl Global { // optimize the tracked states cmdbuf.trackers.optimize(); - //TODO: do we need this code? - for surface_id in cmdbuf.used_surfaces.drain(..) { - match surface_guard[surface_id].presentation { - Some(ref mut present) => { - if present.acquired_texture.is_none() { - return Err(QueueSubmitError::SurfaceOutputDropped); - } - } - None => return Err(QueueSubmitError::SurfaceUnconfigured), - } - } - // update submission IDs for id in cmdbuf.trackers.buffers.used() { let buffer = &mut buffer_guard[id]; @@ -606,8 +594,44 @@ impl Global { } for id in cmdbuf.trackers.textures.used() { let texture = &texture_guard[id]; - if texture.inner.as_raw().is_none() { - return Err(QueueSubmitError::DestroyedTexture(id.0)); + match texture.inner { + TextureInner::Native { raw: None } => { + return Err(QueueSubmitError::DestroyedTexture(id.0)); + } + TextureInner::Native { raw: Some(_) } => {} + TextureInner::Surface { .. } => { + use track::ResourceState as _; + let ref_count = cmdbuf.trackers.textures.get_ref_count(id); + //TODO: better error handling here? + { + // first, register it in the device tracker with uninitialized, + // if it wasn't used before. + let mut ts = track::TextureState::default(); + let _ = ts.change( + id, + texture.full_range.clone(), + hal::TextureUses::UNINITIALIZED, + None, + ); + let _ = trackers.textures.init( + id, + ref_count.clone(), + ts.clone(), + ); + } + { + // then, register it in the temporary tracker. + let mut ts = track::TextureState::default(); + let _ = ts.change( + id, + texture.full_range.clone(), + hal::TextureUses::empty(), + None, + ); + let _ = + used_surface_textures.init(id, ref_count.clone(), ts); + } + } } if !texture.life_guard.use_at(submit_index) { device.temp_suspected.textures.push(id); @@ -690,6 +714,33 @@ impl Global { let transit = unsafe { baked.encoder.end_encoding().unwrap() }; baked.list.insert(0, transit); + + // Transition surface textures into `Present` state. + // Note: we could technically do it after all of the command buffers, + // but here we have a command encoder by hand, so it's easier to use it. + if !used_surface_textures.is_empty() { + unsafe { + baked + .encoder + .begin_encoding(Some("_Present")) + .map_err(DeviceError::from)? + }; + let texture_barriers = trackers + .textures + .merge_replace(&used_surface_textures) + .map(|pending| { + let tex = &texture_guard[pending.id]; + pending.into_hal(tex) + }); + let present = unsafe { + baked.encoder.transition_textures(texture_barriers); + baked.encoder.end_encoding().unwrap() + }; + baked.list.push(present); + used_surface_textures.clear(); + } + + // done active_executions.push(EncoderInFlight { raw: baked.encoder, cmd_buffers: baked.list, diff --git a/wgpu-core/src/hub.rs b/wgpu-core/src/hub.rs index 9ab42ce85..06df58917 100644 --- a/wgpu-core/src/hub.rs +++ b/wgpu-core/src/hub.rs @@ -722,13 +722,14 @@ impl Hub { } } - for element in surface_guard.map.drain(..) { - if let Element::Occupied(mut surface, _epoch) = element { + for element in surface_guard.map.iter_mut() { + if let Element::Occupied(ref mut surface, _epoch) = *element { if let Some(present) = surface.presentation.take() { let device = &devices[present.device_id.value]; - let suf = A::get_surface_mut(&mut surface); + let suf = A::get_surface_mut(surface); unsafe { suf.raw.unconfigure(&device.raw); + //TODO: we could destroy the surface here } } } diff --git a/wgpu-core/src/present.rs b/wgpu-core/src/present.rs index 508cba055..6f7d970ee 100644 --- a/wgpu-core/src/present.rs +++ b/wgpu-core/src/present.rs @@ -2,10 +2,11 @@ ## Lifecycle - When a swapchain view is used in `begin_render_pass()`, we assume the start and end image - layouts purely based on whether or not this view was used in this command buffer before. - It always starts with `Uninitialized` and ends with `Present`, so that no barriers are - needed when we need to actually present it. + Whenever a submission detects the use of any surface texture, it adds it to the device + tracker for the duration of the submission (temporarily, while recording). + It's added with `UNINITIALIZED` state and transitioned into `empty()` state. + When this texture is presented, we remove it from the device tracker as well as + extract it from the hub. !*/ #[cfg(feature = "trace")] @@ -222,6 +223,10 @@ impl Global { .take() .ok_or(SurfaceError::AlreadyAcquired)?; + // The texture ID got added to the device tracker by `submit()`, + // and now we are moving it away. + device.trackers.lock().textures.remove(texture_id.value); + let (texture, _) = hub.textures.unregister(texture_id.value.0, &mut token); if let Some(texture) = texture { let suf_texture = match texture.inner { diff --git a/wgpu-core/src/track/mod.rs b/wgpu-core/src/track/mod.rs index 818581e0a..0d0453a66 100644 --- a/wgpu-core/src/track/mod.rs +++ b/wgpu-core/src/track/mod.rs @@ -218,7 +218,7 @@ impl ResourceTracker { } /// Remove an id from the tracked map. - pub(crate) fn _remove(&mut self, id: Valid) -> bool { + pub(crate) fn remove(&mut self, id: Valid) -> bool { let (index, epoch, backend) = id.0.unzip(); debug_assert_eq!(backend, self.backend); match self.map.remove(&index) { @@ -263,13 +263,18 @@ impl ResourceTracker { .map(move |(&index, resource)| Valid(S::Id::zip(index, resource.epoch, backend))) } + pub fn get_ref_count(&self, id: Valid) -> &RefCount { + let (index, _, _) = id.0.unzip(); + &self.map[&index].ref_count + } + /// Return true if there is nothing here. pub fn is_empty(&self) -> bool { self.map.is_empty() } /// Clear the tracked contents. - fn clear(&mut self) { + pub fn clear(&mut self) { self.map.clear(); } diff --git a/wgpu-core/src/track/range.rs b/wgpu-core/src/track/range.rs index f3755c57a..c2238439d 100644 --- a/wgpu-core/src/track/range.rs +++ b/wgpu-core/src/track/range.rs @@ -1,3 +1,5 @@ +//Note: this could be the only place where we need `SmallVec`. +//TODO: consider getting rid of it. use smallvec::SmallVec; use std::{cmp::Ordering, fmt::Debug, iter, ops::Range, slice::Iter}; diff --git a/wgpu/examples/framework.rs b/wgpu/examples/framework.rs index 9ed025085..8cccddff1 100644 --- a/wgpu/examples/framework.rs +++ b/wgpu/examples/framework.rs @@ -296,7 +296,10 @@ fn start( .expect("Failed to acquire next surface texture!") } }; - let view = frame.output.texture.create_view(&wgpu::TextureViewDescriptor::default()); + let view = frame + .output + .texture + .create_view(&wgpu::TextureViewDescriptor::default()); example.render(&view, &device, &queue, &spawner); } diff --git a/wgpu/examples/hello-triangle/main.rs b/wgpu/examples/hello-triangle/main.rs index 8a41b58a9..9bbfb8984 100644 --- a/wgpu/examples/hello-triangle/main.rs +++ b/wgpu/examples/hello-triangle/main.rs @@ -96,7 +96,9 @@ 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 view = frame + .texture + .create_view(&wgpu::TextureViewDescriptor::default()); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); { diff --git a/wgpu/examples/hello-windows/main.rs b/wgpu/examples/hello-windows/main.rs index f5db94451..531b66d39 100644 --- a/wgpu/examples/hello-windows/main.rs +++ b/wgpu/examples/hello-windows/main.rs @@ -112,7 +112,9 @@ 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 view = frame + .texture + .create_view(&wgpu::TextureViewDescriptor::default()); let mut encoder = device .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); { diff --git a/wgpu/src/backend/web.rs b/wgpu/src/backend/web.rs index 42be6c875..43ffae6d7 100644 --- a/wgpu/src/backend/web.rs +++ b/wgpu/src/backend/web.rs @@ -1123,24 +1123,22 @@ impl crate::Context for Context { surface.0.configure_swap_chain(&mapped); } - fn surface_get_current_texture_view( + fn surface_get_current_texture( &self, _surface: &Self::SurfaceId, ) -> ( - Option, + Option, wgt::SurfaceStatus, Self::SurfaceOutputDetail, ) { - // TODO: Should we pass a descriptor here? - // Or is the default view always correct? ( - None, //TODO: surface.0.get_current_texture().create_view() + None, //TODO: surface.0.get_current_texture(), wgt::SurfaceStatus::Good, (), ) } - fn surface_present(&self, _view: &Self::TextureViewId, _detail: &Self::SurfaceOutputDetail) { + fn surface_present(&self, _texture: &Self::TextureId, _detail: &Self::SurfaceOutputDetail) { // Swapchain is presented automatically }