Skip to content

Commit

Permalink
The big unraveling: core device now has a boxed DynDevice, ripple e…
Browse files Browse the repository at this point in the history
…ffects from there leading to boxing of almost all hal resources
  • Loading branch information
Wumpf committed Aug 3, 2024
1 parent e12445d commit a498175
Show file tree
Hide file tree
Showing 20 changed files with 285 additions and 276 deletions.
32 changes: 15 additions & 17 deletions wgpu-core/src/binding_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,7 @@ impl<A: HalApi> std::fmt::Display for ExclusivePipeline<A> {
/// Bind group layout.
#[derive(Debug)]
pub struct BindGroupLayout<A: HalApi> {
pub(crate) raw: Option<A::BindGroupLayout>,
pub(crate) raw: Option<Box<dyn hal::DynBindGroupLayout>>,
pub(crate) device: Arc<Device<A>>,
pub(crate) entries: bgl::EntryMap,
/// It is very important that we know if the bind group comes from the BGL pool.
Expand All @@ -521,11 +521,10 @@ impl<A: HalApi> Drop for BindGroupLayout<A> {
if matches!(self.origin, bgl::Origin::Pool) {
self.device.bgl_pool.remove(&self.entries);
}
if let Some(mut raw) = self.raw.take() {
if let Some(raw) = self.raw.take() {
resource_log!("Destroy raw {}", self.error_ident());
unsafe {
use hal::Device;
self.device.raw().destroy_bind_group_layout(&mut raw);
self.device.raw().destroy_bind_group_layout(raw);
}
}
}
Expand All @@ -538,8 +537,8 @@ crate::impl_storage_item!(BindGroupLayout);
crate::impl_trackable!(BindGroupLayout);

impl<A: HalApi> BindGroupLayout<A> {
pub(crate) fn raw(&self) -> &A::BindGroupLayout {
self.raw.as_ref().unwrap()
pub(crate) fn raw(&self) -> &dyn hal::DynBindGroupLayout {
self.raw.as_ref().unwrap().as_ref()
}
}

Expand Down Expand Up @@ -653,7 +652,7 @@ pub struct ResolvedPipelineLayoutDescriptor<'a, A: HalApi> {

#[derive(Debug)]
pub struct PipelineLayout<A: HalApi> {
pub(crate) raw: Option<A::PipelineLayout>,
pub(crate) raw: Option<Box<dyn hal::DynPipelineLayout>>,
pub(crate) device: Arc<Device<A>>,
/// The `label` from the descriptor used to create the resource.
pub(crate) label: String,
Expand All @@ -664,19 +663,18 @@ pub struct PipelineLayout<A: HalApi> {

impl<A: HalApi> Drop for PipelineLayout<A> {
fn drop(&mut self) {
if let Some(mut raw) = self.raw.take() {
if let Some(raw) = self.raw.take() {
resource_log!("Destroy raw {}", self.error_ident());
unsafe {
use hal::Device;
self.device.raw().destroy_pipeline_layout(&mut raw);
self.device.raw().destroy_pipeline_layout(raw);
}
}
}
}

impl<A: HalApi> PipelineLayout<A> {
pub(crate) fn raw(&self) -> &A::PipelineLayout {
self.raw.as_ref().unwrap()
pub(crate) fn raw(&self) -> &dyn hal::DynPipelineLayout {
self.raw.as_ref().unwrap().as_ref()
}

pub(crate) fn get_binding_maps(&self) -> ArrayVec<&bgl::EntryMap, { hal::MAX_BIND_GROUPS }> {
Expand Down Expand Up @@ -892,7 +890,7 @@ pub(crate) fn buffer_binding_type_alignment(

#[derive(Debug)]
pub struct BindGroup<A: HalApi> {
pub(crate) raw: Snatchable<A::BindGroup>,
pub(crate) raw: Snatchable<Box<dyn hal::DynBindGroup>>,
pub(crate) device: Arc<Device<A>>,
pub(crate) layout: Arc<BindGroupLayout<A>>,
/// The `label` from the descriptor used to create the resource.
Expand All @@ -909,11 +907,10 @@ pub struct BindGroup<A: HalApi> {

impl<A: HalApi> Drop for BindGroup<A> {
fn drop(&mut self) {
if let Some(mut raw) = self.raw.take() {
if let Some(raw) = self.raw.take() {
resource_log!("Destroy raw {}", self.error_ident());
unsafe {
use hal::Device;
self.device.raw().destroy_bind_group(&mut raw);
self.device.raw().destroy_bind_group(raw);
}
}
}
Expand All @@ -923,7 +920,7 @@ impl<A: HalApi> BindGroup<A> {
pub(crate) fn try_raw<'a>(
&'a self,
guard: &'a SnatchGuard,
) -> Result<&A::BindGroup, DestroyedResourceError> {
) -> Result<&dyn hal::DynBindGroup, DestroyedResourceError> {
// Clippy insist on writing it this way. The idea is to return None
// if any of the raw buffer is not valid anymore.
for buffer in &self.used_buffer_ranges {
Expand All @@ -935,6 +932,7 @@ impl<A: HalApi> BindGroup<A> {

self.raw
.get(guard)
.map(|raw| raw.as_ref())
.ok_or_else(|| DestroyedResourceError(self.error_ident()))
}

Expand Down
22 changes: 10 additions & 12 deletions wgpu-core/src/command/allocator.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use crate::hal_api::HalApi;
use crate::resource_log;
use hal::Device as _;

use crate::lock::{rank, Mutex};

Expand All @@ -14,11 +12,11 @@ use crate::lock::{rank, Mutex};
/// [`wgpu_hal::CommandEncoder`]: hal::CommandEncoder
/// [ce]: hal::CommandEncoder
/// [cb]: hal::Api::CommandBuffer
pub(crate) struct CommandAllocator<A: HalApi> {
free_encoders: Mutex<Vec<A::CommandEncoder>>,
pub(crate) struct CommandAllocator {
free_encoders: Mutex<Vec<Box<dyn hal::DynCommandEncoder>>>,
}

impl<A: HalApi> CommandAllocator<A> {
impl CommandAllocator {
pub(crate) fn new() -> Self {
Self {
free_encoders: Mutex::new(rank::COMMAND_ALLOCATOR_FREE_ENCODERS, Vec::new()),
Expand All @@ -33,9 +31,9 @@ impl<A: HalApi> CommandAllocator<A> {
/// [`wgpu_hal::CommandEncoder`]: hal::CommandEncoder
pub(crate) fn acquire_encoder(
&self,
device: &A::Device,
queue: &A::Queue,
) -> Result<A::CommandEncoder, hal::DeviceError> {
device: &dyn hal::DynDevice,
queue: &dyn hal::DynQueue,
) -> Result<Box<dyn hal::DynCommandEncoder>, hal::DeviceError> {
let mut free_encoders = self.free_encoders.lock();
match free_encoders.pop() {
Some(encoder) => Ok(encoder),
Expand All @@ -47,20 +45,20 @@ impl<A: HalApi> CommandAllocator<A> {
}

/// Add `encoder` back to the free pool.
pub(crate) fn release_encoder(&self, encoder: A::CommandEncoder) {
pub(crate) fn release_encoder(&self, encoder: Box<dyn hal::DynCommandEncoder>) {
let mut free_encoders = self.free_encoders.lock();
free_encoders.push(encoder);
}

/// Free the pool of command encoders.
///
/// This is only called when the `Device` is dropped.
pub(crate) fn dispose(&self, device: &A::Device) {
pub(crate) fn dispose(&self, device: &dyn hal::DynDevice) {
let mut free_encoders = self.free_encoders.lock();
resource_log!("CommandAllocator::dispose encoders {}", free_encoders.len());
for mut cmd_encoder in free_encoders.drain(..) {
for cmd_encoder in free_encoders.drain(..) {
unsafe {
device.destroy_command_encoder(&mut cmd_encoder);
device.destroy_command_encoder(cmd_encoder);
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions wgpu-core/src/command/clear.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ impl Global {
encoder,
&mut tracker.textures,
&device.alignments,
device.zero_buffer.as_ref().unwrap(),
device.zero_buffer.as_ref().unwrap().as_ref(),
&snatch_guard,
)
}
Expand All @@ -274,7 +274,7 @@ pub(crate) fn clear_texture<A: HalApi, T: TextureTrackerSetSingle<A>>(
encoder: &mut dyn hal::DynCommandEncoder,
texture_tracker: &mut T,
alignments: &hal::Alignments,
zero_buffer: &A::Buffer,
zero_buffer: &dyn hal::DynBuffer,
snatch_guard: &SnatchGuard<'_>,
) -> Result<(), ClearError> {
let dst_raw = dst_texture.try_raw(snatch_guard)?;
Expand Down Expand Up @@ -462,7 +462,7 @@ fn clear_texture_via_render_passes<A: HalApi>(
let (color_attachments, depth_stencil_attachment) = if is_color {
color_attachments_tmp = [Some(hal::ColorAttachment {
target: hal::Attachment {
view: Texture::get_clear_view(
view: Texture::<A>::get_clear_view(
clear_mode,
&dst_texture.desc,
mip_level,
Expand All @@ -480,7 +480,7 @@ fn clear_texture_via_render_passes<A: HalApi>(
&[][..],
Some(hal::DepthStencilAttachment {
target: hal::Attachment {
view: Texture::get_clear_view(
view: Texture::<A>::get_clear_view(
clear_mode,
&dst_texture.desc,
mip_level,
Expand Down
6 changes: 2 additions & 4 deletions wgpu-core/src/command/compute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -506,14 +506,12 @@ impl Global {
// But no point in erroring over that nuance here!
if let Some(range) = range {
unsafe {
state
.raw_encoder
.reset_queries(query_set.raw.as_ref().unwrap(), range);
state.raw_encoder.reset_queries(query_set.raw(), range);
}
}

Some(hal::PassTimestampWrites {
query_set: query_set.raw.as_ref().unwrap(),
query_set: query_set.raw(),
beginning_of_pass_write_index: tw.beginning_of_pass_write_index,
end_of_pass_write_index: tw.end_of_pass_write_index,
})
Expand Down
11 changes: 5 additions & 6 deletions wgpu-core/src/command/memory_init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ pub(crate) fn fixup_discarded_surfaces<
encoder,
texture_tracker,
&device.alignments,
device.zero_buffer.as_ref().unwrap(),
device.zero_buffer.as_ref().unwrap().as_ref(),
snatch_guard,
)
.unwrap();
Expand Down Expand Up @@ -226,10 +226,9 @@ impl<A: HalApi> BakedCommands<A> {
.set_single(&buffer, hal::BufferUses::COPY_DST);

let raw_buf = buffer.try_raw_dyn(snatch_guard)?;
let encoder: &mut dyn hal::DynCommandEncoder = &mut self.encoder; // TODO(#5124): temporary

unsafe {
encoder.transition_buffers(
self.encoder.transition_buffers(
transition
.map(|pending| pending.into_hal(&buffer, snatch_guard))
.as_slice(),
Expand All @@ -253,7 +252,7 @@ impl<A: HalApi> BakedCommands<A> {
);

unsafe {
encoder.clear_buffer(raw_buf, range.clone());
self.encoder.clear_buffer(raw_buf, range.clone());
}
}
}
Expand Down Expand Up @@ -306,10 +305,10 @@ impl<A: HalApi> BakedCommands<A> {
let clear_result = clear_texture(
&texture_use.texture,
range,
&mut self.encoder,
self.encoder.as_mut(),
&mut device_tracker.textures,
&device.alignments,
device.zero_buffer.as_ref().unwrap(),
device.zero_buffer.as_ref().unwrap().as_ref(),
snatch_guard,
);

Expand Down
26 changes: 11 additions & 15 deletions wgpu-core/src/command/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ use crate::track::{DeviceTracker, Tracker, UsageScope};
use crate::LabelHelpers;
use crate::{api_log, global::Global, hal_api::HalApi, id, resource_log, Label};

use hal::CommandEncoder as _;
use thiserror::Error;

#[cfg(feature = "trace")]
Expand Down Expand Up @@ -115,15 +114,15 @@ pub(crate) enum CommandEncoderStatus {
/// [rce]: hal::Api::CommandEncoder
/// [rcb]: hal::Api::CommandBuffer
/// [`CommandEncoderId`]: crate::id::CommandEncoderId
pub(crate) struct CommandEncoder<A: HalApi> {
pub(crate) struct CommandEncoder {
/// The underlying `wgpu_hal` [`CommandEncoder`].
///
/// Successfully executed command buffers' encoders are saved in a
/// [`CommandAllocator`] for recycling.
///
/// [`CommandEncoder`]: hal::Api::CommandEncoder
/// [`CommandAllocator`]: crate::command::CommandAllocator
raw: A::CommandEncoder,
raw: Box<dyn hal::DynCommandEncoder>,

/// All the raw command buffers for our owning [`CommandBuffer`], in
/// submission order.
Expand All @@ -136,7 +135,7 @@ pub(crate) struct CommandEncoder<A: HalApi> {
///
/// [CE::ra]: hal::CommandEncoder::reset_all
/// [`wgpu_hal::CommandEncoder`]: hal::CommandEncoder
list: Vec<A::CommandBuffer>,
list: Vec<Box<dyn hal::DynCommandBuffer>>,

/// True if `raw` is in the "recording" state.
///
Expand All @@ -150,7 +149,7 @@ pub(crate) struct CommandEncoder<A: HalApi> {
}

//TODO: handle errors better
impl<A: HalApi> CommandEncoder<A> {
impl CommandEncoder {
/// Finish the current command buffer, if any, and place it
/// at the second-to-last position in our list.
///
Expand Down Expand Up @@ -226,7 +225,7 @@ impl<A: HalApi> CommandEncoder<A> {
unsafe { self.raw.begin_encoding(hal_label)? };
}

Ok(&mut self.raw)
Ok(self.raw.as_mut())
}

/// Begin recording a new command buffer for a render pass, with
Expand All @@ -242,8 +241,8 @@ impl<A: HalApi> CommandEncoder<A> {
}

pub(crate) struct BakedCommands<A: HalApi> {
pub(crate) encoder: A::CommandEncoder,
pub(crate) list: Vec<A::CommandBuffer>,
pub(crate) encoder: Box<dyn hal::DynCommandEncoder>,
pub(crate) list: Vec<Box<dyn hal::DynCommandBuffer>>,
pub(crate) trackers: Tracker<A>,
buffer_memory_init_actions: Vec<BufferInitTrackerAction<A>>,
texture_memory_actions: CommandBufferTextureMemoryActions<A>,
Expand All @@ -255,7 +254,7 @@ pub struct CommandBufferMutable<A: HalApi> {
/// they belong to.
///
/// [`wgpu_hal::Api::CommandBuffer`]: hal::Api::CommandBuffer
pub(crate) encoder: CommandEncoder<A>,
pub(crate) encoder: CommandEncoder,

/// The current state of this command buffer's encoder.
status: CommandEncoderStatus,
Expand Down Expand Up @@ -329,20 +328,17 @@ impl<A: HalApi> Drop for CommandBuffer<A> {
}
let mut baked = self.extract_baked_commands();
unsafe {
baked.encoder.reset_all(baked.list.iter_mut());
baked.encoder.reset_all(baked.list);
}
unsafe {
use hal::Device;
self.device
.raw()
.destroy_command_encoder(&mut baked.encoder);
self.device.raw().destroy_command_encoder(baked.encoder);
}
}
}

impl<A: HalApi> CommandBuffer<A> {
pub(crate) fn new(
encoder: A::CommandEncoder,
encoder: Box<dyn hal::DynCommandEncoder>,
device: &Arc<Device<A>>,
#[cfg(feature = "trace")] enable_tracing: bool,
label: &Label,
Expand Down
2 changes: 1 addition & 1 deletion wgpu-core/src/command/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ pub(super) fn end_occlusion_query<A: HalApi>(
active_query: &mut Option<(Arc<QuerySet<A>>, u32)>,
) -> Result<(), QueryUseError> {
if let Some((query_set, query_index)) = active_query.take() {
unsafe { raw_encoder.end_query(query_set.raw.as_ref().unwrap(), query_index) };
unsafe { raw_encoder.end_query(query_set.raw(), query_index) };
Ok(())
} else {
Err(QueryUseError::AlreadyStopped)
Expand Down
Loading

0 comments on commit a498175

Please sign in to comment.