From 4413c4648dcb4538cbbc6db172a696facae57bd0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 29 Apr 2020 18:33:42 -0400 Subject: [PATCH] Update for wgpu-core --- Cargo.toml | 6 +- examples/capture/main.rs | 2 +- examples/cube/main.rs | 5 +- examples/framework.rs | 3 +- examples/hello-compute/main.rs | 10 +-- examples/hello-triangle/main.rs | 11 ++- examples/mipmap/main.rs | 3 + examples/shadow/main.rs | 2 + examples/skybox/main.rs | 2 + src/backend/direct.rs | 116 ++++++-------------------------- src/backend/web.rs | 9 ++- src/lib.rs | 62 ++++++----------- 12 files changed, 77 insertions(+), 154 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 1006b4c02..21d1fdbde 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ exclude = ["etc/**/*", "examples/**/*", "tests/**/*", "Cargo.lock", "target/**/* [features] default = [] +trace = ["wgc/trace"] # Make Vulkan backend available on platforms where it is by default not, e.g. macOS vulkan = ["wgc/gfx-backend-vulkan"] @@ -27,13 +28,14 @@ vulkan = ["wgc/gfx-backend-vulkan"] package = "wgpu-core" version = "0.5" git = "https://github.com/gfx-rs/wgpu" -rev = "5c172dd4756aa152b4f3350e624d7b1b5d24ddda" +rev = "f64b2dd3bb9e11c1dfc0eb3be44fbaae81b18c7b" +features = ["raw-window-handle"] [dependencies.wgt] package = "wgpu-types" version = "0.5" git = "https://github.com/gfx-rs/wgpu" -rev = "5c172dd4756aa152b4f3350e624d7b1b5d24ddda" +rev = "f64b2dd3bb9e11c1dfc0eb3be44fbaae81b18c7b" [dependencies] arrayvec = "0.5" diff --git a/examples/capture/main.rs b/examples/capture/main.rs index 1034a178d..de4f0f25c 100644 --- a/examples/capture/main.rs +++ b/examples/capture/main.rs @@ -22,7 +22,7 @@ async fn run() { anisotropic_filtering: false, }, limits: wgpu::Limits::default(), - }) + }, None) .await .unwrap(); diff --git a/examples/cube/main.rs b/examples/cube/main.rs index 689da44d8..a014ec0f1 100644 --- a/examples/cube/main.rs +++ b/examples/cube/main.rs @@ -135,6 +135,7 @@ impl framework::Example for Example { // Create pipeline layout let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, bindings: &[ wgpu::BindGroupLayoutEntry { binding: 0, @@ -156,7 +157,6 @@ impl framework::Example for Example { ty: wgpu::BindingType::Sampler { comparison: false }, }, ], - label: None, }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { bind_group_layouts: &[&bind_group_layout], @@ -171,13 +171,13 @@ impl framework::Example for Example { depth: 1, }; let texture = device.create_texture(&wgpu::TextureDescriptor { + label: None, size: texture_extent, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8UnormSrgb, usage: wgpu::TextureUsage::SAMPLED | wgpu::TextureUsage::COPY_DST, - label: None, }); let texture_view = texture.create_default_view(); let temp_buf = @@ -200,6 +200,7 @@ impl framework::Example for Example { // Create other resources let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: None, address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, diff --git a/examples/framework.rs b/examples/framework.rs index 84c55ddbf..f088d9f17 100644 --- a/examples/framework.rs +++ b/examples/framework.rs @@ -73,7 +73,7 @@ async fn run_async(event_loop: EventLoop<()>, window: Window) { anisotropic_filtering: false, }, limits: wgpu::Limits::default(), - }) + }, None) .await .unwrap(); @@ -99,6 +99,7 @@ async fn run_async(event_loop: EventLoop<()>, window: Window) { log::info!("Entering render loop..."); event_loop.run(move |event, _, control_flow| { + let _ = (&instance, &adapter); // force ownership by the closure *control_flow = if cfg!(feature = "metal-auto-capture") { ControlFlow::Exit } else { diff --git a/examples/hello-compute/main.rs b/examples/hello-compute/main.rs index 9e60f9920..ea333a136 100644 --- a/examples/hello-compute/main.rs +++ b/examples/hello-compute/main.rs @@ -3,7 +3,7 @@ use std::{convert::TryInto, str::FromStr}; async fn run() { let numbers = if std::env::args().len() <= 1 { let default = vec![1, 2, 3, 4]; - log::info!("No numbers were provided, defaulting to {:?}", default); + println!("No numbers were provided, defaulting to {:?}", default); default } else { std::env::args() @@ -12,8 +12,10 @@ async fn run() { .collect() }; - // To see the output, run `RUST_LOG=info cargo run --example hello-compute`. - log::info!("Times: {:?}", execute_gpu(numbers).await); + let times = execute_gpu(numbers).await; + println!("Times: {:?}", times); + #[cfg(target_arch = "wasm32")] + log::info!("Times: {:?}", times); } async fn execute_gpu(numbers: Vec) -> Vec { @@ -38,7 +40,7 @@ async fn execute_gpu(numbers: Vec) -> Vec { anisotropic_filtering: false, }, limits: wgpu::Limits::default(), - }) + }, None) .await .unwrap(); diff --git a/examples/hello-triangle/main.rs b/examples/hello-triangle/main.rs index 7df29c320..15c8e9b8f 100644 --- a/examples/hello-triangle/main.rs +++ b/examples/hello-triangle/main.rs @@ -25,7 +25,7 @@ async fn run(event_loop: EventLoop<()>, window: Window, swapchain_format: wgpu:: anisotropic_filtering: false, }, limits: wgpu::Limits::default(), - }) + }, None) .await .unwrap(); @@ -86,6 +86,15 @@ async fn run(event_loop: EventLoop<()>, window: Window, swapchain_format: wgpu:: let mut swap_chain = device.create_swap_chain(&surface, &sc_desc); event_loop.run(move |event, _, control_flow| { + // force ownership by the closure + let _ = ( + &instance, + &adapter, + &vs_module, + &fs_module, + &pipeline_layout, + ); + *control_flow = ControlFlow::Poll; match event { Event::MainEventsCleared => window.request_redraw(), diff --git a/examples/mipmap/main.rs b/examples/mipmap/main.rs index 962c520eb..a9e12fc83 100644 --- a/examples/mipmap/main.rs +++ b/examples/mipmap/main.rs @@ -147,6 +147,7 @@ impl Example { }); let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("mip"), address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, @@ -161,6 +162,7 @@ impl Example { let views = (0..mip_count) .map(|mip| { texture.create_view(&wgpu::TextureViewDescriptor { + label: Some("mip"), format: TEXTURE_FORMAT, dimension: wgpu::TextureViewDimension::D2, aspect: wgpu::TextureAspect::All, @@ -293,6 +295,7 @@ impl framework::Example for Example { // Create other resources let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: None, address_mode_u: wgpu::AddressMode::Repeat, address_mode_v: wgpu::AddressMode::Repeat, address_mode_w: wgpu::AddressMode::Repeat, diff --git a/examples/shadow/main.rs b/examples/shadow/main.rs index 6730df3c9..a451bb4e1 100644 --- a/examples/shadow/main.rs +++ b/examples/shadow/main.rs @@ -346,6 +346,7 @@ impl framework::Example for Example { // Create other resources let shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("shadow"), address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, @@ -371,6 +372,7 @@ impl framework::Example for Example { let mut shadow_target_views = (0..2) .map(|i| { Some(shadow_texture.create_view(&wgpu::TextureViewDescriptor { + label: Some("shadow"), format: Self::SHADOW_FORMAT, dimension: wgpu::TextureViewDimension::D2, aspect: wgpu::TextureAspect::All, diff --git a/examples/skybox/main.rs b/examples/skybox/main.rs index 4359b2096..3301eeeca 100644 --- a/examples/skybox/main.rs +++ b/examples/skybox/main.rs @@ -138,6 +138,7 @@ impl framework::Example for Skybox { }); let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: None, address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, @@ -219,6 +220,7 @@ impl framework::Example for Skybox { } let texture_view = texture.create_view(&wgpu::TextureViewDescriptor { + label: None, format: SKYBOX_FORMAT, dimension: wgpu::TextureViewDimension::Cube, aspect: wgpu::TextureAspect::default(), diff --git a/src/backend/direct.rs b/src/backend/direct.rs index fed7fc352..52263a436 100644 --- a/src/backend/direct.rs +++ b/src/backend/direct.rs @@ -13,7 +13,7 @@ use std::{ffi::CString, marker::PhantomData, ptr, slice}; macro_rules! gfx_select { ($id:expr => $global:ident.$method:ident( $($param:expr),+ )) => { match $id.backend() { - #[cfg(any(not(any(target_os = "ios", target_os = "macos")), feature = "gfx-backend-vulkan"))] + #[cfg(any(not(any(target_os = "ios", target_os = "macos")), feature = "vulkan-portability"))] wgt::Backend::Vulkan => $global.$method::( $($param),+ ), #[cfg(any(target_os = "ios", target_os = "macos"))] wgt::Backend::Metal => $global.$method::( $($param),+ ), @@ -222,80 +222,11 @@ impl crate::Context for Context { wgc::hub::Global::new("wgpu", wgc::hub::IdentityManagerFactory) } - fn instance_create_surface( + fn instance_create_surface( &self, - window: &W, + handle: raw_window_handle::RawWindowHandle, ) -> Self::SurfaceId { - use raw_window_handle::RawWindowHandle as Rwh; - - let surface = match window.raw_window_handle() { - #[cfg(target_os = "ios")] - Rwh::IOS(h) => wgc::instance::Surface { - #[cfg(feature = "vulkan-portability")] - vulkan: None, - metal: self - .instance - .metal - .create_surface_from_uiview(h.ui_view, cfg!(debug_assertions)), - }, - #[cfg(target_os = "macos")] - Rwh::MacOS(h) => { - use objc::{msg_send, runtime::Object, sel, sel_impl}; - let ns_view = if h.ns_view.is_null() { - let ns_window = h.ns_window as *mut Object; - unsafe { msg_send![ns_window, contentView] } - } else { - h.ns_view - }; - wgc::instance::Surface { - #[cfg(feature = "vulkan-portability")] - vulkan: self - .instance - .vulkan - .as_ref() - .map(|inst| inst.create_surface_from_ns_view(ns_view)), - metal: self - .instance - .metal - .create_surface_from_nsview(ns_view, cfg!(debug_assertions)), - } - } - #[cfg(all(unix, not(target_os = "ios"), not(target_os = "macos")))] - Rwh::Xlib(h) => wgc::instance::Surface { - vulkan: self - .instance - .vulkan - .as_ref() - .map(|inst| inst.create_surface_from_xlib(h.display as _, h.window as _)), - }, - #[cfg(all(unix, not(target_os = "ios"), not(target_os = "macos")))] - Rwh::Wayland(h) => wgc::instance::Surface { - vulkan: self - .instance - .vulkan - .as_ref() - .map(|inst| inst.create_surface_from_wayland(h.display, h.surface)), - }, - #[cfg(windows)] - Rwh::Windows(h) => wgc::instance::Surface { - vulkan: self - .instance - .vulkan - .as_ref() - .map(|inst| inst.create_surface_from_hwnd(std::ptr::null_mut(), h.hwnd)), - dx12: self - .instance - .dx12 - .as_ref() - .map(|inst| inst.create_surface_from_hwnd(h.hwnd)), - dx11: self.instance.dx11.create_surface_from_hwnd(h.hwnd), - }, - _ => panic!("Unsupported window handle"), - }; - - let mut token = wgc::hub::Token::root(); - self.surfaces - .register_identity(PhantomData, surface, &mut token) + self.instance_create_surface(handle, PhantomData) } fn instance_request_adapter( @@ -308,7 +239,7 @@ impl crate::Context for Context { power_preference: options.power_preference, compatible_surface: options.compatible_surface.map(|surface| surface.id), }, - wgc::instance::AdapterInputs::Mask(backends, || PhantomData), + wgc::instance::AdapterInputs::Mask(backends, |_| PhantomData), ); ready(id) } @@ -317,9 +248,9 @@ impl crate::Context for Context { &self, adapter: &Self::AdapterId, desc: &crate::DeviceDescriptor, + trace_dir: Option<&std::path::Path>, ) -> Self::RequestDeviceFuture { - let device_id = - gfx_select!(*adapter => self.adapter_request_device(*adapter, desc, PhantomData)); + let device_id = gfx_select!(*adapter => self.adapter_request_device(*adapter, desc, trace_dir, PhantomData)); ready(Ok((device_id, device_id))) } @@ -579,11 +510,7 @@ impl crate::Context for Context { unsafe { let (id, ptr) = gfx_select!(*device => self.device_create_buffer_mapped( *device, - &wgt::BufferDescriptor { - label: owned_label.as_ptr(), - size: desc.size, - usage: desc.usage, - }, + &desc.map_label(|_| owned_label.as_ptr()), PhantomData )); let mapped_data = std::slice::from_raw_parts_mut(ptr, desc.size as usize); @@ -599,11 +526,7 @@ impl crate::Context for Context { let owned_label = OwnedLabel::new(desc.label.as_deref()); gfx_select!(*device => self.device_create_buffer( *device, - &wgt::BufferDescriptor { - label: owned_label.as_ptr(), - size: desc.size, - usage: desc.usage, - }, + &desc.map_label(|_| owned_label.as_ptr()), PhantomData )) } @@ -616,15 +539,7 @@ impl crate::Context for Context { let owned_label = OwnedLabel::new(desc.label.as_deref()); gfx_select!(*device => self.device_create_texture( *device, - &wgt::TextureDescriptor { - label: owned_label.as_ptr(), - size: desc.size, - mip_level_count: desc.mip_level_count, - sample_count: desc.sample_count, - dimension: desc.dimension, - format: desc.format, - usage: desc.usage, - }, + &desc.map_label(|_| owned_label.as_ptr()), PhantomData )) } @@ -634,7 +549,12 @@ impl crate::Context for Context { device: &Self::DeviceId, desc: &SamplerDescriptor, ) -> Self::SamplerId { - gfx_select!(*device => self.device_create_sampler(*device, desc, PhantomData)) + let owned_label = OwnedLabel::new(desc.label.as_deref()); + gfx_select!(*device => self.device_create_sampler( + *device, + &desc.map_label(|_| owned_label.as_ptr()), + PhantomData + )) } fn device_create_command_encoder( @@ -774,7 +694,9 @@ impl crate::Context for Context { texture: &Self::TextureId, desc: Option<&TextureViewDescriptor>, ) -> Self::TextureViewId { - gfx_select!(*texture => self.texture_create_view(*texture, desc, PhantomData)) + let owned_label = OwnedLabel::new(desc.and_then(|d| d.label.as_deref())); + let descriptor = desc.map(|d| d.map_label(|_| owned_label.as_ptr())); + gfx_select!(*texture => self.texture_create_view(*texture, descriptor.as_ref(), PhantomData)) } fn texture_drop(&self, texture: &Self::TextureId) { diff --git a/src/backend/web.rs b/src/backend/web.rs index f8a815c08..893cebefb 100644 --- a/src/backend/web.rs +++ b/src/backend/web.rs @@ -603,11 +603,10 @@ impl crate::Context for Context { web_sys::window().unwrap().navigator().gpu() } - fn instance_create_surface( + fn instance_create_surface( &self, - window: &W, + handle: raw_window_handle::RawWindowHandle, ) -> Self::SurfaceId { - let handle = window.raw_window_handle(); let canvas_attribute = match handle { raw_window_handle::RawWindowHandle::Web(web_handle) => web_handle.id, _ => panic!("expected valid handle for canvas"), @@ -654,7 +653,11 @@ impl crate::Context for Context { &self, adapter: &Self::AdapterId, desc: &crate::DeviceDescriptor, + trace_dir: Option<&std::path::Path>, ) -> Self::RequestDeviceFuture { + if trace_dir.is_some() { + //Error: Tracing isn't supported on the Web target + } let mut mapped_desc = web_sys::GpuDeviceDescriptor::new(); // TODO: label, extensions let mut mapped_limits = web_sys::GpuLimits::new(); diff --git a/src/lib.rs b/src/lib.rs index af6a7cecb..954a44cc9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,10 +16,10 @@ pub use wgt::{ CompareFunction, CullMode, DepthStencilStateDescriptor, DeviceDescriptor, DynamicOffset, Extensions, Extent3d, FilterMode, FrontFace, IndexFormat, InputStepMode, Limits, LoadOp, Origin3d, PowerPreference, PresentMode, PrimitiveTopology, RasterizationStateDescriptor, - SamplerDescriptor, ShaderLocation, ShaderStage, StencilOperation, StencilStateFaceDescriptor, - StoreOp, SwapChainDescriptor, TextureAspect, TextureComponentType, TextureDimension, - TextureFormat, TextureUsage, TextureViewDescriptor, TextureViewDimension, - VertexAttributeDescriptor, VertexFormat, BIND_BUFFER_ALIGNMENT, MAX_BIND_GROUPS, + ShaderLocation, ShaderStage, StencilOperation, StencilStateFaceDescriptor, StoreOp, + SwapChainDescriptor, TextureAspect, TextureComponentType, TextureDimension, TextureFormat, + TextureUsage, TextureViewDimension, VertexAttributeDescriptor, VertexFormat, + BIND_BUFFER_ALIGNMENT, MAX_BIND_GROUPS, }; use backend::Context as C; @@ -117,9 +117,9 @@ trait Context: Sized { type MapWriteFuture: Future>; fn init() -> Self; - fn instance_create_surface( + fn instance_create_surface( &self, - window: &W, + handle: raw_window_handle::RawWindowHandle, ) -> Self::SurfaceId; fn instance_request_adapter( &self, @@ -130,6 +130,7 @@ trait Context: Sized { &self, adapter: &Self::AdapterId, desc: &DeviceDescriptor, + trace_dir: Option<&std::path::Path>, ) -> Self::RequestDeviceFuture; fn device_create_swap_chain( @@ -780,18 +781,7 @@ pub struct RenderPassDescriptor<'a, 'b> { } /// A description of a buffer. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct BufferDescriptor<'a> { - /// An optional label to apply to the buffer. - /// This can be useful for debugging and performance analysis. - pub label: Option<&'a str>, - - /// The size of the buffer (in bytes). - pub size: BufferAddress, - - /// All possible ways the buffer can be used. - pub usage: BufferUsage, -} +pub type BufferDescriptor<'a> = wgt::BufferDescriptor>; /// A description of a command encoder. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] @@ -802,30 +792,13 @@ pub struct CommandEncoderDescriptor<'a> { } /// A description of a texture. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct TextureDescriptor<'a> { - /// An optional label to apply to the texture. - /// This can be useful for debugging and performance analysis. - pub label: Option<&'a str>, - - /// The size of the texture. - pub size: Extent3d, +pub type TextureDescriptor<'a> = wgt::TextureDescriptor>; - /// The mip level count. - pub mip_level_count: u32, - - /// The sample count. - pub sample_count: u32, +/// A description of a texture view. +pub type TextureViewDescriptor<'a> = wgt::TextureViewDescriptor>; - /// The texture dimension. - pub dimension: TextureDimension, - - /// The texture format. - pub format: TextureFormat, - - /// All possible ways the texture can be used. - pub usage: TextureUsage, -} +/// A description of a sampler. +pub type SamplerDescriptor<'a> = wgt::SamplerDescriptor>; /// A swap chain image that can be rendered to. pub struct SwapChainOutput { @@ -910,7 +883,9 @@ impl Instance { pub fn enumerate_adapters(&self, backends: wgt::BackendBit) -> impl Iterator { let context = Arc::clone(&self.context); self.context - .enumerate_adapters(wgc::instance::AdapterInputs::Mask(backends, || PhantomData)) + .enumerate_adapters(wgc::instance::AdapterInputs::Mask(backends, |_| { + PhantomData + })) .into_iter() .map(move |id| crate::Adapter { id, @@ -924,7 +899,7 @@ impl Instance { window: &W, ) -> Surface { Surface { - id: self.context.instance_create_surface(window), + id: Context::instance_create_surface(&*self.context, window.raw_window_handle()), } } @@ -983,9 +958,10 @@ impl Adapter { pub fn request_device( &self, desc: &DeviceDescriptor, + trace_path: Option<&std::path::Path>, ) -> impl Future> { let context = Arc::clone(&self.context); - Context::adapter_request_device(&*self.context, &self.id, desc).map(|result| { + Context::adapter_request_device(&*self.context, &self.id, desc, trace_path).map(|result| { result.map(|(device_id, queue_id)| { ( Device {