From af38d79d79607802df4b70754982730fae85d39b Mon Sep 17 00:00:00 2001 From: Atul Bhosale Date: Tue, 23 Apr 2019 22:01:47 +0530 Subject: [PATCH] Format code using 'cargo fmt' --- .rustfmt.toml | 1 + examples/hello_triangle_rust/main.rs | 8 +- gfx-examples/src/framework.rs | 8 +- wgpu-native/src/binding_model.rs | 6 +- wgpu-native/src/command/allocator.rs | 28 ++--- wgpu-native/src/command/bind.rs | 48 +++---- wgpu-native/src/command/compute.rs | 20 +-- wgpu-native/src/command/mod.rs | 31 +++-- wgpu-native/src/command/render.rs | 28 +++-- wgpu-native/src/command/transfer.rs | 9 +- wgpu-native/src/conv.rs | 6 +- wgpu-native/src/device.rs | 182 +++++++++++++++++---------- wgpu-native/src/hub.rs | 27 ++-- wgpu-native/src/instance.rs | 6 +- wgpu-native/src/pipeline.rs | 15 +-- wgpu-native/src/resource.rs | 9 +- wgpu-native/src/swap_chain.rs | 11 +- wgpu-native/src/track.rs | 6 +- wgpu-rs/src/lib.rs | 60 +++++++-- 19 files changed, 311 insertions(+), 198 deletions(-) create mode 100644 .rustfmt.toml diff --git a/.rustfmt.toml b/.rustfmt.toml new file mode 100644 index 0000000000..45a9457909 --- /dev/null +++ b/.rustfmt.toml @@ -0,0 +1 @@ +imports_layout = "HorizontalVertical" diff --git a/examples/hello_triangle_rust/main.rs b/examples/hello_triangle_rust/main.rs index 0c00d429b5..2275bde1e7 100644 --- a/examples/hello_triangle_rust/main.rs +++ b/examples/hello_triangle_rust/main.rs @@ -60,7 +60,13 @@ fn main() { }); use wgpu::winit::{ - ElementState, Event, EventsLoop, KeyboardInput, VirtualKeyCode, Window, WindowEvent, + ElementState, + Event, + EventsLoop, + KeyboardInput, + VirtualKeyCode, + Window, + WindowEvent, }; let mut events_loop = EventsLoop::new(); diff --git a/gfx-examples/src/framework.rs b/gfx-examples/src/framework.rs index feed527616..abb1d5dba0 100644 --- a/gfx-examples/src/framework.rs +++ b/gfx-examples/src/framework.rs @@ -48,7 +48,13 @@ pub trait Example { pub fn run(title: &str) { use wgpu::winit::{ - ElementState, Event, EventsLoop, KeyboardInput, VirtualKeyCode, Window, WindowEvent, + ElementState, + Event, + EventsLoop, + KeyboardInput, + VirtualKeyCode, + Window, + WindowEvent, }; info!("Initializing the device..."); diff --git a/wgpu-native/src/binding_model.rs b/wgpu-native/src/binding_model.rs index 977cc3f9f9..317755ebd4 100644 --- a/wgpu-native/src/binding_model.rs +++ b/wgpu-native/src/binding_model.rs @@ -1,12 +1,8 @@ -use crate::{ - track::TrackerSet, - BindGroupLayoutId, BufferId, LifeGuard, SamplerId, TextureViewId, -}; +use crate::{track::TrackerSet, BindGroupLayoutId, BufferId, LifeGuard, SamplerId, TextureViewId}; use arrayvec::ArrayVec; use bitflags::bitflags; - pub const MAX_BIND_GROUPS: usize = 4; bitflags! { diff --git a/wgpu-native/src/command/allocator.rs b/wgpu-native/src/command/allocator.rs index d83b295c73..e21ebc10d9 100644 --- a/wgpu-native/src/command/allocator.rs +++ b/wgpu-native/src/command/allocator.rs @@ -1,23 +1,11 @@ use super::CommandBuffer; -use crate::{ - track::TrackerSet, - DeviceId, LifeGuard, Stored, SubmissionIndex, -}; +use crate::{track::TrackerSet, DeviceId, LifeGuard, Stored, SubmissionIndex}; -use hal::{ - command::RawCommandBuffer, - pool::RawCommandPool, - Device, -}; +use hal::{command::RawCommandBuffer, pool::RawCommandPool, Device}; use log::trace; use parking_lot::Mutex; -use std::{ - collections::HashMap, - sync::atomic::Ordering, - thread, -}; - +use std::{collections::HashMap, sync::atomic::Ordering, thread}; struct CommandPool { raw: B::CommandPool, @@ -112,7 +100,9 @@ impl CommandAllocator { } pub fn after_submit(&self, cmd_buf: CommandBuffer, submit_index: SubmissionIndex) { - cmd_buf.life_guard.submission_index + cmd_buf + .life_guard + .submission_index .store(submit_index, Ordering::Release); self.inner.lock().pending.push(cmd_buf); } @@ -126,7 +116,11 @@ impl CommandAllocator { .load(Ordering::Acquire); if index <= last_done { let cmd_buf = inner.pending.swap_remove(i); - trace!("recycling comb submitted in {} when {} is done", index, last_done); + trace!( + "recycling comb submitted in {} when {} is done", + index, + last_done + ); inner.recycle(cmd_buf); } } diff --git a/wgpu-native/src/command/bind.rs b/wgpu-native/src/command/bind.rs index ed491d4d95..88e43cfd06 100644 --- a/wgpu-native/src/command/bind.rs +++ b/wgpu-native/src/command/bind.rs @@ -4,11 +4,9 @@ use log::trace; use std::convert::identity; - pub const MAX_BIND_GROUPS: usize = 4; type BindGroupMask = u8; - pub struct BindGroupPair { layout_id: BindGroupLayoutId, group_id: Stored, @@ -28,7 +26,6 @@ pub enum Provision { }, } - struct TakeSome { iter: I, } @@ -51,14 +48,17 @@ pub struct BindGroupEntry { impl BindGroupEntry { fn provide(&mut self, bind_group_id: BindGroupId, bind_group: &BindGroupHandle) -> Provision { let was_compatible = match self.provided { - Some(BindGroupPair { layout_id, ref group_id }) => { + Some(BindGroupPair { + layout_id, + ref group_id, + }) => { if group_id.value == bind_group_id { assert_eq!(layout_id, bind_group.layout_id); return Provision::Unchanged; } self.expected_layout_id == Some(layout_id) } - None => true + None => true, }; self.provided = Some(BindGroupPair { @@ -75,10 +75,7 @@ impl BindGroupEntry { } } - pub fn expect_layout( - &mut self, - bind_group_layout_id: BindGroupLayoutId, - ) -> LayoutChange { + pub fn expect_layout(&mut self, bind_group_layout_id: BindGroupLayoutId) -> LayoutChange { let some = Some(bind_group_layout_id); if self.expected_layout_id != some { self.expected_layout_id = some; @@ -103,14 +100,15 @@ impl BindGroupEntry { } fn actual_value(&self) -> Option { - self.expected_layout_id - .and_then(|layout_id| self.provided.as_ref().and_then(|pair| { + self.expected_layout_id.and_then(|layout_id| { + self.provided.as_ref().and_then(|pair| { if pair.layout_id == layout_id { Some(pair.group_id.value) } else { None } - })) + }) + }) } } @@ -122,7 +120,7 @@ pub struct Binder { impl Binder { pub(crate) fn reset_expectations(&mut self, length: usize) { - for entry in self.entries[length ..].iter_mut() { + for entry in self.entries[length..].iter_mut() { entry.expected_layout_id = None; } } @@ -140,15 +138,16 @@ impl Binder { ) -> Option<(PipelineLayoutId, impl 'a + Iterator)> { trace!("\tBinding [{}] = group {:?}", index, bind_group_id); match self.entries[index].provide(bind_group_id, bind_group) { - Provision::Unchanged => { - None - } - Provision::Changed { now_compatible: false, .. } => { + Provision::Unchanged => None, + Provision::Changed { + now_compatible: false, + .. + } => { trace!("\t\tnot compatible"); None } Provision::Changed { was_compatible, .. } => { - if self.entries[.. index].iter().all(|entry| entry.is_valid()) { + if self.entries[..index].iter().all(|entry| entry.is_valid()) { self.pipeline_layout_id.map(move |pipeline_layout_id| { let end = if was_compatible { trace!("\t\tgenerating follow-up sequence"); @@ -156,11 +155,14 @@ impl Binder { } else { index + 1 }; - (pipeline_layout_id, TakeSome { - iter: self.entries[index + 1 .. end] - .iter() - .map(|entry| entry.actual_value()), - }) + ( + pipeline_layout_id, + TakeSome { + iter: self.entries[index + 1..end] + .iter() + .map(|entry| entry.actual_value()), + }, + ) }) } else { trace!("\t\tbehind an incompatible"); diff --git a/wgpu-native/src/command/compute.rs b/wgpu-native/src/command/compute.rs index 0a3f617b59..ea11e9c69d 100644 --- a/wgpu-native/src/command/compute.rs +++ b/wgpu-native/src/command/compute.rs @@ -2,17 +2,18 @@ use crate::{ command::bind::{Binder, LayoutChange}, hub::HUB, track::{Stitch, TrackerSet}, - BindGroupId, CommandBuffer, CommandBufferId, ComputePassId, ComputePipelineId, Stored, + BindGroupId, + CommandBuffer, + CommandBufferId, + ComputePassId, + ComputePipelineId, + Stored, }; -use hal::{ - self, - command::RawCommandBuffer, -}; +use hal::{self, command::RawCommandBuffer}; use std::iter; - pub struct ComputePass { raw: B::CommandBuffer, cmb_id: Stored, @@ -78,8 +79,8 @@ pub extern "C" fn wgpu_compute_pass_set_bind_group( .provide_entry(index as usize, bind_group_id, bind_group) { let pipeline_layout_guard = HUB.pipeline_layouts.read(); - let bind_groups = iter::once(&bind_group.raw) - .chain(follow_up.map(|bg_id| &bind_group_guard[bg_id].raw)); + let bind_groups = + iter::once(&bind_group.raw).chain(follow_up.map(|bg_id| &bind_group_guard[bg_id].raw)); unsafe { pass.raw.bind_compute_descriptor_sets( &pipeline_layout_guard[pipeline_layout_id].raw, @@ -114,7 +115,8 @@ pub extern "C" fn wgpu_compute_pass_set_pipeline( let bind_group_guard = HUB.bind_groups.read(); pass.binder.pipeline_layout_id = Some(pipeline.layout_id.clone()); - pass.binder.reset_expectations(pipeline_layout.bind_group_layout_ids.len()); + pass.binder + .reset_expectations(pipeline_layout.bind_group_layout_ids.len()); for (index, (entry, &bgl_id)) in pass .binder diff --git a/wgpu-native/src/command/mod.rs b/wgpu-native/src/command/mod.rs index 22db3c35c1..cb24c8feb0 100644 --- a/wgpu-native/src/command/mod.rs +++ b/wgpu-native/src/command/mod.rs @@ -12,32 +12,37 @@ pub use self::transfer::*; use crate::{ conv, device::{ - all_buffer_stages, all_image_stages, FramebufferKey, RenderPassContext, RenderPassKey, + all_buffer_stages, + all_image_stages, + FramebufferKey, + RenderPassContext, + RenderPassKey, }, hub::{Storage, HUB}, pipeline::IndexFormat, resource::TexturePlacement, swap_chain::{SwapChainLink, SwapImageEpoch}, track::{DummyUsage, Stitch, TrackerSet}, - BufferHandle, Color, CommandBufferHandle, CommandBufferId, CommandEncoderId, DeviceId, - LifeGuard, Stored, TextureHandle, TextureUsageFlags, TextureViewId, + BufferHandle, + Color, + CommandBufferHandle, + CommandBufferId, + CommandEncoderId, + DeviceId, + LifeGuard, + Stored, + TextureHandle, + TextureUsageFlags, + TextureViewId, }; #[cfg(feature = "local")] use crate::{ComputePassId, RenderPassId}; use back::Backend; -use hal::{ - Device as _, - command::RawCommandBuffer, -}; +use hal::{command::RawCommandBuffer, Device as _}; use log::trace; -use std::{ - iter, slice, - collections::hash_map::Entry, - thread::ThreadId, -}; - +use std::{collections::hash_map::Entry, iter, slice, thread::ThreadId}; #[repr(C)] #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] diff --git a/wgpu-native/src/command/render.rs b/wgpu-native/src/command/render.rs index 874d124467..ce3d0dfd84 100644 --- a/wgpu-native/src/command/render.rs +++ b/wgpu-native/src/command/render.rs @@ -6,14 +6,20 @@ use crate::{ pipeline::{IndexFormat, PipelineFlags}, resource::BufferUsageFlags, track::{Stitch, TrackerSet}, - BindGroupId, BufferId, Color, CommandBuffer, CommandBufferId, RenderPassId, RenderPipelineId, Stored, + BindGroupId, + BufferId, + Color, + CommandBuffer, + CommandBufferId, + RenderPassId, + RenderPipelineId, + Stored, }; use hal::command::RawCommandBuffer; use std::{iter, slice}; - #[derive(Debug, PartialEq)] enum BlendColorStatus { Unused, @@ -75,7 +81,7 @@ impl RenderPass { }); } if self.blend_color_status == BlendColorStatus::Required { - return Err(DrawError::MissingBlendColor) + return Err(DrawError::MissingBlendColor); } Ok(()) } @@ -231,8 +237,8 @@ pub extern "C" fn wgpu_render_pass_set_bind_group( .provide_entry(index as usize, bind_group_id, bind_group) { let pipeline_layout_guard = HUB.pipeline_layouts.read(); - let bind_groups = iter::once(&bind_group.raw) - .chain(follow_up.map(|bg_id| &bind_group_guard[bg_id].raw)); + let bind_groups = + iter::once(&bind_group.raw).chain(follow_up.map(|bg_id| &bind_group_guard[bg_id].raw)); unsafe { pass.raw.bind_graphics_descriptor_sets( &&pipeline_layout_guard[pipeline_layout_id].raw, @@ -259,7 +265,9 @@ pub extern "C" fn wgpu_render_pass_set_pipeline( "The render pipeline is not compatible with the pass!" ); - if pipeline.flags.contains(PipelineFlags::BLEND_COLOR) && pass.blend_color_status == BlendColorStatus::Unused { + if pipeline.flags.contains(PipelineFlags::BLEND_COLOR) + && pass.blend_color_status == BlendColorStatus::Unused + { pass.blend_color_status = BlendColorStatus::Required; } @@ -276,7 +284,8 @@ pub extern "C" fn wgpu_render_pass_set_pipeline( let bind_group_guard = HUB.bind_groups.read(); pass.binder.pipeline_layout_id = Some(pipeline.layout_id.clone()); - pass.binder.reset_expectations(pipeline_layout.bind_group_layout_ids.len()); + pass.binder + .reset_expectations(pipeline_layout.bind_group_layout_ids.len()); for (index, (entry, &bgl_id)) in pass .binder @@ -324,10 +333,7 @@ pub extern "C" fn wgpu_render_pass_set_pipeline( } #[no_mangle] -pub extern "C" fn wgpu_render_pass_set_blend_color( - pass_id: RenderPassId, - color: &Color, -) { +pub extern "C" fn wgpu_render_pass_set_blend_color(pass_id: RenderPassId, color: &Color) { let mut pass_guard = HUB.render_passes.write(); let pass = &mut pass_guard[pass_id]; diff --git a/wgpu-native/src/command/transfer.rs b/wgpu-native/src/command/transfer.rs index 124b69215d..47ae776760 100644 --- a/wgpu-native/src/command/transfer.rs +++ b/wgpu-native/src/command/transfer.rs @@ -4,7 +4,13 @@ use crate::{ hub::HUB, resource::TexturePlacement, swap_chain::SwapChainLink, - BufferId, BufferUsageFlags, CommandBufferId, Extent3d, Origin3d, TextureId, TextureUsageFlags, + BufferId, + BufferUsageFlags, + CommandBufferId, + Extent3d, + Origin3d, + TextureId, + TextureUsageFlags, }; use copyless::VecHelper as _; @@ -12,7 +18,6 @@ use hal::command::RawCommandBuffer; use std::iter; - const BITS_PER_BYTE: u32 = 8; #[repr(C)] diff --git a/wgpu-native/src/conv.rs b/wgpu-native/src/conv.rs index 28ebb64d3f..b4d20f517e 100644 --- a/wgpu-native/src/conv.rs +++ b/wgpu-native/src/conv.rs @@ -1,8 +1,4 @@ -use crate::{ - binding_model, command, pipeline, resource, - Color, Extent3d, Origin3d, -}; - +use crate::{binding_model, command, pipeline, resource, Color, Extent3d, Origin3d}; pub fn map_buffer_usage( usage: resource::BufferUsageFlags, diff --git a/wgpu-native/src/device.rs b/wgpu-native/src/device.rs index 800eead0e5..0d51482b92 100644 --- a/wgpu-native/src/device.rs +++ b/wgpu-native/src/device.rs @@ -1,36 +1,57 @@ use crate::{ - binding_model, command, conv, pipeline, resource, swap_chain, + binding_model, + command, + conv, hub::HUB, - track::{DummyUsage, Stitch, Tracktion, TrackPermit, TrackerSet}, - AdapterId, BindGroupId, BufferId, CommandBufferId, DeviceId, QueueId, SurfaceId, TextureId, + pipeline, + resource, + swap_chain, + track::{DummyUsage, Stitch, TrackPermit, TrackerSet, Tracktion}, + AdapterId, + BindGroupId, + BufferId, + BufferMapAsyncStatus, + BufferMapOperation, + CommandBufferId, + DeviceId, + LifeGuard, + QueueId, + RefCount, + Stored, + SubmissionIndex, + SurfaceId, + TextureId, TextureViewId, - BufferMapAsyncStatus, BufferMapOperation, LifeGuard, RefCount, Stored, SubmissionIndex, }; #[cfg(feature = "local")] use crate::{ - BindGroupLayoutId, CommandEncoderId, ComputePipelineId, PipelineLayoutId, RenderPipelineId, - SamplerId, ShaderModuleId, SwapChainId, + BindGroupLayoutId, + CommandEncoderId, + ComputePipelineId, + PipelineLayoutId, + RenderPipelineId, + SamplerId, + ShaderModuleId, + SwapChainId, }; use arrayvec::ArrayVec; -use copyless::VecHelper as _; use back; +use copyless::VecHelper as _; use hal::{ - self, DescriptorPool as _, Device as _, Surface as _, + self, backend::FastHashMap, command::RawCommandBuffer, queue::RawCommandQueue, + DescriptorPool as _, + Device as _, + Surface as _, }; use log::{info, trace}; //use rendy_memory::{allocator, Config, Heaps}; use parking_lot::Mutex; -use std::{ - ffi, iter, ptr, slice, - collections::hash_map::Entry, - sync::atomic::Ordering, -}; - +use std::{collections::hash_map::Entry, ffi, iter, ptr, slice, sync::atomic::Ordering}; pub const MAX_COLOR_TARGETS: usize = 4; @@ -151,13 +172,12 @@ impl PendingResources { hal::device::WaitFor::All, !0, ) - }.unwrap(); + } + .unwrap(); } for i in (0..self.active.len()).rev() { - if force_wait || unsafe { - device.get_fence_status(&self.active[i].fence).unwrap() - } { + if force_wait || unsafe { device.get_fence_status(&self.active[i].fence).unwrap() } { let a = self.active.swap_remove(i); trace!("Active submission {} is done", a.index); last_done = last_done.max(a.index); @@ -248,9 +268,12 @@ impl PendingResources { let buf = &buffer_guard[resource_id]; let submit_index = buf.life_guard.submission_index.load(Ordering::Acquire); - trace!("Mapping of {:?} at submission {:?} gets assigned to active {:?}", - resource_id, submit_index, - self.active.iter().position(|a| a.index == submit_index)); + trace!( + "Mapping of {:?} at submission {:?} gets assigned to active {:?}", + resource_id, + submit_index, + self.active.iter().position(|a| a.index == submit_index) + ); self.active .iter_mut() @@ -328,12 +351,8 @@ impl PendingResources { }; match operation { - BufferMapOperation::Read(_, callback, userdata) => { - callback(status, ptr, userdata) - } - BufferMapOperation::Write(_, callback, userdata) => { - callback(status, ptr, userdata) - } + BufferMapOperation::Read(_, callback, userdata) => callback(status, ptr, userdata), + BufferMapOperation::Write(_, callback, userdata) => callback(status, ptr, userdata), }; } } @@ -349,10 +368,16 @@ fn map_buffer( // gfx-rs requires mapping and flushing/invalidation ranges to be done at `non_coherent_atom_size` // granularity for memory types that aren't coherent. We achieve that by flooring the start offset // and ceiling the end offset to those atom sizes, using bitwise operations on an `atom_mask`. - let is_coherent = buffer.memory_properties.contains(hal::memory::Properties::COHERENT); - let atom_mask = if is_coherent { 0 } else { limits.non_coherent_atom_size as u64 - 1 }; + let is_coherent = buffer + .memory_properties + .contains(hal::memory::Properties::COHERENT); + let atom_mask = if is_coherent { + 0 + } else { + limits.non_coherent_atom_size as u64 - 1 + }; let atom_offset = original_range.start & atom_mask; - let range = (original_range.start & !atom_mask) .. ((original_range.end - 1) | atom_mask) + 1; + let range = (original_range.start & !atom_mask)..((original_range.end - 1) | atom_mask) + 1; let pointer = unsafe { raw.map_memory(&buffer.memory, range.clone()) }?; if !is_coherent { @@ -520,19 +545,14 @@ pub fn device_create_buffer( // if the memory is mapped but not coherent, round up to the atom size let mut mem_size = requirements.size; - if memory_properties.contains(hal::memory::Properties::CPU_VISIBLE) && - !memory_properties.contains(hal::memory::Properties::COHERENT) + if memory_properties.contains(hal::memory::Properties::CPU_VISIBLE) + && !memory_properties.contains(hal::memory::Properties::COHERENT) { let mask = device.limits.non_coherent_atom_size as u64 - 1; - mem_size = ((mem_size - 1 ) | mask) + 1; + mem_size = ((mem_size - 1) | mask) + 1; } - let memory = unsafe { - device - .raw - .allocate_memory(device_type, mem_size) - .unwrap() - }; + let memory = unsafe { device.raw.allocate_memory(device_type, mem_size).unwrap() }; unsafe { device .raw @@ -599,9 +619,15 @@ pub extern "C" fn wgpu_device_create_buffer_mapped( let device_guard = HUB.devices.read(); let device = &device_guard[device_id]; - let range = 0 .. desc.size as u64; + let range = 0..desc.size as u64; - match map_buffer(&device.raw, &device.limits, &mut buffer, &range, HostMap::Write) { + match map_buffer( + &device.raw, + &device.limits, + &mut buffer, + &range, + HostMap::Write, + ) { Ok(ptr) => unsafe { *mapped_ptr_out = ptr; }, @@ -999,12 +1025,20 @@ pub fn device_create_bind_group( ) .unwrap(); let alignment = match decl.ty { - binding_model::BindingType::UniformBuffer => device.limits.min_uniform_buffer_offset_alignment, - binding_model::BindingType::StorageBuffer => device.limits.min_storage_buffer_offset_alignment, + binding_model::BindingType::UniformBuffer => { + device.limits.min_uniform_buffer_offset_alignment + } + binding_model::BindingType::StorageBuffer => { + device.limits.min_storage_buffer_offset_alignment + } _ => panic!("Mismatched buffer binding for {:?}", decl), }; - assert_eq!(bb.offset as hal::buffer::Offset % alignment, 0, - "Misaligned buffer offset {}", bb.offset); + assert_eq!( + bb.offset as hal::buffer::Offset % alignment, + 0, + "Misaligned buffer offset {}", + bb.offset + ); let range = Some(bb.offset as u64)..Some((bb.offset + bb.size) as u64); hal::pso::Descriptor::Buffer(&buffer.raw, range) } @@ -1212,21 +1246,22 @@ pub extern "C" fn wgpu_queue_submit( let command_buffer_guard = HUB.command_buffers.read(); let surface_guard = HUB.surfaces.read(); - let wait_semaphores = swap_chain_links - .into_iter() - .flat_map(|link| { - let swap_chain = surface_guard[link.swap_chain_id].swap_chain.as_ref()?; - let frame = &swap_chain.frames[link.image_index as usize]; - let mut wait_for_epoch = frame.wait_for_epoch.lock(); - let current_epoch = *wait_for_epoch.as_ref()?; - if link.epoch < current_epoch { - None - } else { - debug_assert_eq!(link.epoch, current_epoch); - *wait_for_epoch = None; - Some((&frame.sem_available, hal::pso::PipelineStage::COLOR_ATTACHMENT_OUTPUT)) - } - }); + let wait_semaphores = swap_chain_links.into_iter().flat_map(|link| { + let swap_chain = surface_guard[link.swap_chain_id].swap_chain.as_ref()?; + let frame = &swap_chain.frames[link.image_index as usize]; + let mut wait_for_epoch = frame.wait_for_epoch.lock(); + let current_epoch = *wait_for_epoch.as_ref()?; + if link.epoch < current_epoch { + None + } else { + debug_assert_eq!(link.epoch, current_epoch); + *wait_for_epoch = None; + Some(( + &frame.sem_available, + hal::pso::PipelineStage::COLOR_ATTACHMENT_OUTPUT, + )) + } + }); let submission = hal::queue::Submission::<_, _, &[::Semaphore]> { @@ -1469,7 +1504,10 @@ pub fn device_create_render_pipeline( }; let mut flags = pipeline::PipelineFlags::empty(); - if color_states.iter().any(|state| state.color.uses_color() | state.alpha.uses_color()) { + if color_states + .iter() + .any(|state| state.color.uses_color() | state.alpha.uses_color()) + { flags |= pipeline::PipelineFlags::BLEND_COLOR; } @@ -1872,7 +1910,12 @@ pub extern "C" fn wgpu_buffer_map_read_async( let device = &device_guard[device_id]; let usage = resource::BufferUsageFlags::MAP_READ; - match device.trackers.lock().buffers.transit(buffer_id, &ref_count, usage, TrackPermit::REPLACE) { + match device + .trackers + .lock() + .buffers + .transit(buffer_id, &ref_count, usage, TrackPermit::REPLACE) + { Ok(Tracktion::Keep) => {} Ok(Tracktion::Replace { .. }) => { //TODO: launch a memory barrier into `HOST_READ` access? @@ -1880,9 +1923,7 @@ pub extern "C" fn wgpu_buffer_map_read_async( other => panic!("Invalid mapping transition {:?}", other), } - device.pending - .lock() - .map(buffer_id, ref_count); + device.pending.lock().map(buffer_id, ref_count); } #[no_mangle] @@ -1912,7 +1953,12 @@ pub extern "C" fn wgpu_buffer_map_write_async( let device = &device_guard[device_id]; let usage = resource::BufferUsageFlags::MAP_WRITE; - match device.trackers.lock().buffers.transit(buffer_id, &ref_count, usage, TrackPermit::REPLACE) { + match device + .trackers + .lock() + .buffers + .transit(buffer_id, &ref_count, usage, TrackPermit::REPLACE) + { Ok(Tracktion::Keep) => {} Ok(Tracktion::Replace { .. }) => { //TODO: launch a memory barrier into `HOST_WRITE` access? @@ -1920,9 +1966,7 @@ pub extern "C" fn wgpu_buffer_map_write_async( other => panic!("Invalid mapping transition {:?}", other), } - device.pending - .lock() - .map(buffer_id, ref_count); + device.pending.lock().map(buffer_id, ref_count); } #[no_mangle] diff --git a/wgpu-native/src/hub.rs b/wgpu-native/src/hub.rs index 43f35e75c9..d34c00b2e6 100644 --- a/wgpu-native/src/hub.rs +++ b/wgpu-native/src/hub.rs @@ -1,8 +1,21 @@ use crate::{ - AdapterHandle, BindGroupHandle, BindGroupLayoutHandle, BufferHandle, CommandBufferHandle, - ComputePassHandle, ComputePipelineHandle, DeviceHandle, InstanceHandle, PipelineLayoutHandle, - RenderPassHandle, RenderPipelineHandle, SamplerHandle, ShaderModuleHandle, SurfaceHandle, - TextureHandle, TextureViewHandle, + AdapterHandle, + BindGroupHandle, + BindGroupLayoutHandle, + BufferHandle, + CommandBufferHandle, + ComputePassHandle, + ComputePipelineHandle, + DeviceHandle, + InstanceHandle, + PipelineLayoutHandle, + RenderPassHandle, + RenderPipelineHandle, + SamplerHandle, + ShaderModuleHandle, + SurfaceHandle, + TextureHandle, + TextureViewHandle, }; use lazy_static::lazy_static; @@ -13,11 +26,7 @@ use parking_lot::RwLock; use serde::{Deserialize, Serialize}; use vec_map::VecMap; -use std::{ - ops, - sync::Arc, -}; - +use std::{ops, sync::Arc}; pub(crate) type Index = u32; pub(crate) type Epoch = u32; diff --git a/wgpu-native/src/instance.rs b/wgpu-native/src/instance.rs index 4cff380312..a41d187834 100644 --- a/wgpu-native/src/instance.rs +++ b/wgpu-native/src/instance.rs @@ -1,7 +1,4 @@ -use crate::{ - hub::HUB, - AdapterHandle, AdapterId, DeviceHandle, InstanceId, SurfaceHandle, -}; +use crate::{hub::HUB, AdapterHandle, AdapterId, DeviceHandle, InstanceId, SurfaceHandle}; #[cfg(feature = "local")] use crate::{DeviceId, SurfaceId}; @@ -12,7 +9,6 @@ use serde::{Deserialize, Serialize}; use hal::{self, Instance as _, PhysicalDevice as _}; - #[repr(C)] #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] #[cfg_attr(feature = "remote", derive(Serialize, Deserialize))] diff --git a/wgpu-native/src/pipeline.rs b/wgpu-native/src/pipeline.rs index d400832d53..b03e09b797 100644 --- a/wgpu-native/src/pipeline.rs +++ b/wgpu-native/src/pipeline.rs @@ -1,12 +1,7 @@ -use crate::{ - device::RenderPassContext, - resource, - ByteArray, PipelineLayoutId, ShaderModuleId, -}; +use crate::{device::RenderPassContext, resource, ByteArray, PipelineLayoutId, ShaderModuleId}; use bitflags::bitflags; - pub type ShaderAttributeIndex = u32; #[repr(C)] @@ -66,10 +61,10 @@ impl BlendDescriptor { pub fn uses_color(&self) -> bool { match (self.src_factor, self.dst_factor) { - (BlendFactor::BlendColor, _) | - (BlendFactor::OneMinusBlendColor, _) | - (_, BlendFactor::BlendColor) | - (_, BlendFactor::OneMinusBlendColor) => true, + (BlendFactor::BlendColor, _) + | (BlendFactor::OneMinusBlendColor, _) + | (_, BlendFactor::BlendColor) + | (_, BlendFactor::OneMinusBlendColor) => true, (_, _) => false, } } diff --git a/wgpu-native/src/resource.rs b/wgpu-native/src/resource.rs index 9acd10386c..f76354447c 100644 --- a/wgpu-native/src/resource.rs +++ b/wgpu-native/src/resource.rs @@ -1,6 +1,12 @@ use crate::{ swap_chain::{SwapChainLink, SwapImageEpoch}, - BufferMapReadCallback, BufferMapWriteCallback, DeviceId, Extent3d, LifeGuard, RefCount, Stored, + BufferMapReadCallback, + BufferMapWriteCallback, + DeviceId, + Extent3d, + LifeGuard, + RefCount, + Stored, TextureId, }; @@ -10,7 +16,6 @@ use parking_lot::Mutex; use std::borrow::Borrow; - bitflags! { #[repr(transparent)] pub struct BufferUsageFlags: u32 { diff --git a/wgpu-native/src/swap_chain.rs b/wgpu-native/src/swap_chain.rs index 8ae07de0fe..e97e1ff806 100644 --- a/wgpu-native/src/swap_chain.rs +++ b/wgpu-native/src/swap_chain.rs @@ -1,9 +1,15 @@ use crate::{ - conv, resource, + conv, device::all_image_stages, hub::HUB, + resource, track::TrackPermit, - DeviceId, Extent3d, Stored, SwapChainId, TextureId, TextureViewId, + DeviceId, + Extent3d, + Stored, + SwapChainId, + TextureId, + TextureViewId, }; use hal::{self, Device as _, Swapchain as _}; @@ -12,7 +18,6 @@ use parking_lot::Mutex; use std::{iter, mem}; - pub type SwapImageEpoch = u16; pub(crate) struct SwapChainLink { diff --git a/wgpu-native/src/track.rs b/wgpu-native/src/track.rs index fb30458165..83f130f4ad 100644 --- a/wgpu-native/src/track.rs +++ b/wgpu-native/src/track.rs @@ -1,7 +1,10 @@ use crate::{ hub::{Epoch, Id, Index, NewId, Storage}, resource::{BufferUsageFlags, TextureUsageFlags}, - BufferId, RefCount, TextureId, TextureViewId, + BufferId, + RefCount, + TextureId, + TextureViewId, }; use bitflags::bitflags; @@ -15,7 +18,6 @@ use std::{ ops::{BitOr, Range}, }; - #[derive(Clone, Debug, PartialEq)] #[allow(unused)] pub enum Tracktion { diff --git a/wgpu-rs/src/lib.rs b/wgpu-rs/src/lib.rs index ce60b02b41..2edd6fff34 100644 --- a/wgpu-rs/src/lib.rs +++ b/wgpu-rs/src/lib.rs @@ -10,17 +10,55 @@ use std::slice; pub use wgn::winit; pub use wgn::{ - AdapterDescriptor, AddressMode, BindGroupLayoutBinding, BindingType, BlendDescriptor, - BlendFactor, BlendOperation, BorderColor, BufferDescriptor, BufferMapAsyncStatus, - BufferUsageFlags, Color, ColorStateDescriptor, ColorWriteFlags, CommandEncoderDescriptor, - CompareFunction, CullMode, DepthStencilStateDescriptor, DeviceDescriptor, Extensions, Extent3d, - FilterMode, FrontFace, IndexFormat, InputStepMode, LoadOp, Origin3d, PowerPreference, - PrimitiveTopology, RasterizationStateDescriptor, RenderPassColorAttachmentDescriptor, - RenderPassDepthStencilAttachmentDescriptor, SamplerDescriptor, ShaderAttributeIndex, - ShaderModuleDescriptor, ShaderStageFlags, StencilOperation, StencilStateFaceDescriptor, - StoreOp, SwapChainDescriptor, TextureAspectFlags, TextureDescriptor, TextureDimension, - TextureFormat, TextureUsageFlags, TextureViewDescriptor, TextureViewDimension, - VertexAttributeDescriptor, VertexFormat, + AdapterDescriptor, + AddressMode, + BindGroupLayoutBinding, + BindingType, + BlendDescriptor, + BlendFactor, + BlendOperation, + BorderColor, + BufferDescriptor, + BufferMapAsyncStatus, + BufferUsageFlags, + Color, + ColorStateDescriptor, + ColorWriteFlags, + CommandEncoderDescriptor, + CompareFunction, + CullMode, + DepthStencilStateDescriptor, + DeviceDescriptor, + Extensions, + Extent3d, + FilterMode, + FrontFace, + IndexFormat, + InputStepMode, + LoadOp, + Origin3d, + PowerPreference, + PrimitiveTopology, + RasterizationStateDescriptor, + RenderPassColorAttachmentDescriptor, + RenderPassDepthStencilAttachmentDescriptor, + SamplerDescriptor, + ShaderAttributeIndex, + ShaderModuleDescriptor, + ShaderStageFlags, + StencilOperation, + StencilStateFaceDescriptor, + StoreOp, + SwapChainDescriptor, + TextureAspectFlags, + TextureDescriptor, + TextureDimension, + TextureFormat, + TextureUsageFlags, + TextureViewDescriptor, + TextureViewDimension, + VertexAttributeDescriptor, + VertexFormat, }; //TODO: avoid heap allocating vectors during resource creation.