diff --git a/.travis.yml b/.travis.yml index 6157b297b..5158a9f22 100644 --- a/.travis.yml +++ b/.travis.yml @@ -58,7 +58,7 @@ before_install: script: - cargo test # TODO: enable GL backend - #- (cd wgpu-native && cargo check --features local,glutin) + - (cd wgpu-native && cargo check --features local) - if [[ $TRAVIS_OS_NAME == "osx" ]]; then (cd wgpu-native && cargo check --features gfx-backend-vulkan); fi - if [[ $TRAVIS_OS_NAME == "linux" ]]; then cargo check --release; fi - if [[ $TRAVIS_RUST_VERSION == "nightly" ]]; then cargo +nightly install cbindgen; fi diff --git a/Makefile b/Makefile index 9830795cc..d139791ce 100644 --- a/Makefile +++ b/Makefile @@ -44,7 +44,7 @@ clear: $(CLEAN_FFI_DIR) lib-native: Cargo.lock wgpu-native/Cargo.toml $(WILDCARD_WGPU_NATIVE) - cargo build --manifest-path wgpu-native/Cargo.toml + cargo build --manifest-path wgpu-native/Cargo.toml --features local lib-remote: Cargo.lock wgpu-remote/Cargo.toml $(WILDCARD_WGPU_NATIVE_AND_REMOTE) cargo build --manifest-path wgpu-remote/Cargo.toml diff --git a/ffi/wgpu.h b/ffi/wgpu.h index b4935ef46..af7a47175 100644 --- a/ffi/wgpu.h +++ b/ffi/wgpu.h @@ -665,71 +665,97 @@ typedef struct { uint32_t array_layer_count; } WGPUTextureViewDescriptor; -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUDeviceId wgpu_adapter_request_device(WGPUAdapterId adapter_id, const WGPUDeviceDescriptor *desc); #endif +#if defined(WGPU_LOCAL) void wgpu_bind_group_destroy(WGPUBindGroupId bind_group_id); +#endif +#if defined(WGPU_LOCAL) void wgpu_buffer_destroy(WGPUBufferId buffer_id); +#endif +#if defined(WGPU_LOCAL) void wgpu_buffer_map_read_async(WGPUBufferId buffer_id, WGPUBufferAddress start, WGPUBufferAddress size, WGPUBufferMapReadCallback callback, uint8_t *userdata); +#endif +#if defined(WGPU_LOCAL) void wgpu_buffer_map_write_async(WGPUBufferId buffer_id, WGPUBufferAddress start, WGPUBufferAddress size, WGPUBufferMapWriteCallback callback, uint8_t *userdata); +#endif +#if defined(WGPU_LOCAL) void wgpu_buffer_unmap(WGPUBufferId buffer_id); +#endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUComputePassId wgpu_command_encoder_begin_compute_pass(WGPUCommandEncoderId encoder_id, const WGPUComputePassDescriptor *desc); #endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPURenderPassId wgpu_command_encoder_begin_render_pass(WGPUCommandEncoderId encoder_id, const WGPURenderPassDescriptor *desc); #endif +#if defined(WGPU_LOCAL) void wgpu_command_encoder_copy_buffer_to_buffer(WGPUCommandEncoderId command_encoder_id, WGPUBufferId source, WGPUBufferAddress source_offset, WGPUBufferId destination, WGPUBufferAddress destination_offset, WGPUBufferAddress size); +#endif +#if defined(WGPU_LOCAL) void wgpu_command_encoder_copy_buffer_to_texture(WGPUCommandEncoderId command_encoder_id, const WGPUBufferCopyView *source, const WGPUTextureCopyView *destination, WGPUExtent3d copy_size); +#endif +#if defined(WGPU_LOCAL) void wgpu_command_encoder_copy_texture_to_buffer(WGPUCommandEncoderId command_encoder_id, const WGPUTextureCopyView *source, const WGPUBufferCopyView *destination, WGPUExtent3d copy_size); +#endif +#if defined(WGPU_LOCAL) void wgpu_command_encoder_copy_texture_to_texture(WGPUCommandEncoderId command_encoder_id, const WGPUTextureCopyView *source, const WGPUTextureCopyView *destination, WGPUExtent3d copy_size); +#endif +#if defined(WGPU_LOCAL) WGPUCommandBufferId wgpu_command_encoder_finish(WGPUCommandEncoderId encoder_id, const WGPUCommandBufferDescriptor *desc); +#endif +#if defined(WGPU_LOCAL) void wgpu_compute_pass_dispatch(WGPUComputePassId pass_id, uint32_t x, uint32_t y, uint32_t z); +#endif +#if defined(WGPU_LOCAL) void wgpu_compute_pass_dispatch_indirect(WGPUComputePassId pass_id, WGPUBufferId indirect_buffer_id, WGPUBufferAddress indirect_offset); +#endif +#if defined(WGPU_LOCAL) void wgpu_compute_pass_end_pass(WGPUComputePassId pass_id); +#endif void wgpu_compute_pass_insert_debug_marker(WGPUComputePassId _pass_id, WGPURawString _label); @@ -737,160 +763,205 @@ void wgpu_compute_pass_pop_debug_group(WGPUComputePassId _pass_id); void wgpu_compute_pass_push_debug_group(WGPUComputePassId _pass_id, WGPURawString _label); +#if defined(WGPU_LOCAL) void wgpu_compute_pass_set_bind_group(WGPUComputePassId pass_id, uint32_t index, WGPUBindGroupId bind_group_id, const WGPUBufferAddress *offsets, uintptr_t offsets_length); +#endif +#if defined(WGPU_LOCAL) void wgpu_compute_pass_set_pipeline(WGPUComputePassId pass_id, WGPUComputePipelineId pipeline_id); +#endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUSurfaceId wgpu_create_surface_from_metal_layer(void *layer); #endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUSurfaceId wgpu_create_surface_from_windows_hwnd(void *_hinstance, void *hwnd); #endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUSurfaceId wgpu_create_surface_from_xlib(const void **display, uint64_t window); #endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUBindGroupId wgpu_device_create_bind_group(WGPUDeviceId device_id, const WGPUBindGroupDescriptor *desc); #endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUBindGroupLayoutId wgpu_device_create_bind_group_layout(WGPUDeviceId device_id, const WGPUBindGroupLayoutDescriptor *desc); #endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUBufferId wgpu_device_create_buffer(WGPUDeviceId device_id, const WGPUBufferDescriptor *desc); #endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUBufferId wgpu_device_create_buffer_mapped(WGPUDeviceId device_id, const WGPUBufferDescriptor *desc, uint8_t **mapped_ptr_out); #endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUCommandEncoderId wgpu_device_create_command_encoder(WGPUDeviceId device_id, const WGPUCommandEncoderDescriptor *desc); #endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUComputePipelineId wgpu_device_create_compute_pipeline(WGPUDeviceId device_id, const WGPUComputePipelineDescriptor *desc); #endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUPipelineLayoutId wgpu_device_create_pipeline_layout(WGPUDeviceId device_id, const WGPUPipelineLayoutDescriptor *desc); #endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPURenderPipelineId wgpu_device_create_render_pipeline(WGPUDeviceId device_id, const WGPURenderPipelineDescriptor *desc); #endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUSamplerId wgpu_device_create_sampler(WGPUDeviceId device_id, const WGPUSamplerDescriptor *desc); #endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUShaderModuleId wgpu_device_create_shader_module(WGPUDeviceId device_id, const WGPUShaderModuleDescriptor *desc); #endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUSwapChainId wgpu_device_create_swap_chain(WGPUDeviceId device_id, WGPUSurfaceId surface_id, const WGPUSwapChainDescriptor *desc); #endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUTextureId wgpu_device_create_texture(WGPUDeviceId device_id, const WGPUTextureDescriptor *desc); #endif +#if defined(WGPU_LOCAL) void wgpu_device_destroy(WGPUDeviceId device_id); +#endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) void wgpu_device_get_limits(WGPUDeviceId _device_id, WGPULimits *limits); #endif +#if defined(WGPU_LOCAL) WGPUQueueId wgpu_device_get_queue(WGPUDeviceId device_id); +#endif +#if defined(WGPU_LOCAL) void wgpu_device_poll(WGPUDeviceId device_id, bool force_wait); +#endif +#if defined(WGPU_LOCAL) void wgpu_queue_submit(WGPUQueueId queue_id, const WGPUCommandBufferId *command_buffers, uintptr_t command_buffers_length); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_draw(WGPURenderPassId pass_id, uint32_t vertex_count, uint32_t instance_count, uint32_t first_vertex, uint32_t first_instance); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_draw_indexed(WGPURenderPassId pass_id, uint32_t index_count, uint32_t instance_count, uint32_t first_index, int32_t base_vertex, uint32_t first_instance); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_draw_indexed_indirect(WGPURenderPassId pass_id, WGPUBufferId indirect_buffer_id, WGPUBufferAddress indirect_offset); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_draw_indirect(WGPURenderPassId pass_id, WGPUBufferId indirect_buffer_id, WGPUBufferAddress indirect_offset); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_end_pass(WGPURenderPassId pass_id); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_execute_bundles(WGPURenderPassId _pass_id, const WGPURenderBundleId *_bundles, uintptr_t _bundles_length); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_insert_debug_marker(WGPURenderPassId _pass_id, WGPURawString _label); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_pop_debug_group(WGPURenderPassId _pass_id); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_push_debug_group(WGPURenderPassId _pass_id, WGPURawString _label); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_set_bind_group(WGPURenderPassId pass_id, uint32_t index, WGPUBindGroupId bind_group_id, const WGPUBufferAddress *offsets, uintptr_t offsets_length); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_set_blend_color(WGPURenderPassId pass_id, const WGPUColor *color); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_set_index_buffer(WGPURenderPassId pass_id, WGPUBufferId buffer_id, WGPUBufferAddress offset); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_set_pipeline(WGPURenderPassId pass_id, WGPURenderPipelineId pipeline_id); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_set_scissor_rect(WGPURenderPassId pass_id, uint32_t x, uint32_t y, uint32_t w, uint32_t h); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_set_stencil_reference(WGPURenderPassId pass_id, uint32_t value); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_set_vertex_buffers(WGPURenderPassId pass_id, uint32_t start_slot, const WGPUBufferId *buffers, const WGPUBufferAddress *offsets, uintptr_t length); +#endif +#if defined(WGPU_LOCAL) void wgpu_render_pass_set_viewport(WGPURenderPassId pass_id, float x, float y, @@ -898,24 +969,33 @@ void wgpu_render_pass_set_viewport(WGPURenderPassId pass_id, float h, float min_depth, float max_depth); +#endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUAdapterId wgpu_request_adapter(const WGPURequestAdapterOptions *desc); #endif +#if defined(WGPU_LOCAL) void wgpu_sampler_destroy(WGPUSamplerId sampler_id); +#endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUSwapChainOutput wgpu_swap_chain_get_next_texture(WGPUSwapChainId swap_chain_id); #endif +#if defined(WGPU_LOCAL) void wgpu_swap_chain_present(WGPUSwapChainId swap_chain_id); +#endif -#if !defined(WGPU_REMOTE) +#if defined(WGPU_LOCAL) WGPUTextureViewId wgpu_texture_create_view(WGPUTextureId texture_id, const WGPUTextureViewDescriptor *desc); #endif +#if defined(WGPU_LOCAL) void wgpu_texture_destroy(WGPUTextureId texture_id); +#endif +#if defined(WGPU_LOCAL) void wgpu_texture_view_destroy(WGPUTextureViewId texture_view_id); +#endif diff --git a/wgpu-native/Cargo.toml b/wgpu-native/Cargo.toml index 0b62ef017..357d97d10 100644 --- a/wgpu-native/Cargo.toml +++ b/wgpu-native/Cargo.toml @@ -17,7 +17,7 @@ crate-type = ["lib", "cdylib", "staticlib"] [features] default = [] -remote = ["serde"] +local = ["lazy_static"] metal-auto-capture = ["gfx-backend-metal/auto-capture"] #NOTE: glutin feature is not stable, use at your own risk #glutin = ["gfx-backend-gl/glutin"] @@ -26,7 +26,7 @@ metal-auto-capture = ["gfx-backend-metal/auto-capture"] arrayvec = "0.5" bitflags = "1.0" copyless = "0.1" -lazy_static = "1.1.0" +lazy_static = { version = "1.1.0", optional = true } log = "0.4" hal = { package = "gfx-hal", git = "https://github.com/gfx-rs/gfx", rev = "3d5db15661127c8cad8d85522a68ec36c82f6e69" } gfx-backend-empty = { git = "https://github.com/gfx-rs/gfx", rev = "3d5db15661127c8cad8d85522a68ec36c82f6e69" } diff --git a/wgpu-native/cbindgen.toml b/wgpu-native/cbindgen.toml index 9a538ab74..9e296d5de 100644 --- a/wgpu-native/cbindgen.toml +++ b/wgpu-native/cbindgen.toml @@ -15,6 +15,9 @@ exclude = ["BufferMapResult"] [parse] parse_deps = false +[parse.expand] +features = ["local"] + [fn] [struct] diff --git a/wgpu-native/src/command/allocator.rs b/wgpu-native/src/command/allocator.rs index 555395c46..07ce1bfe9 100644 --- a/wgpu-native/src/command/allocator.rs +++ b/wgpu-native/src/command/allocator.rs @@ -3,10 +3,17 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use super::CommandBuffer; -use crate::{hub::GfxBackend, track::TrackerSet, DeviceId, Features, LifeGuard, Stored, SubmissionIndex}; +use crate::{ + hub::GfxBackend, + track::TrackerSet, + DeviceId, + Features, + LifeGuard, + Stored, + SubmissionIndex, +}; use hal::{command::CommandBuffer as _, device::Device as _, pool::CommandPool as _}; -use log::trace; use parking_lot::Mutex; use std::{collections::HashMap, sync::atomic::Ordering, thread}; @@ -127,7 +134,7 @@ impl CommandAllocator { .load(Ordering::Acquire); if index <= last_done { let cmd_buf = inner.pending.swap_remove(i); - trace!( + log::trace!( "recycling comb submitted in {} when {} is done", index, last_done diff --git a/wgpu-native/src/command/bind.rs b/wgpu-native/src/command/bind.rs index 3e7eff7cb..e6e04365b 100644 --- a/wgpu-native/src/command/bind.rs +++ b/wgpu-native/src/command/bind.rs @@ -12,7 +12,6 @@ use crate::{ Stored, }; -use log::trace; use smallvec::{smallvec, SmallVec}; use std::convert::identity; @@ -36,9 +35,7 @@ pub enum LayoutChange<'a> { #[derive(Debug)] pub enum Provision { Unchanged, - Changed { - was_compatible: bool, - }, + Changed { was_compatible: bool }, } struct TakeSome { @@ -95,9 +92,7 @@ impl BindGroupEntry { self.dynamic_offsets.clear(); self.dynamic_offsets.extend_from_slice(offsets); - Provision::Changed { - was_compatible, - } + Provision::Changed { was_compatible } } pub fn expect_layout(&mut self, bind_group_layout_id: BindGroupLayoutId) -> LayoutChange { @@ -108,8 +103,9 @@ impl BindGroupEntry { Some(BindGroupPair { layout_id, ref group_id, - }) if layout_id == bind_group_layout_id => - LayoutChange::Match(group_id.value, &self.dynamic_offsets), + }) if layout_id == bind_group_layout_id => { + LayoutChange::Match(group_id.value, &self.dynamic_offsets) + } Some(_) | None => LayoutChange::Mismatch, } } else { @@ -148,7 +144,7 @@ impl Binder { pub(crate) fn new(max_bind_groups: u32) -> Self { Self { pipeline_layout_id: None, - entries: smallvec![Default::default(); max_bind_groups as usize] + entries: smallvec![Default::default(); max_bind_groups as usize], } } @@ -174,7 +170,7 @@ impl Binder { impl 'a + Iterator, impl 'a + Iterator, )> { - trace!("\tBinding [{}] = group {:?}", index, bind_group_id); + log::trace!("\tBinding [{}] = group {:?}", index, bind_group_id); debug_assert_eq!(B::VARIANT, bind_group_id.backend()); match self.entries[index].provide(bind_group_id, bind_group, offsets) { @@ -182,9 +178,12 @@ impl Binder { Provision::Changed { was_compatible, .. } => { let compatible_count = self.compatible_count(); if index < compatible_count { - let end = compatible_count - .min(if was_compatible { index + 1 } else { self.entries.len() }); - trace!("\t\tbinding up to {}", end); + let end = compatible_count.min(if was_compatible { + index + 1 + } else { + self.entries.len() + }); + log::trace!("\t\tbinding up to {}", end); Some(( self.pipeline_layout_id?, TakeSome { @@ -197,7 +196,7 @@ impl Binder { .flat_map(|entry| entry.dynamic_offsets.as_slice()), )) } else { - trace!("\t\tskipping above compatible {}", compatible_count); + log::trace!("\t\tskipping above compatible {}", compatible_count); None } } diff --git a/wgpu-native/src/command/compute.rs b/wgpu-native/src/command/compute.rs index 87556cc5e..5278cc299 100644 --- a/wgpu-native/src/command/compute.rs +++ b/wgpu-native/src/command/compute.rs @@ -5,8 +5,7 @@ use crate::{ command::bind::{Binder, LayoutChange}, device::all_buffer_stages, - gfx_select, - hub::{GfxBackend, Token}, + hub::{GfxBackend, Global, Token}, track::{Stitch, TrackerSet}, BindGroupId, BufferAddress, @@ -20,11 +19,14 @@ use crate::{ Stored, BIND_BUFFER_ALIGNMENT, }; +#[cfg(feature = "local")] +use crate::{gfx_select, hub::GLOBAL}; use hal::{self, command::CommandBuffer as _}; -use log::trace; -use std::{iter, slice}; +use std::iter; +#[cfg(feature = "local")] +use std::slice; #[derive(Debug)] pub struct ComputePass { @@ -52,9 +54,9 @@ impl ComputePass { // Common routines between render/compute -pub fn compute_pass_end_pass(pass_id: ComputePassId) { +pub fn compute_pass_end_pass(global: &Global, pass_id: ComputePassId) { let mut token = Token::root(); - let hub = B::hub(); + let hub = B::hub(global); let (mut cmb_guard, mut token) = hub.command_buffers.write(&mut token); let (pass, _) = hub.compute_passes.unregister(pass_id, &mut token); let cmb = &mut cmb_guard[pass.cmb_id.value]; @@ -65,18 +67,20 @@ pub fn compute_pass_end_pass(pass_id: ComputePassId) { cmb.raw.push(pass.raw); } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_compute_pass_end_pass(pass_id: ComputePassId) { - gfx_select!(pass_id => compute_pass_end_pass(pass_id)) + gfx_select!(pass_id => compute_pass_end_pass(&*GLOBAL, pass_id)) } pub fn compute_pass_set_bind_group( + global: &Global, pass_id: ComputePassId, index: u32, bind_group_id: BindGroupId, offsets: &[BufferAddress], ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(&mut token); @@ -109,7 +113,7 @@ pub fn compute_pass_set_bind_group( let (buffer_guard, mut token) = hub.buffers.read(&mut token); let (texture_guard, _) = hub.textures.read(&mut token); - trace!( + log::trace!( "Encoding barriers on binding of {:?} in pass {:?}", bind_group_id, pass_id @@ -143,6 +147,7 @@ pub fn compute_pass_set_bind_group( }; } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_compute_pass_set_bind_group( pass_id: ComputePassId, @@ -156,7 +161,7 @@ pub extern "C" fn wgpu_compute_pass_set_bind_group( } else { &[] }; - gfx_select!(pass_id => compute_pass_set_bind_group(pass_id, index, bind_group_id, offsets)) + gfx_select!(pass_id => compute_pass_set_bind_group(&*GLOBAL, pass_id, index, bind_group_id, offsets)) } #[no_mangle] @@ -179,8 +184,14 @@ pub extern "C" fn wgpu_compute_pass_insert_debug_marker( // Compute-specific routines -pub fn compute_pass_dispatch(pass_id: ComputePassId, x: u32, y: u32, z: u32) { - let hub = B::hub(); +pub fn compute_pass_dispatch( + global: &Global, + pass_id: ComputePassId, + x: u32, + y: u32, + z: u32, +) { + let hub = B::hub(global); let mut token = Token::root(); let (mut pass_guard, _) = hub.compute_passes.write(&mut token); unsafe { @@ -188,17 +199,19 @@ pub fn compute_pass_dispatch(pass_id: ComputePassId, x: u32, y: u } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_compute_pass_dispatch(pass_id: ComputePassId, x: u32, y: u32, z: u32) { - gfx_select!(pass_id => compute_pass_dispatch(pass_id, x, y, z)) + gfx_select!(pass_id => compute_pass_dispatch(&*GLOBAL, pass_id, x, y, z)) } pub fn compute_pass_dispatch_indirect( + global: &Global, pass_id: ComputePassId, indirect_buffer_id: BufferId, indirect_offset: BufferAddress, ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (buffer_guard, _) = hub.buffers.read(&mut token); let (mut pass_guard, _) = hub.compute_passes.write(&mut token); @@ -229,20 +242,22 @@ pub fn compute_pass_dispatch_indirect( } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_compute_pass_dispatch_indirect( pass_id: ComputePassId, indirect_buffer_id: BufferId, indirect_offset: BufferAddress, ) { - gfx_select!(pass_id => compute_pass_dispatch_indirect(pass_id, indirect_buffer_id, indirect_offset)) + gfx_select!(pass_id => compute_pass_dispatch_indirect(&*GLOBAL, pass_id, indirect_buffer_id, indirect_offset)) } pub fn compute_pass_set_pipeline( + global: &Global, pass_id: ComputePassId, pipeline_id: ComputePipelineId, ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(&mut token); let (bind_group_guard, mut token) = hub.bind_groups.read(&mut token); @@ -282,8 +297,7 @@ pub fn compute_pass_set_pipeline( ); } } - LayoutChange::Match(..) | - LayoutChange::Unchanged => {} + LayoutChange::Match(..) | LayoutChange::Unchanged => {} LayoutChange::Mismatch => { is_compatible = false; } @@ -292,10 +306,11 @@ pub fn compute_pass_set_pipeline( } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_compute_pass_set_pipeline( pass_id: ComputePassId, pipeline_id: ComputePipelineId, ) { - gfx_select!(pass_id => compute_pass_set_pipeline(pass_id, pipeline_id)) + gfx_select!(pass_id => compute_pass_set_pipeline(&*GLOBAL, pass_id, pipeline_id)) } diff --git a/wgpu-native/src/command/mod.rs b/wgpu-native/src/command/mod.rs index 8e5cd17a3..4313ffe50 100644 --- a/wgpu-native/src/command/mod.rs +++ b/wgpu-native/src/command/mod.rs @@ -22,8 +22,7 @@ use crate::{ RenderPassContext, RenderPassKey, }, - gfx_select, - hub::{GfxBackend, Storage, Token}, + hub::{GfxBackend, Global, Storage, Token}, id::{Input, Output}, resource::TextureViewInner, track::{Stitch, TrackerSet}, @@ -43,22 +42,15 @@ use crate::{ TextureUsage, TextureViewId, }; +#[cfg(feature = "local")] +use crate::{gfx_select, hub::GLOBAL}; use arrayvec::ArrayVec; use hal::{adapter::PhysicalDevice as _, command::CommandBuffer as _, device::Device as _}; -use log::trace; -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] use std::marker::PhantomData; -use std::{ - borrow::Borrow, - collections::hash_map::Entry, - iter, - mem, - ptr, - slice, - thread::ThreadId, -}; +use std::{borrow::Borrow, collections::hash_map::Entry, iter, mem, ptr, slice, thread::ThreadId}; pub struct RenderBundle { @@ -136,7 +128,7 @@ impl CommandBuffer { buffer_guard: &Storage, BufferId>, texture_guard: &Storage, TextureId>, ) { - trace!("\tstitch {:?}", stitch); + log::trace!("\tstitch {:?}", stitch); debug_assert_eq!(B::VARIANT, base.backend()); debug_assert_eq!(B::VARIANT, head.backend()); @@ -144,7 +136,7 @@ impl CommandBuffer { .buffers .merge_replace(&head.buffers, stitch) .map(|pending| { - trace!("\tbuffer -> {:?}", pending); + log::trace!("\tbuffer -> {:?}", pending); hal::memory::Barrier::Buffer { states: pending.to_states(), target: &buffer_guard[pending.id].raw, @@ -156,7 +148,7 @@ impl CommandBuffer { .textures .merge_replace(&head.textures, stitch) .map(|pending| { - trace!("\ttexture -> {:?}", pending); + log::trace!("\ttexture -> {:?}", pending); hal::memory::Barrier::Image { states: pending.to_states(), target: &texture_guard[pending.id].raw, @@ -194,10 +186,11 @@ pub struct CommandBufferDescriptor { } pub fn command_encoder_finish( + global: &Global, encoder_id: CommandEncoderId, _desc: &CommandBufferDescriptor, ) -> CommandBufferId { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); //TODO: actually close the last recorded command buffer let (mut comb_guard, _) = hub.command_buffers.write(&mut token); @@ -211,21 +204,23 @@ pub fn command_encoder_finish( encoder_id } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_command_encoder_finish( encoder_id: CommandEncoderId, desc: Option<&CommandBufferDescriptor>, ) -> CommandBufferId { let desc = &desc.cloned().unwrap_or_default(); - gfx_select!(encoder_id => command_encoder_finish(encoder_id, desc)) + gfx_select!(encoder_id => command_encoder_finish(&*GLOBAL, encoder_id, desc)) } pub fn command_encoder_begin_render_pass( + global: &Global, encoder_id: CommandEncoderId, desc: &RenderPassDescriptor, id_in: Input, ) -> Output { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (adapter_guard, mut token) = hub.adapters.read(&mut token); @@ -270,7 +265,7 @@ pub fn command_encoder_begin_render_pass( "Attachment sample_count must be supported by physical device limits" ); - trace!( + log::trace!( "Encoding render pass begin in command buffer {:?}", encoder_id ); @@ -289,17 +284,15 @@ pub fn command_encoder_begin_render_pass( } let texture_id = match view.inner { TextureViewInner::Native { ref source_id, .. } => source_id.value, - TextureViewInner::SwapChain {..} => - panic!("Unexpected depth/stencil use of swapchain image!"), + TextureViewInner::SwapChain { .. } => { + panic!("Unexpected depth/stencil use of swapchain image!") + } }; let texture = &texture_guard[texture_id]; assert!(texture.usage.contains(TextureUsage::OUTPUT_ATTACHMENT)); - let old_layout = match trackers - .textures - .query(texture_id, view.range.clone()) - { + let old_layout = match trackers.textures.query(texture_id, view.range.clone()) { Some(usage) => { conv::map_texture_state( usage, @@ -318,7 +311,7 @@ pub fn command_encoder_begin_render_pass( ); barriers.extend(pending.map(|pending| { - trace!("\tdepth-stencil {:?}", pending); + log::trace!("\tdepth-stencil {:?}", pending); hal::memory::Barrier::Image { states: pending.to_states(), target: &texture.raw, @@ -352,40 +345,42 @@ pub fn command_encoder_begin_render_pass( view.samples, sample_count, "All attachments must have the same sample_count" ); - let first_use = trackers.views - .init(at.attachment, &view.life_guard.ref_count, (), ()); + let first_use = + trackers + .views + .init(at.attachment, &view.life_guard.ref_count, (), ()); let layouts = match view.inner { TextureViewInner::Native { ref source_id, .. } => { let texture = &texture_guard[source_id.value]; assert!(texture.usage.contains(TextureUsage::OUTPUT_ATTACHMENT)); - let old_layout = match trackers - .textures - .query(source_id.value, view.range.clone()) - { - Some(usage) => conv::map_texture_state(usage, hal::format::Aspects::COLOR).1, - None => { - // Required sub-resources have inconsistent states, we need to - // issue individual barriers instead of relying on the render pass. - let pending = trackers.textures.change_replace( - source_id.value, - &texture.life_guard.ref_count, - view.range.clone(), - TextureUsage::OUTPUT_ATTACHMENT, - ); - barriers.extend(pending.map(|pending| { - trace!("\tcolor {:?}", pending); - hal::memory::Barrier::Image { - states: pending.to_states(), - target: &texture.raw, - families: None, - range: pending.selector, - } - })); - hal::image::Layout::ColorAttachmentOptimal - } - }; + let old_layout = + match trackers.textures.query(source_id.value, view.range.clone()) { + Some(usage) => { + conv::map_texture_state(usage, hal::format::Aspects::COLOR).1 + } + None => { + // Required sub-resources have inconsistent states, we need to + // issue individual barriers instead of relying on the render pass. + let pending = trackers.textures.change_replace( + source_id.value, + &texture.life_guard.ref_count, + view.range.clone(), + TextureUsage::OUTPUT_ATTACHMENT, + ); + barriers.extend(pending.map(|pending| { + log::trace!("\tcolor {:?}", pending); + hal::memory::Barrier::Image { + states: pending.to_states(), + target: &texture.raw, + families: None, + range: pending.selector, + } + })); + hal::image::Layout::ColorAttachmentOptimal + } + }; old_layout .. hal::image::Layout::ColorAttachmentOptimal } TextureViewInner::SwapChain { .. } => { @@ -400,7 +395,11 @@ pub fn command_encoder_begin_render_pass( } let end = hal::image::Layout::Present; - let start = if first_use { hal::image::Layout::Undefined } else { end }; + let start = if first_use { + hal::image::Layout::Undefined + } else { + end + }; start .. end } }; @@ -424,40 +423,42 @@ pub fn command_encoder_begin_render_pass( view.samples, 1, "All resolve_targets must have a sample_count of 1" ); - let first_use = trackers.views - .init(resolve_target, &view.life_guard.ref_count, (), ()); + let first_use = + trackers + .views + .init(resolve_target, &view.life_guard.ref_count, (), ()); let layouts = match view.inner { TextureViewInner::Native { ref source_id, .. } => { let texture = &texture_guard[source_id.value]; assert!(texture.usage.contains(TextureUsage::OUTPUT_ATTACHMENT)); - let old_layout = match trackers - .textures - .query(source_id.value, view.range.clone()) - { - Some(usage) => conv::map_texture_state(usage, hal::format::Aspects::COLOR).1, - None => { - // Required sub-resources have inconsistent states, we need to - // issue individual barriers instead of relying on the render pass. - let pending = trackers.textures.change_replace( - source_id.value, - &texture.life_guard.ref_count, - view.range.clone(), - TextureUsage::OUTPUT_ATTACHMENT, - ); - barriers.extend(pending.map(|pending| { - trace!("\tresolve {:?}", pending); - hal::memory::Barrier::Image { - states: pending.to_states(), - target: &texture.raw, - families: None, - range: pending.selector, - } - })); - hal::image::Layout::ColorAttachmentOptimal - } - }; + let old_layout = + match trackers.textures.query(source_id.value, view.range.clone()) { + Some(usage) => { + conv::map_texture_state(usage, hal::format::Aspects::COLOR).1 + } + None => { + // Required sub-resources have inconsistent states, we need to + // issue individual barriers instead of relying on the render pass. + let pending = trackers.textures.change_replace( + source_id.value, + &texture.life_guard.ref_count, + view.range.clone(), + TextureUsage::OUTPUT_ATTACHMENT, + ); + barriers.extend(pending.map(|pending| { + log::trace!("\tresolve {:?}", pending); + hal::memory::Barrier::Image { + states: pending.to_states(), + target: &texture.raw, + families: None, + range: pending.selector, + } + })); + hal::image::Layout::ColorAttachmentOptimal + } + }; old_layout .. hal::image::Layout::ColorAttachmentOptimal } TextureViewInner::SwapChain { .. } => { @@ -472,7 +473,11 @@ pub fn command_encoder_begin_render_pass( } let end = hal::image::Layout::Present; - let start = if first_use { hal::image::Layout::Undefined } else { end }; + let start = if first_use { + hal::image::Layout::Undefined + } else { + end + }; start .. end } }; @@ -601,12 +606,16 @@ pub fn command_encoder_begin_render_pass( let fb = { let attachments = e.key().all().map(|&id| match view_guard[id].inner { TextureViewInner::Native { ref raw, .. } => raw, - TextureViewInner::SwapChain { ref image, .. } => Borrow::borrow(image), + TextureViewInner::SwapChain { ref image, .. } => { + Borrow::borrow(image) + } }); unsafe { - device - .raw - .create_framebuffer(&render_pass, attachments, extent.unwrap()) + device.raw.create_framebuffer( + &render_pass, + attachments, + extent.unwrap(), + ) } .unwrap() }; @@ -652,9 +661,7 @@ pub fn command_encoder_begin_render_pass( uint32: conv::map_color_u32(&at.clear_color), }, }; - Some(hal::command::ClearValue { - color: value, - }) + Some(hal::command::ClearValue { color: value }) } } }) @@ -718,21 +725,22 @@ pub fn command_encoder_begin_render_pass( hub.render_passes.register_identity(id_in, pass, &mut token) } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_command_encoder_begin_render_pass( encoder_id: CommandEncoderId, desc: &RenderPassDescriptor, ) -> RenderPassId { - gfx_select!(encoder_id => command_encoder_begin_render_pass(encoder_id, desc, PhantomData)) + gfx_select!(encoder_id => command_encoder_begin_render_pass(&*GLOBAL, encoder_id, desc, PhantomData)) } pub fn command_encoder_begin_compute_pass( + global: &Global, encoder_id: CommandEncoderId, _desc: &ComputePassDescriptor, id_in: Input, ) -> Output { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (mut cmb_guard, mut token) = hub.command_buffers.write(&mut token); @@ -750,12 +758,12 @@ pub fn command_encoder_begin_compute_pass( .register_identity(id_in, pass, &mut token) } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_command_encoder_begin_compute_pass( encoder_id: CommandEncoderId, desc: Option<&ComputePassDescriptor>, ) -> ComputePassId { let desc = &desc.cloned().unwrap_or_default(); - gfx_select!(encoder_id => command_encoder_begin_compute_pass(encoder_id, desc, PhantomData)) + gfx_select!(encoder_id => command_encoder_begin_compute_pass(&*GLOBAL, encoder_id, desc, PhantomData)) } diff --git a/wgpu-native/src/command/render.rs b/wgpu-native/src/command/render.rs index 35dc72ca3..2c4c8a979 100644 --- a/wgpu-native/src/command/render.rs +++ b/wgpu-native/src/command/render.rs @@ -6,8 +6,7 @@ use crate::{ command::bind::{Binder, LayoutChange}, conv, device::{RenderPassContext, BIND_BUFFER_ALIGNMENT, MAX_VERTEX_BUFFERS}, - gfx_select, - hub::{GfxBackend, Token}, + hub::{GfxBackend, Global, Token}, pipeline::{IndexFormat, InputStepMode, PipelineFlags}, resource::BufferUsage, track::{Stitch, TrackerSet}, @@ -17,17 +16,18 @@ use crate::{ Color, CommandBuffer, CommandBufferId, - RawString, - RenderBundleId, RenderPassId, RenderPipelineId, Stored, }; +#[cfg(feature = "local")] +use crate::{gfx_select, hub::GLOBAL, RawString, RenderBundleId}; use hal::command::CommandBuffer as _; -use log::trace; -use std::{iter, ops::Range, slice}; +#[cfg(feature = "local")] +use std::slice; +use std::{iter, ops::Range}; #[derive(Debug, PartialEq)] enum OptionalState { @@ -181,8 +181,8 @@ impl RenderPass { // Common routines between render/compute -pub fn render_pass_end_pass(pass_id: RenderPassId) { - let hub = B::hub(); +pub fn render_pass_end_pass(global: &Global, pass_id: RenderPassId) { + let hub = B::hub(global); let mut token = Token::root(); let (mut cmb_guard, mut token) = hub.command_buffers.write(&mut token); let (mut pass, mut token) = hub.render_passes.unregister(pass_id, &mut token); @@ -196,7 +196,7 @@ pub fn render_pass_end_pass(pass_id: RenderPassId) { match cmb.raw.last_mut() { Some(last) => { - trace!("Encoding barriers before pass {:?}", pass_id); + log::trace!("Encoding barriers before pass {:?}", pass_id); CommandBuffer::insert_barriers( last, &mut cmb.trackers, @@ -215,18 +215,20 @@ pub fn render_pass_end_pass(pass_id: RenderPassId) { cmb.raw.push(pass.raw); } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_end_pass(pass_id: RenderPassId) { - gfx_select!(pass_id => render_pass_end_pass(pass_id)) + gfx_select!(pass_id => render_pass_end_pass(&*GLOBAL, pass_id)) } pub fn render_pass_set_bind_group( + global: &Global, pass_id: RenderPassId, index: u32, bind_group_id: BindGroupId, offsets: &[BufferAddress], ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(&mut token); let (bind_group_guard, mut token) = hub.bind_groups.read(&mut token); @@ -276,6 +278,7 @@ pub fn render_pass_set_bind_group( }; } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_set_bind_group( pass_id: RenderPassId, @@ -289,19 +292,22 @@ pub extern "C" fn wgpu_render_pass_set_bind_group( } else { &[] }; - gfx_select!(pass_id => render_pass_set_bind_group(pass_id, index, bind_group_id, offsets)) + gfx_select!(pass_id => render_pass_set_bind_group(&*GLOBAL, pass_id, index, bind_group_id, offsets)) } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_push_debug_group(_pass_id: RenderPassId, _label: RawString) { //TODO } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_pop_debug_group(_pass_id: RenderPassId) { //TODO } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_insert_debug_marker(_pass_id: RenderPassId, _label: RawString) { //TODO @@ -310,11 +316,12 @@ pub extern "C" fn wgpu_render_pass_insert_debug_marker(_pass_id: RenderPassId, _ // Render-specific routines pub fn render_pass_set_index_buffer( + global: &Global, pass_id: RenderPassId, buffer_id: BufferId, offset: BufferAddress, ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (mut pass_guard, mut token) = hub.render_passes.write(&mut token); let (buffer_guard, _) = hub.buffers.read(&mut token); @@ -342,22 +349,24 @@ pub fn render_pass_set_index_buffer( } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_set_index_buffer( pass_id: RenderPassId, buffer_id: BufferId, offset: BufferAddress, ) { - gfx_select!(pass_id => render_pass_set_index_buffer(pass_id, buffer_id, offset)) + gfx_select!(pass_id => render_pass_set_index_buffer(&*GLOBAL, pass_id, buffer_id, offset)) } pub fn render_pass_set_vertex_buffers( + global: &Global, pass_id: RenderPassId, start_slot: u32, buffers: &[BufferId], offsets: &[BufferAddress], ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); assert_eq!(buffers.len(), offsets.len()); @@ -391,6 +400,7 @@ pub fn render_pass_set_vertex_buffers( } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_set_vertex_buffers( pass_id: RenderPassId, @@ -401,17 +411,18 @@ pub extern "C" fn wgpu_render_pass_set_vertex_buffers( ) { let buffers = unsafe { slice::from_raw_parts(buffers, length) }; let offsets = unsafe { slice::from_raw_parts(offsets, length) }; - gfx_select!(pass_id => render_pass_set_vertex_buffers(pass_id, start_slot, buffers, offsets)) + gfx_select!(pass_id => render_pass_set_vertex_buffers(&*GLOBAL, pass_id, start_slot, buffers, offsets)) } pub fn render_pass_draw( + global: &Global, pass_id: RenderPassId, vertex_count: u32, instance_count: u32, first_vertex: u32, first_instance: u32, ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (mut pass_guard, _) = hub.render_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; @@ -434,6 +445,7 @@ pub fn render_pass_draw( } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_draw( pass_id: RenderPassId, @@ -442,15 +454,16 @@ pub extern "C" fn wgpu_render_pass_draw( first_vertex: u32, first_instance: u32, ) { - gfx_select!(pass_id => render_pass_draw(pass_id, vertex_count, instance_count, first_vertex, first_instance)) + gfx_select!(pass_id => render_pass_draw(&*GLOBAL, pass_id, vertex_count, instance_count, first_vertex, first_instance)) } pub fn render_pass_draw_indirect( + global: &Global, pass_id: RenderPassId, indirect_buffer_id: BufferId, indirect_offset: BufferAddress, ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (mut pass_guard, _) = hub.render_passes.write(&mut token); let (buffer_guard, _) = hub.buffers.read(&mut token); @@ -474,16 +487,18 @@ pub fn render_pass_draw_indirect( } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_draw_indirect( pass_id: RenderPassId, indirect_buffer_id: BufferId, indirect_offset: BufferAddress, ) { - gfx_select!(pass_id => render_pass_draw_indirect(pass_id, indirect_buffer_id, indirect_offset)) + gfx_select!(pass_id => render_pass_draw_indirect(&*GLOBAL, pass_id, indirect_buffer_id, indirect_offset)) } pub fn render_pass_draw_indexed( + global: &Global, pass_id: RenderPassId, index_count: u32, instance_count: u32, @@ -491,7 +506,7 @@ pub fn render_pass_draw_indexed( base_vertex: i32, first_instance: u32, ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (mut pass_guard, _) = hub.render_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; @@ -516,6 +531,7 @@ pub fn render_pass_draw_indexed( } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_draw_indexed( pass_id: RenderPassId, @@ -525,15 +541,16 @@ pub extern "C" fn wgpu_render_pass_draw_indexed( base_vertex: i32, first_instance: u32, ) { - gfx_select!(pass_id => render_pass_draw_indexed(pass_id, index_count, instance_count, first_index, base_vertex, first_instance)) + gfx_select!(pass_id => render_pass_draw_indexed(&*GLOBAL, pass_id, index_count, instance_count, first_index, base_vertex, first_instance)) } pub fn render_pass_draw_indexed_indirect( + global: &Global, pass_id: RenderPassId, indirect_buffer_id: BufferId, indirect_offset: BufferAddress, ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (mut pass_guard, _) = hub.render_passes.write(&mut token); let (buffer_guard, _) = hub.buffers.read(&mut token); @@ -558,20 +575,22 @@ pub fn render_pass_draw_indexed_indirect( } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_draw_indexed_indirect( pass_id: RenderPassId, indirect_buffer_id: BufferId, indirect_offset: BufferAddress, ) { - gfx_select!(pass_id => render_pass_draw_indexed_indirect(pass_id, indirect_buffer_id, indirect_offset)) + gfx_select!(pass_id => render_pass_draw_indexed_indirect(&*GLOBAL, pass_id, indirect_buffer_id, indirect_offset)) } pub fn render_pass_set_pipeline( + global: &Global, pass_id: RenderPassId, pipeline_id: RenderPipelineId, ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(&mut token); let (bind_group_guard, mut token) = hub.bind_groups.read(&mut token); @@ -625,8 +644,7 @@ pub fn render_pass_set_pipeline( ); } } - LayoutChange::Match(..) | - LayoutChange::Unchanged => {} + LayoutChange::Match(..) | LayoutChange::Unchanged => {} LayoutChange::Mismatch => { is_compatible = false; } @@ -675,16 +693,21 @@ pub fn render_pass_set_pipeline( pass.vertex_state.update_limits(); } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_set_pipeline( pass_id: RenderPassId, pipeline_id: RenderPipelineId, ) { - gfx_select!(pass_id => render_pass_set_pipeline(pass_id, pipeline_id)) + gfx_select!(pass_id => render_pass_set_pipeline(&*GLOBAL, pass_id, pipeline_id)) } -pub fn render_pass_set_blend_color(pass_id: RenderPassId, color: &Color) { - let hub = B::hub(); +pub fn render_pass_set_blend_color( + global: &Global, + pass_id: RenderPassId, + color: &Color, +) { + let hub = B::hub(global); let mut token = Token::root(); let (mut pass_guard, _) = hub.render_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; @@ -696,13 +719,18 @@ pub fn render_pass_set_blend_color(pass_id: RenderPassId, color: } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_set_blend_color(pass_id: RenderPassId, color: &Color) { - gfx_select!(pass_id => render_pass_set_blend_color(pass_id, color)) + gfx_select!(pass_id => render_pass_set_blend_color(&*GLOBAL, pass_id, color)) } -pub fn render_pass_set_stencil_reference(pass_id: RenderPassId, value: u32) { - let hub = B::hub(); +pub fn render_pass_set_stencil_reference( + global: &Global, + pass_id: RenderPassId, + value: u32, +) { + let hub = B::hub(global); let mut token = Token::root(); let (mut pass_guard, _) = hub.render_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; @@ -714,12 +742,14 @@ pub fn render_pass_set_stencil_reference(pass_id: RenderPassId, v } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_set_stencil_reference(pass_id: RenderPassId, value: u32) { - gfx_select!(pass_id => render_pass_set_stencil_reference(pass_id, value)) + gfx_select!(pass_id => render_pass_set_stencil_reference(&*GLOBAL, pass_id, value)) } pub fn render_pass_set_viewport( + global: &Global, pass_id: RenderPassId, x: f32, y: f32, @@ -728,7 +758,7 @@ pub fn render_pass_set_viewport( min_depth: f32, max_depth: f32, ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (mut pass_guard, _) = hub.render_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; @@ -752,6 +782,7 @@ pub fn render_pass_set_viewport( } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_set_viewport( pass_id: RenderPassId, @@ -762,17 +793,18 @@ pub extern "C" fn wgpu_render_pass_set_viewport( min_depth: f32, max_depth: f32, ) { - gfx_select!(pass_id => render_pass_set_viewport(pass_id, x, y, w, h, min_depth, max_depth)) + gfx_select!(pass_id => render_pass_set_viewport(&*GLOBAL, pass_id, x, y, w, h, min_depth, max_depth)) } pub fn render_pass_set_scissor_rect( + global: &Global, pass_id: RenderPassId, x: u32, y: u32, w: u32, h: u32, ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (mut pass_guard, _) = hub.render_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; @@ -793,6 +825,7 @@ pub fn render_pass_set_scissor_rect( } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_set_scissor_rect( pass_id: RenderPassId, @@ -801,9 +834,10 @@ pub extern "C" fn wgpu_render_pass_set_scissor_rect( w: u32, h: u32, ) { - gfx_select!(pass_id => render_pass_set_scissor_rect(pass_id, x, y, w, h)) + gfx_select!(pass_id => render_pass_set_scissor_rect(&*GLOBAL, pass_id, x, y, w, h)) } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_render_pass_execute_bundles( _pass_id: RenderPassId, diff --git a/wgpu-native/src/command/transfer.rs b/wgpu-native/src/command/transfer.rs index 58a5cc54b..fc85ff13d 100644 --- a/wgpu-native/src/command/transfer.rs +++ b/wgpu-native/src/command/transfer.rs @@ -5,8 +5,7 @@ use crate::{ conv, device::{all_buffer_stages, all_image_stages}, - gfx_select, - hub::{GfxBackend, Token}, + hub::{GfxBackend, Global, Token}, BufferAddress, BufferId, BufferUsage, @@ -16,6 +15,8 @@ use crate::{ TextureId, TextureUsage, }; +#[cfg(feature = "local")] +use crate::{gfx_select, hub::GLOBAL}; use hal::command::CommandBuffer as _; @@ -65,6 +66,7 @@ impl TextureCopyView { } pub fn command_encoder_copy_buffer_to_buffer( + global: &Global, command_encoder_id: CommandEncoderId, source: BufferId, source_offset: BufferAddress, @@ -72,7 +74,7 @@ pub fn command_encoder_copy_buffer_to_buffer( destination_offset: BufferAddress, size: BufferAddress, ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (mut cmb_guard, mut token) = hub.command_buffers.write(&mut token); @@ -124,6 +126,7 @@ pub fn command_encoder_copy_buffer_to_buffer( } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_command_encoder_copy_buffer_to_buffer( command_encoder_id: CommandEncoderId, @@ -134,6 +137,7 @@ pub extern "C" fn wgpu_command_encoder_copy_buffer_to_buffer( size: BufferAddress, ) { gfx_select!(command_encoder_id => command_encoder_copy_buffer_to_buffer( + &*GLOBAL, command_encoder_id, source, source_offset, destination, @@ -142,12 +146,13 @@ pub extern "C" fn wgpu_command_encoder_copy_buffer_to_buffer( } pub fn command_encoder_copy_buffer_to_texture( + global: &Global, command_encoder_id: CommandEncoderId, source: &BufferCopyView, destination: &TextureCopyView, copy_size: Extent3d, ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (mut cmb_guard, mut token) = hub.command_buffers.write(&mut token); let cmb = &mut cmb_guard[command_encoder_id]; @@ -215,6 +220,7 @@ pub fn command_encoder_copy_buffer_to_texture( } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_command_encoder_copy_buffer_to_texture( command_encoder_id: CommandEncoderId, @@ -223,6 +229,7 @@ pub extern "C" fn wgpu_command_encoder_copy_buffer_to_texture( copy_size: Extent3d, ) { gfx_select!(command_encoder_id => command_encoder_copy_buffer_to_texture( + &*GLOBAL, command_encoder_id, source, destination, @@ -230,12 +237,13 @@ pub extern "C" fn wgpu_command_encoder_copy_buffer_to_texture( } pub fn command_encoder_copy_texture_to_buffer( + global: &Global, command_encoder_id: CommandEncoderId, source: &TextureCopyView, destination: &BufferCopyView, copy_size: Extent3d, ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (mut cmb_guard, mut token) = hub.command_buffers.write(&mut token); let cmb = &mut cmb_guard[command_encoder_id]; @@ -305,6 +313,7 @@ pub fn command_encoder_copy_texture_to_buffer( } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_command_encoder_copy_texture_to_buffer( command_encoder_id: CommandEncoderId, @@ -313,6 +322,7 @@ pub extern "C" fn wgpu_command_encoder_copy_texture_to_buffer( copy_size: Extent3d, ) { gfx_select!(command_encoder_id => command_encoder_copy_texture_to_buffer( + &*GLOBAL, command_encoder_id, source, destination, @@ -320,12 +330,13 @@ pub extern "C" fn wgpu_command_encoder_copy_texture_to_buffer( } pub fn command_encoder_copy_texture_to_texture( + global: &Global, command_encoder_id: CommandEncoderId, source: &TextureCopyView, destination: &TextureCopyView, copy_size: Extent3d, ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (mut cmb_guard, mut token) = hub.command_buffers.write(&mut token); @@ -393,6 +404,7 @@ pub fn command_encoder_copy_texture_to_texture( } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_command_encoder_copy_texture_to_texture( command_encoder_id: CommandEncoderId, @@ -401,6 +413,7 @@ pub extern "C" fn wgpu_command_encoder_copy_texture_to_texture( copy_size: Extent3d, ) { gfx_select!(command_encoder_id => command_encoder_copy_texture_to_texture( + &*GLOBAL, command_encoder_id, source, destination, diff --git a/wgpu-native/src/conv.rs b/wgpu-native/src/conv.rs index 4af1ab45e..60495e12b 100644 --- a/wgpu-native/src/conv.rs +++ b/wgpu-native/src/conv.rs @@ -311,7 +311,10 @@ fn map_stencil_operation(stencil_operation: pipeline::StencilOperation) -> hal:: } } -pub(crate) fn map_texture_format(texture_format: resource::TextureFormat, features: Features) -> hal::format::Format { +pub(crate) fn map_texture_format( + texture_format: resource::TextureFormat, + features: Features, +) -> hal::format::Format { use crate::resource::TextureFormat as Tf; use hal::format::Format as H; match texture_format { @@ -371,16 +374,20 @@ pub(crate) fn map_texture_format(texture_format: resource::TextureFormat, featur // Depth and stencil formats Tf::Depth32Float => H::D32Sfloat, - Tf::Depth24Plus => if features.supports_texture_d24_s8 { - H::D24UnormS8Uint - } else { - H::D32Sfloat + Tf::Depth24Plus => { + if features.supports_texture_d24_s8 { + H::D24UnormS8Uint + } else { + H::D32Sfloat + } + } + Tf::Depth24PlusStencil8 => { + if features.supports_texture_d24_s8 { + H::D24UnormS8Uint + } else { + H::D32SfloatS8Uint + } } - Tf::Depth24PlusStencil8 => if features.supports_texture_d24_s8 { - H::D24UnormS8Uint - } else { - H::D32SfloatS8Uint - }, } } diff --git a/wgpu-native/src/device.rs b/wgpu-native/src/device.rs index c8bebc958..ac07e7f8c 100644 --- a/wgpu-native/src/device.rs +++ b/wgpu-native/src/device.rs @@ -2,16 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#[cfg(not(feature = "remote"))] -use crate::{ - instance::Limits, -}; +#[cfg(feature = "local")] +use crate::instance::Limits; use crate::{ binding_model, command, conv, - gfx_select, - hub::{GfxBackend, Token, GLOBAL}, + hub::{GfxBackend, Global, Token}, id::{Input, Output}, pipeline, resource, @@ -46,6 +43,8 @@ use crate::{ TextureUsage, TextureViewId, }; +#[cfg(feature = "local")] +use crate::{gfx_select, hub::GLOBAL}; use arrayvec::ArrayVec; use copyless::VecHelper as _; @@ -61,7 +60,7 @@ use parking_lot::Mutex; use rendy_descriptor::{DescriptorAllocator, DescriptorRanges, DescriptorSet}; use rendy_memory::{Block, Heaps, MemoryBlock}; -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] use std::marker::PhantomData; use std::{ collections::hash_map::Entry, @@ -70,7 +69,7 @@ use std::{ ops::Range, ptr, slice, - sync::atomic::{Ordering}, + sync::atomic::Ordering, }; @@ -275,7 +274,12 @@ impl PendingResources { last_done } - fn triage_referenced(&mut self, trackers: &mut TrackerSet, mut token: &mut Token>) { + fn triage_referenced( + &mut self, + global: &Global, + trackers: &mut TrackerSet, + mut token: &mut Token>, + ) { // Before destruction, a resource is expected to have the following strong refs: // - in resource itself // - in the device tracker @@ -286,7 +290,7 @@ impl PendingResources { return; } - let hub = B::hub(); + let hub = B::hub(global); //TODO: lock less, if possible let (mut bind_group_guard, mut token) = hub.bind_groups.write(&mut token); let (mut buffer_guard, mut token) = hub.buffers.write(&mut token); @@ -310,14 +314,14 @@ impl PendingResources { } trackers.buffers.remove(id); let buf = buffer_guard.remove(id).unwrap(); - #[cfg(not(feature = "remote"))] + #[cfg(feature = "local")] hub.buffers.identity.lock().free(id); (buf.life_guard, NativeResource::Buffer(buf.raw, buf.memory)) } ResourceId::Texture(id) => { trackers.textures.remove(id); let tex = texture_guard.remove(id).unwrap(); - #[cfg(not(feature = "remote"))] + #[cfg(feature = "local")] hub.textures.identity.lock().free(id); (tex.life_guard, NativeResource::Image(tex.raw, tex.memory)) } @@ -328,14 +332,14 @@ impl PendingResources { resource::TextureViewInner::Native { raw, .. } => raw, resource::TextureViewInner::SwapChain { .. } => unreachable!(), }; - #[cfg(not(feature = "remote"))] + #[cfg(feature = "local")] hub.texture_views.identity.lock().free(id); (view.life_guard, NativeResource::ImageView(raw)) } ResourceId::BindGroup(id) => { trackers.bind_groups.remove(id); let bind_group = bind_group_guard.remove(id).unwrap(); - #[cfg(not(feature = "remote"))] + #[cfg(feature = "local")] hub.bind_groups.identity.lock().free(id); ( bind_group.life_guard, @@ -345,7 +349,7 @@ impl PendingResources { ResourceId::Sampler(id) => { trackers.samplers.remove(id); let sampler = sampler_guard.remove(id).unwrap(); - #[cfg(not(feature = "remote"))] + #[cfg(feature = "local")] hub.samplers.identity.lock().free(id); (sampler.life_guard, NativeResource::Sampler(sampler.raw)) } @@ -362,11 +366,11 @@ impl PendingResources { } } - fn triage_mapped(&mut self, token: &mut Token>) { + fn triage_mapped(&mut self, global: &Global, token: &mut Token>) { if self.mapped.is_empty() { return; } - let (buffer_guard, _) = B::hub().buffers.read(token); + let (buffer_guard, _) = B::hub(global).buffers.read(token); for stored in self.mapped.drain(..) { let resource_id = stored.value; @@ -390,10 +394,11 @@ impl PendingResources { fn triage_framebuffers( &mut self, + global: &Global, framebuffers: &mut FastHashMap, token: &mut Token>, ) { - let (texture_view_guard, _) = B::hub().texture_views.read(token); + let (texture_view_guard, _) = B::hub(global).texture_views.read(token); let remove_list = framebuffers .keys() .filter_map(|key| { @@ -428,13 +433,14 @@ impl PendingResources { fn handle_mapping( &mut self, + global: &Global, raw: &B::Device, token: &mut Token>, ) -> Vec { if self.ready_to_map.is_empty() { return Vec::new(); } - let (mut buffer_guard, _) = B::hub().buffers.write(token); + let (mut buffer_guard, _) = B::hub(global).buffers.write(token); self.ready_to_map .drain(..) .map(|buffer_id| { @@ -562,24 +568,29 @@ impl Device { features: Features { max_bind_groups, supports_texture_d24_s8, - } + }, } } - fn maintain(&self, force_wait: bool, token: &mut Token) -> Vec { + fn maintain( + &self, + global: &Global, + force_wait: bool, + token: &mut Token, + ) -> Vec { let mut pending = self.pending.lock(); let mut trackers = self.trackers.lock(); - pending.triage_referenced(&mut *trackers, token); - pending.triage_mapped(token); - pending.triage_framebuffers(&mut *self.framebuffers.lock(), token); + pending.triage_referenced(global, &mut *trackers, token); + pending.triage_mapped(global, token); + pending.triage_framebuffers(global, &mut *self.framebuffers.lock(), token); let last_done = pending.cleanup( &self.raw, &self.mem_allocator, &self.desc_allocator, force_wait, ); - let callbacks = pending.handle_mapping(&self.raw, token); + let callbacks = pending.handle_mapping(global, &self.raw, token); unsafe { self.desc_allocator.lock().cleanup(&self.raw); @@ -678,7 +689,9 @@ impl Device { // Ensure `D24Plus` textures cannot be copied match desc.format { TextureFormat::Depth24Plus | TextureFormat::Depth24PlusStencil8 => { - assert!(!desc.usage.intersects(TextureUsage::COPY_SRC | TextureUsage::COPY_DST)); + assert!(!desc + .usage + .intersects(TextureUsage::COPY_SRC | TextureUsage::COPY_DST)); } _ => {} } @@ -755,7 +768,7 @@ impl Device { } } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_get_limits(_device_id: DeviceId, limits: &mut Limits) { *limits = Limits::default(); // TODO @@ -767,11 +780,12 @@ pub struct ShaderModule { } pub fn device_create_buffer( + global: &Global, device_id: DeviceId, desc: &resource::BufferDescriptor, id_in: Input, ) -> Output { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (device_guard, _) = hub.devices.read(&mut token); @@ -791,22 +805,23 @@ pub fn device_create_buffer( id_out } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_create_buffer( device_id: DeviceId, desc: &resource::BufferDescriptor, ) -> BufferId { - gfx_select!(device_id => device_create_buffer(device_id, desc, PhantomData)) + gfx_select!(device_id => device_create_buffer(&*GLOBAL, device_id, desc, PhantomData)) } pub fn device_create_buffer_mapped( + global: &Global, device_id: DeviceId, desc: &resource::BufferDescriptor, mapped_ptr_out: *mut *mut u8, id_in: Input, ) -> Output { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let mut desc = desc.clone(); desc.usage |= resource::BufferUsage::MAP_WRITE; @@ -840,18 +855,18 @@ pub fn device_create_buffer_mapped( id_out } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_create_buffer_mapped( device_id: DeviceId, desc: &resource::BufferDescriptor, mapped_ptr_out: *mut *mut u8, ) -> BufferId { - gfx_select!(device_id => device_create_buffer_mapped(device_id, desc, mapped_ptr_out, PhantomData)) + gfx_select!(device_id => device_create_buffer_mapped(&*GLOBAL, device_id, desc, mapped_ptr_out, PhantomData)) } -pub fn buffer_destroy(buffer_id: BufferId) { - let hub = B::hub(); +pub fn buffer_destroy(global: &Global, buffer_id: BufferId) { + let hub = B::hub(global); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); let (buffer_guard, _) = hub.buffers.read(&mut token); @@ -862,17 +877,19 @@ pub fn buffer_destroy(buffer_id: BufferId) { ); } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_buffer_destroy(buffer_id: BufferId) { - gfx_select!(buffer_id => buffer_destroy(buffer_id)) + gfx_select!(buffer_id => buffer_destroy(&*GLOBAL, buffer_id)) } pub fn device_create_texture( + global: &Global, device_id: DeviceId, desc: &resource::TextureDescriptor, id_in: Input, ) -> Output { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (device_guard, _) = hub.devices.read(&mut token); @@ -892,21 +909,22 @@ pub fn device_create_texture( id_out } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_create_texture( device_id: DeviceId, desc: &resource::TextureDescriptor, ) -> TextureId { - gfx_select!(device_id => device_create_texture(device_id, desc, PhantomData)) + gfx_select!(device_id => device_create_texture(&*GLOBAL, device_id, desc, PhantomData)) } pub fn texture_create_view( + global: &Global, texture_id: TextureId, desc: Option<&resource::TextureViewDescriptor>, id_in: Input, ) -> Output { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); @@ -990,17 +1008,17 @@ pub fn texture_create_view( id_out } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_texture_create_view( texture_id: TextureId, desc: Option<&resource::TextureViewDescriptor>, ) -> TextureViewId { - gfx_select!(texture_id => texture_create_view(texture_id, desc, PhantomData)) + gfx_select!(texture_id => texture_create_view(&*GLOBAL, texture_id, desc, PhantomData)) } -pub fn texture_destroy(texture_id: TextureId) { - let hub = B::hub(); +pub fn texture_destroy(global: &Global, texture_id: TextureId) { + let hub = B::hub(global); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); @@ -1015,23 +1033,24 @@ pub fn texture_destroy(texture_id: TextureId) { ); } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_texture_destroy(texture_id: TextureId) { - gfx_select!(texture_id => texture_destroy(texture_id)) + gfx_select!(texture_id => texture_destroy(&*GLOBAL, texture_id)) } -pub fn texture_view_destroy(texture_view_id: TextureViewId) { - let hub = B::hub(); +pub fn texture_view_destroy(global: &Global, texture_view_id: TextureViewId) { + let hub = B::hub(global); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); let (texture_guard, mut token) = hub.textures.read(&mut token); let (texture_view_guard, _) = hub.texture_views.read(&mut token); let view = &texture_view_guard[texture_view_id]; let device_id = match view.inner { - resource::TextureViewInner::Native { ref source_id, .. } => - texture_guard[source_id.value].device_id.value, - resource::TextureViewInner::SwapChain { .. } => - panic!("Can't destroy a swap chain image"), + resource::TextureViewInner::Native { ref source_id, .. } => { + texture_guard[source_id.value].device_id.value + } + resource::TextureViewInner::SwapChain { .. } => panic!("Can't destroy a swap chain image"), }; device_guard[device_id].pending.lock().destroy( ResourceId::TextureView(texture_view_id), @@ -1039,17 +1058,19 @@ pub fn texture_view_destroy(texture_view_id: TextureViewId) { ); } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_texture_view_destroy(texture_view_id: TextureViewId) { - gfx_select!(texture_view_id => texture_view_destroy(texture_view_id)) + gfx_select!(texture_view_id => texture_view_destroy(&*GLOBAL, texture_view_id)) } pub fn device_create_sampler( + global: &Global, device_id: DeviceId, desc: &resource::SamplerDescriptor, id_in: Input, ) -> Output { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); let device = &device_guard[device_id]; @@ -1086,17 +1107,17 @@ pub fn device_create_sampler( hub.samplers.register_identity(id_in, sampler, &mut token) } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_create_sampler( device_id: DeviceId, desc: &resource::SamplerDescriptor, ) -> SamplerId { - gfx_select!(device_id => device_create_sampler(device_id, desc, PhantomData)) + gfx_select!(device_id => device_create_sampler(&*GLOBAL, device_id, desc, PhantomData)) } -pub fn sampler_destroy(sampler_id: SamplerId) { - let hub = B::hub(); +pub fn sampler_destroy(global: &Global, sampler_id: SamplerId) { + let hub = B::hub(global); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); let (sampler_guard, _) = hub.samplers.read(&mut token); @@ -1110,18 +1131,20 @@ pub fn sampler_destroy(sampler_id: SamplerId) { ); } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_sampler_destroy(sampler_id: SamplerId) { - gfx_select!(sampler_id => sampler_destroy(sampler_id)) + gfx_select!(sampler_id => sampler_destroy(&*GLOBAL, sampler_id)) } pub fn device_create_bind_group_layout( + global: &Global, device_id: DeviceId, desc: &binding_model::BindGroupLayoutDescriptor, id_in: Input, ) -> Output { let mut token = Token::root(); - let hub = B::hub(); + let hub = B::hub(global); let bindings = unsafe { slice::from_raw_parts(desc.bindings, desc.bindings_length) }; let raw_bindings = bindings @@ -1154,21 +1177,22 @@ pub fn device_create_bind_group_layout( .register_identity(id_in, layout, &mut token) } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_create_bind_group_layout( device_id: DeviceId, desc: &binding_model::BindGroupLayoutDescriptor, ) -> BindGroupLayoutId { - gfx_select!(device_id => device_create_bind_group_layout(device_id, desc, PhantomData)) + gfx_select!(device_id => device_create_bind_group_layout(&*GLOBAL, device_id, desc, PhantomData)) } pub fn device_create_pipeline_layout( + global: &Global, device_id: DeviceId, desc: &binding_model::PipelineLayoutDescriptor, id_in: Input, ) -> Output { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); @@ -1197,21 +1221,22 @@ pub fn device_create_pipeline_layout( .register_identity(id_in, layout, &mut token) } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_create_pipeline_layout( device_id: DeviceId, desc: &binding_model::PipelineLayoutDescriptor, ) -> PipelineLayoutId { - gfx_select!(device_id => device_create_pipeline_layout(device_id, desc, PhantomData)) + gfx_select!(device_id => device_create_pipeline_layout(&*GLOBAL, device_id, desc, PhantomData)) } pub fn device_create_bind_group( + global: &Global, device_id: DeviceId, desc: &binding_model::BindGroupDescriptor, id_in: Input, ) -> Output { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); @@ -1276,7 +1301,11 @@ pub fn device_create_bind_group( .buffers .use_extend(&*buffer_guard, bb.buffer, (), usage) .unwrap(); - assert!(buffer.usage.contains(usage), "Expected buffer usage {:?}", usage); + assert!( + buffer.usage.contains(usage), + "Expected buffer usage {:?}", + usage + ); let end = if bb.size == 0 { None @@ -1296,7 +1325,8 @@ pub fn device_create_bind_group( } binding_model::BindingResource::Sampler(id) => { assert_eq!(decl.ty, binding_model::BindingType::Sampler); - let sampler = used.samplers + let sampler = used + .samplers .use_extend(&*sampler_guard, id, (), ()) .unwrap(); hal::pso::Descriptor::Sampler(&sampler.raw) @@ -1317,21 +1347,26 @@ pub fn device_create_bind_group( .use_extend(&*texture_view_guard, id, (), ()) .unwrap(); match view.inner { - resource::TextureViewInner::Native { ref raw, ref source_id } => { - let texture = used.textures - .use_extend( - &*texture_guard, - source_id.value, - view.range.clone(), - usage, - ) - .unwrap(); - assert!(texture.usage.contains(usage)); + resource::TextureViewInner::Native { + ref raw, + ref source_id, + } => { + let texture = used + .textures + .use_extend( + &*texture_guard, + source_id.value, + view.range.clone(), + usage, + ) + .unwrap(); + assert!(texture.usage.contains(usage)); - hal::pso::Descriptor::Image(raw, image_layout) + hal::pso::Descriptor::Image(raw, image_layout) + } + resource::TextureViewInner::SwapChain { .. } => { + panic!("Unable to create a bind group with a swap chain image") } - resource::TextureViewInner::SwapChain { .. } => - panic!("Unable to create a bind group with a swap chain image"), } } }; @@ -1371,17 +1406,17 @@ pub fn device_create_bind_group( id_out } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_create_bind_group( device_id: DeviceId, desc: &binding_model::BindGroupDescriptor, ) -> BindGroupId { - gfx_select!(device_id => device_create_bind_group(device_id, desc, PhantomData)) + gfx_select!(device_id => device_create_bind_group(&*GLOBAL, device_id, desc, PhantomData)) } -pub fn bind_group_destroy(bind_group_id: BindGroupId) { - let hub = B::hub(); +pub fn bind_group_destroy(global: &Global, bind_group_id: BindGroupId) { + let hub = B::hub(global); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); let (bind_group_guard, _) = hub.bind_groups.read(&mut token); @@ -1395,17 +1430,19 @@ pub fn bind_group_destroy(bind_group_id: BindGroupId) { ); } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_bind_group_destroy(bind_group_id: BindGroupId) { - gfx_select!(bind_group_id => bind_group_destroy(bind_group_id)) + gfx_select!(bind_group_id => bind_group_destroy(&*GLOBAL, bind_group_id)) } pub fn device_create_shader_module( + global: &Global, device_id: DeviceId, desc: &pipeline::ShaderModuleDescriptor, id_in: Input, ) -> Output { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let spv = unsafe { slice::from_raw_parts(desc.code.bytes, desc.code.length) }; @@ -1424,21 +1461,22 @@ pub fn device_create_shader_module( .register_identity(id_in, shader, &mut token) } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_create_shader_module( device_id: DeviceId, desc: &pipeline::ShaderModuleDescriptor, ) -> ShaderModuleId { - gfx_select!(device_id => device_create_shader_module(device_id, desc, PhantomData)) + gfx_select!(device_id => device_create_shader_module(&*GLOBAL, device_id, desc, PhantomData)) } pub fn device_create_command_encoder( + global: &Global, device_id: DeviceId, _desc: &command::CommandEncoderDescriptor, id_in: Input, ) -> Output { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); @@ -1448,7 +1486,9 @@ pub fn device_create_command_encoder( value: device_id, ref_count: device.life_guard.ref_count.clone(), }; - let mut comb = device.com_allocator.allocate(dev_stored, &device.raw, device.features); + let mut comb = device + .com_allocator + .allocate(dev_stored, &device.raw, device.features); unsafe { comb.raw.last_mut().unwrap().begin( hal::command::CommandBufferFlags::ONE_TIME_SUBMIT, @@ -1460,23 +1500,28 @@ pub fn device_create_command_encoder( .register_identity(id_in, comb, &mut token) } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_create_command_encoder( device_id: DeviceId, desc: Option<&command::CommandEncoderDescriptor>, ) -> CommandEncoderId { let desc = &desc.cloned().unwrap_or_default(); - gfx_select!(device_id => device_create_command_encoder(device_id, desc, PhantomData)) + gfx_select!(device_id => device_create_command_encoder(&*GLOBAL, device_id, desc, PhantomData)) } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_get_queue(device_id: DeviceId) -> QueueId { device_id } -pub fn queue_submit(queue_id: QueueId, command_buffer_ids: &[CommandBufferId]) { - let hub = B::hub(); +pub fn queue_submit( + global: &Global, + queue_id: QueueId, + command_buffer_ids: &[CommandBufferId], +) { + let hub = B::hub(global); let (submit_index, fence) = { let mut token = Token::root(); @@ -1510,9 +1555,15 @@ pub fn queue_submit(queue_id: QueueId, command_buffer_ids: &[Comm if let Some((view_id, fbo)) = comb.used_swap_chain.take() { let sem = match texture_view_guard[view_id.value].inner { resource::TextureViewInner::Native { .. } => unreachable!(), - resource::TextureViewInner::SwapChain { ref source_id, ref mut framebuffer, .. } => { - assert!(framebuffer.is_none(), - "Using a swap chain in multiple framebuffers is not supported yet"); + resource::TextureViewInner::SwapChain { + ref source_id, + ref mut framebuffer, + .. + } => { + assert!( + framebuffer.is_none(), + "Using a swap chain in multiple framebuffers is not supported yet" + ); *framebuffer = Some(fbo); &swap_chain_guard[source_id.value].semaphore } @@ -1594,8 +1645,7 @@ pub fn queue_submit(queue_id: QueueId, command_buffer_ids: &[Comm }; unsafe { - device.queue_group.queues[0] - .submit(submission, Some(&fence)); + device.queue_group.queues[0].submit(submission, Some(&fence)); } (submit_index, fence) @@ -1607,7 +1657,7 @@ pub fn queue_submit(queue_id: QueueId, command_buffer_ids: &[Comm let (device_guard, mut token) = hub.devices.read(&mut token); let device = &device_guard[queue_id]; - let callbacks = device.maintain(false, &mut token); + let callbacks = device.maintain(global, false, &mut token); device.pending.lock().active.alloc().init(ActiveSubmission { index: submit_index, fence, @@ -1627,6 +1677,7 @@ pub fn queue_submit(queue_id: QueueId, command_buffer_ids: &[Comm Device::::fire_map_callbacks(callbacks); } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_queue_submit( queue_id: QueueId, @@ -1635,15 +1686,16 @@ pub extern "C" fn wgpu_queue_submit( ) { let command_buffer_ids = unsafe { slice::from_raw_parts(command_buffers, command_buffers_length) }; - gfx_select!(queue_id => queue_submit(queue_id, command_buffer_ids)) + gfx_select!(queue_id => queue_submit(&*GLOBAL, queue_id, command_buffer_ids)) } pub fn device_create_render_pipeline( + global: &Global, device_id: DeviceId, desc: &pipeline::RenderPipelineDescriptor, id_in: Input, ) -> Output { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let sc = desc.sample_count; @@ -1898,21 +1950,22 @@ pub fn device_create_render_pipeline( .register_identity(id_in, pipeline, &mut token) } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_create_render_pipeline( device_id: DeviceId, desc: &pipeline::RenderPipelineDescriptor, ) -> RenderPipelineId { - gfx_select!(device_id => device_create_render_pipeline(device_id, desc, PhantomData)) + gfx_select!(device_id => device_create_render_pipeline(&*GLOBAL, device_id, desc, PhantomData)) } pub fn device_create_compute_pipeline( + global: &Global, device_id: DeviceId, desc: &pipeline::ComputePipelineDescriptor, id_in: Input, ) -> Output { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let raw_pipeline = { @@ -1959,25 +2012,26 @@ pub fn device_create_compute_pipeline( .register_identity(id_in, pipeline, &mut token) } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_create_compute_pipeline( device_id: DeviceId, desc: &pipeline::ComputePipelineDescriptor, ) -> ComputePipelineId { - gfx_select!(device_id => device_create_compute_pipeline(device_id, desc, PhantomData)) + gfx_select!(device_id => device_create_compute_pipeline(&*GLOBAL, device_id, desc, PhantomData)) } pub fn device_create_swap_chain( + global: &Global, device_id: DeviceId, surface_id: SurfaceId, desc: &swap_chain::SwapChainDescriptor, ) -> SwapChainId { log::info!("creating swap chain {:?}", desc); - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); - let (mut surface_guard, mut token) = GLOBAL.surfaces.write(&mut token); + let (mut surface_guard, mut token) = global.surfaces.write(&mut token); let (adapter_guard, mut token) = hub.adapters.read(&mut token); let (device_guard, mut token) = hub.devices.read(&mut token); let (mut swap_chain_guard, _) = hub.swap_chains.write(&mut token); @@ -2003,13 +2057,17 @@ pub fn device_create_swap_chain( formats ); } - if desc.width < caps.extents.start().width || - desc.width > caps.extents.end().width || - desc.height < caps.extents.start().height || - desc.height > caps.extents.end().height + if desc.width < caps.extents.start().width + || desc.width > caps.extents.end().width + || desc.height < caps.extents.start().height + || desc.height > caps.extents.end().height { - log::warn!("Requested size {}x{} is outside of the supported range: {:?}", - desc.width, desc.height, caps.extents); + log::warn!( + "Requested size {}x{} is outside of the supported range: {:?}", + desc.width, + desc.height, + caps.extents + ); } unsafe { @@ -2039,40 +2097,42 @@ pub fn device_create_swap_chain( sc_id } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_create_swap_chain( device_id: DeviceId, surface_id: SurfaceId, desc: &swap_chain::SwapChainDescriptor, ) -> SwapChainId { - gfx_select!(device_id => device_create_swap_chain(device_id, surface_id, desc)) + gfx_select!(device_id => device_create_swap_chain(&*GLOBAL, device_id, surface_id, desc)) } -pub fn device_poll(device_id: DeviceId, force_wait: bool) { - let hub = B::hub(); +pub fn device_poll(global: &Global, device_id: DeviceId, force_wait: bool) { + let hub = B::hub(global); let callbacks = { let (device_guard, mut token) = hub.devices.read(&mut Token::root()); - device_guard[device_id].maintain(force_wait, &mut token) + device_guard[device_id].maintain(global, force_wait, &mut token) }; Device::::fire_map_callbacks(callbacks); } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_poll(device_id: DeviceId, force_wait: bool) { - gfx_select!(device_id => device_poll(device_id, force_wait)) + gfx_select!(device_id => device_poll(&*GLOBAL, device_id, force_wait)) } -pub fn device_destroy(device_id: DeviceId) { - let hub = B::hub(); +pub fn device_destroy(global: &Global, device_id: DeviceId) { + let hub = B::hub(global); let (device, mut token) = hub.devices.unregister(device_id, &mut Token::root()); - device.maintain(true, &mut token); + device.maintain(global, true, &mut token); device.com_allocator.destroy(&device.raw); } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_destroy(device_id: DeviceId) { - gfx_select!(device_id => device_destroy(device_id)) + gfx_select!(device_id => device_destroy(&*GLOBAL, device_id)) } pub type BufferMapReadCallback = @@ -2081,11 +2141,12 @@ pub type BufferMapWriteCallback = extern "C" fn(status: BufferMapAsyncStatus, data: *mut u8, userdata: *mut u8); pub fn buffer_map_async( + global: &Global, buffer_id: BufferId, usage: resource::BufferUsage, operation: BufferMapOperation, ) { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); @@ -2121,6 +2182,7 @@ pub fn buffer_map_async( device.pending.lock().map(buffer_id, ref_count); } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_buffer_map_read_async( buffer_id: BufferId, @@ -2130,9 +2192,10 @@ pub extern "C" fn wgpu_buffer_map_read_async( userdata: *mut u8, ) { let operation = BufferMapOperation::Read(start .. start + size, callback, userdata); - gfx_select!(buffer_id => buffer_map_async(buffer_id, resource::BufferUsage::MAP_READ, operation)) + gfx_select!(buffer_id => buffer_map_async(&*GLOBAL, buffer_id, resource::BufferUsage::MAP_READ, operation)) } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_buffer_map_write_async( buffer_id: BufferId, @@ -2142,11 +2205,11 @@ pub extern "C" fn wgpu_buffer_map_write_async( userdata: *mut u8, ) { let operation = BufferMapOperation::Write(start .. start + size, callback, userdata); - gfx_select!(buffer_id => buffer_map_async(buffer_id, resource::BufferUsage::MAP_WRITE, operation)) + gfx_select!(buffer_id => buffer_map_async(&*GLOBAL, buffer_id, resource::BufferUsage::MAP_WRITE, operation)) } -pub fn buffer_unmap(buffer_id: BufferId) { - let hub = B::hub(); +pub fn buffer_unmap(global: &Global, buffer_id: BufferId) { + let hub = B::hub(global); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); @@ -2172,7 +2235,8 @@ pub fn buffer_unmap(buffer_id: BufferId) { buffer.memory.unmap(device_raw); } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_buffer_unmap(buffer_id: BufferId) { - gfx_select!(buffer_id => buffer_unmap(buffer_id)) + gfx_select!(buffer_id => buffer_unmap(&*GLOBAL, buffer_id)) } diff --git a/wgpu-native/src/hub.rs b/wgpu-native/src/hub.rs index c14893bec..b4f132831 100644 --- a/wgpu-native/src/hub.rs +++ b/wgpu-native/src/hub.rs @@ -46,15 +46,16 @@ use crate::{ TypedId, }; -use lazy_static::lazy_static; -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] use parking_lot::Mutex; use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use vec_map::VecMap; -#[allow(unused)] +#[cfg(debug_assertions)] use std::cell::Cell; -use std::{marker::PhantomData, ops, sync::Arc}; +#[cfg(feature = "local")] +use std::sync::Arc; +use std::{marker::PhantomData, ops}; /// A simple structure to manage identities of objects. @@ -147,7 +148,8 @@ impl Storage { pub fn remove(&mut self, id: I) -> Option { let (index, epoch, _) = id.unzip(); - self.map.remove(index as usize) + self.map + .remove(index as usize) .map(|(value, storage_epoch)| { assert_eq!(epoch, storage_epoch); value @@ -271,7 +273,7 @@ impl<'a, T> Drop for Token<'a, T> { #[derive(Debug)] pub struct Registry { - #[cfg(not(feature = "remote"))] + #[cfg(feature = "local")] pub identity: Mutex>, data: RwLock>, backend: Backend, @@ -280,7 +282,7 @@ pub struct Registry { impl Registry { fn new(backend: Backend) -> Self { Registry { - #[cfg(not(feature = "remote"))] + #[cfg(feature = "local")] identity: Mutex::new(IdentityManager::new(backend)), data: RwLock::new(Storage { map: VecMap::new(), @@ -298,13 +300,13 @@ impl Registry { assert!(old.is_none()); } - #[cfg(not(feature = "remote"))] + #[cfg(feature = "local")] pub fn new_identity(&self, _id_in: Input) -> (I, Output) { let id = self.identity.lock().alloc(); (id, id) } - #[cfg(feature = "remote")] + #[cfg(not(feature = "local"))] pub fn new_identity(&self, id_in: Input) -> (I, Output) { //TODO: debug_assert_eq!(self.backend, id_in.backend()); (id_in, PhantomData) @@ -324,7 +326,7 @@ impl Registry { pub fn unregister>(&self, id: I, _token: &mut Token) -> (T, Token) { let value = self.data.write().remove(id).unwrap(); //Note: careful about the order here! - #[cfg(not(feature = "remote"))] + #[cfg(feature = "local")] self.identity.lock().free(id); (value, Token::new()) } @@ -389,7 +391,10 @@ impl Default for Hub { #[derive(Debug, Default)] pub struct Hubs { - #[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 = "gfx-backend-vulkan" + ))] vulkan: Hub, #[cfg(any(target_os = "ios", target_os = "macos"))] metal: Hub, @@ -406,7 +411,8 @@ pub struct Global { hubs: Hubs, } -lazy_static! { +#[cfg(feature = "local")] +lazy_static::lazy_static! { pub static ref GLOBAL: Arc = Arc::new(Global { instance: Instance::new("wgpu", 1), surfaces: Registry::new(Backend::Empty), @@ -416,15 +422,18 @@ lazy_static! { pub trait GfxBackend: hal::Backend { const VARIANT: Backend; - fn hub() -> &'static Hub; + fn hub(global: &Global) -> &Hub; fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface; } -#[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 = "gfx-backend-vulkan" +))] impl GfxBackend for backend::Vulkan { const VARIANT: Backend = Backend::Vulkan; - fn hub() -> &'static Hub { - &GLOBAL.hubs.vulkan + fn hub(global: &Global) -> &Hub { + &global.hubs.vulkan } fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface { surface.vulkan.as_mut().unwrap() @@ -434,8 +443,8 @@ impl GfxBackend for backend::Vulkan { #[cfg(any(target_os = "ios", target_os = "macos"))] impl GfxBackend for backend::Metal { const VARIANT: Backend = Backend::Metal; - fn hub() -> &'static Hub { - &GLOBAL.hubs.metal + fn hub(global: &Global) -> &Hub { + &global.hubs.metal } fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface { &mut surface.metal @@ -445,8 +454,8 @@ impl GfxBackend for backend::Metal { #[cfg(windows)] impl GfxBackend for backend::Dx12 { const VARIANT: Backend = Backend::Dx12; - fn hub() -> &'static Hub { - &GLOBAL.hubs.dx12 + fn hub(global: &Global) -> &Hub { + &global.hubs.dx12 } fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface { surface.dx12.as_mut().unwrap() @@ -456,8 +465,8 @@ impl GfxBackend for backend::Dx12 { #[cfg(windows)] impl GfxBackend for backend::Dx11 { const VARIANT: Backend = Backend::Dx11; - fn hub() -> &'static Hub { - &GLOBAL.hubs.dx11 + fn hub(global: &Global) -> &Hub { + &global.hubs.dx11 } fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface { &mut surface.dx11 diff --git a/wgpu-native/src/id.rs b/wgpu-native/src/id.rs index 16bd6be05..839c8521a 100644 --- a/wgpu-native/src/id.rs +++ b/wgpu-native/src/id.rs @@ -76,13 +76,13 @@ impl TypedId for Id { } } -#[cfg(feature = "remote")] +#[cfg(not(feature = "local"))] pub type Input = T; -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] pub type Input = PhantomData; -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] pub type Output = T; -#[cfg(feature = "remote")] +#[cfg(not(feature = "local"))] pub type Output = PhantomData; diff --git a/wgpu-native/src/instance.rs b/wgpu-native/src/instance.rs index 51469893c..fd6c93278 100644 --- a/wgpu-native/src/instance.rs +++ b/wgpu-native/src/instance.rs @@ -6,7 +6,7 @@ use crate::{ backend, binding_model::MAX_BIND_GROUPS, device::BIND_BUFFER_ALIGNMENT, - hub::{GfxBackend, Token, GLOBAL}, + hub::{GfxBackend, Global, Token}, id::{Input, Output}, AdapterId, AdapterInfo, @@ -14,28 +14,25 @@ use crate::{ Device, DeviceId, }; -#[cfg(not(feature = "remote"))] -use crate::{gfx_select, SurfaceId}; +#[cfg(feature = "local")] +use crate::{gfx_select, hub::GLOBAL, SurfaceId}; -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] use bitflags::bitflags; -use log::{info, warn}; -#[cfg(feature = "remote")] +#[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; -use hal::{ - self, - Instance as _, - adapter::PhysicalDevice as _, - queue::QueueFamily as _, -}; -#[cfg(not(feature = "remote"))] +use hal::{self, adapter::PhysicalDevice as _, queue::QueueFamily as _, Instance as _}; +#[cfg(feature = "local")] use std::marker::PhantomData; #[derive(Debug)] pub struct Instance { - #[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 = "gfx-backend-vulkan" + ))] vulkan: Option, #[cfg(any(target_os = "ios", target_os = "macos"))] metal: gfx_backend_metal::Instance, @@ -46,9 +43,12 @@ pub struct Instance { } impl Instance { - pub(crate) fn new(name: &str, version: u32) -> Self { + pub fn new(name: &str, version: u32) -> Self { Instance { - #[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 = "gfx-backend-vulkan" + ))] vulkan: gfx_backend_vulkan::Instance::create(name, version).ok(), #[cfg(any(target_os = "ios", target_os = "macos"))] metal: gfx_backend_metal::Instance::create(name, version).unwrap(), @@ -64,7 +64,10 @@ type GfxSurface = ::Surface; #[derive(Debug)] pub struct Surface { - #[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 = "gfx-backend-vulkan" + ))] pub(crate) vulkan: Option>, #[cfg(any(target_os = "ios", target_os = "macos"))] pub(crate) metal: GfxSurface, @@ -81,14 +84,14 @@ pub struct Adapter { #[repr(C)] #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] -#[cfg_attr(feature = "remote", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum PowerPreference { Default = 0, LowPower = 1, HighPerformance = 2, } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] bitflags! { #[repr(transparent)] pub struct BackendBit: u32 { @@ -104,7 +107,7 @@ bitflags! { } } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] impl From for BackendBit { fn from(backend: Backend) -> Self { BackendBit::from_bits(1 << backend as u32).unwrap() @@ -113,10 +116,10 @@ impl From for BackendBit { #[repr(C)] #[derive(Clone, Debug)] -#[cfg_attr(feature = "remote", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct RequestAdapterOptions { pub power_preference: PowerPreference, - #[cfg(not(feature = "remote"))] + #[cfg(feature = "local")] pub backends: BackendBit, } @@ -124,7 +127,7 @@ impl Default for RequestAdapterOptions { fn default() -> Self { RequestAdapterOptions { power_preference: PowerPreference::Default, - #[cfg(not(feature = "remote"))] + #[cfg(feature = "local")] backends: BackendBit::PRIMARY, } } @@ -132,14 +135,14 @@ impl Default for RequestAdapterOptions { #[repr(C)] #[derive(Clone, Debug, Default)] -#[cfg_attr(feature = "remote", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Extensions { pub anisotropic_filtering: bool, } #[repr(C)] #[derive(Clone, Debug)] -#[cfg_attr(feature = "remote", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Limits { pub max_bind_groups: u32, } @@ -154,13 +157,13 @@ impl Default for Limits { #[repr(C)] #[derive(Clone, Debug, Default)] -#[cfg_attr(feature = "remote", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct DeviceDescriptor { pub extensions: Extensions, pub limits: Limits, } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] pub fn wgpu_create_surface(raw_handle: raw_window_handle::RawWindowHandle) -> SurfaceId { use raw_window_handle::RawWindowHandle as Rwh; @@ -220,7 +223,12 @@ pub fn wgpu_create_surface(raw_handle: raw_window_handle::RawWindowHandle) -> Su .register_identity(PhantomData, surface, &mut token) } -#[cfg(all(not(feature = "remote"), unix, not(target_os = "ios"), not(target_os = "macos")))] +#[cfg(all( + feature = "local", + unix, + not(target_os = "ios"), + not(target_os = "macos") +))] #[no_mangle] pub extern "C" fn wgpu_create_surface_from_xlib( display: *mut *const std::ffi::c_void, @@ -234,7 +242,7 @@ pub extern "C" fn wgpu_create_surface_from_xlib( })) } -#[cfg(all(not(feature = "remote"), any(target_os = "ios", target_os = "macos")))] +#[cfg(all(feature = "local", any(target_os = "ios", target_os = "macos")))] #[no_mangle] pub extern "C" fn wgpu_create_surface_from_metal_layer(layer: *mut std::ffi::c_void) -> SurfaceId { let surface = Surface { @@ -251,7 +259,7 @@ pub extern "C" fn wgpu_create_surface_from_metal_layer(layer: *mut std::ffi::c_v .register_identity(PhantomData, surface, &mut Token::root()) } -#[cfg(all(not(feature = "remote"), windows))] +#[cfg(all(feature = "local", windows))] #[no_mangle] pub extern "C" fn wgpu_create_surface_from_windows_hwnd( _hinstance: *mut std::ffi::c_void, @@ -267,15 +275,16 @@ pub extern "C" fn wgpu_create_surface_from_windows_hwnd( } pub fn request_adapter( + global: &Global, desc: &RequestAdapterOptions, input_ids: &[Input], ) -> Option { - let instance = &GLOBAL.instance; + let instance = &global.instance; let mut device_types = Vec::new(); - #[cfg(feature = "remote")] + #[cfg(not(feature = "local"))] let find_input = |b: Backend| input_ids.iter().find(|id| id.backend() == b).cloned(); - #[cfg(not(feature = "remote"))] + #[cfg(feature = "local")] let find_input = |b: Backend| { let _ = input_ids; if desc.backends.contains(b.into()) { @@ -284,9 +293,9 @@ pub fn request_adapter( None } }; - #[cfg(feature = "remote")] + #[cfg(not(feature = "local"))] let pick = |_output, input_maybe| input_maybe; - #[cfg(not(feature = "remote"))] + #[cfg(feature = "local")] let pick = |output, _input_maybe| Some(output); let id_vulkan = find_input(Backend::Vulkan); @@ -294,7 +303,10 @@ pub fn request_adapter( let id_dx12 = find_input(Backend::Dx12); let id_dx11 = find_input(Backend::Dx11); - #[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 = "gfx-backend-vulkan" + ))] let mut adapters_vk = match instance.vulkan { Some(ref inst) if id_vulkan.is_some() => { let adapters = inst.enumerate_adapters(); @@ -360,14 +372,17 @@ pub fn request_adapter( let mut token = Token::root(); let mut selected = preferred_gpu.unwrap_or(0); - #[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 = "gfx-backend-vulkan" + ))] { if selected < adapters_vk.len() { let adapter = Adapter { raw: adapters_vk.swap_remove(selected), }; - info!("Adapter Vulkan {:?}", adapter.raw.info); - let id_out = backend::Vulkan::hub().adapters.register_identity( + log::info!("Adapter Vulkan {:?}", adapter.raw.info); + let id_out = backend::Vulkan::hub(global).adapters.register_identity( id_vulkan.unwrap(), adapter, &mut token, @@ -382,8 +397,8 @@ pub fn request_adapter( let adapter = Adapter { raw: adapters_mtl.swap_remove(selected), }; - info!("Adapter Metal {:?}", adapter.raw.info); - let id_out = backend::Metal::hub().adapters.register_identity( + log::info!("Adapter Metal {:?}", adapter.raw.info); + let id_out = backend::Metal::hub(global).adapters.register_identity( id_metal.unwrap(), adapter, &mut token, @@ -398,8 +413,8 @@ pub fn request_adapter( let adapter = Adapter { raw: adapters_dx12.swap_remove(selected), }; - info!("Adapter Dx12 {:?}", adapter.raw.info); - let id_out = backend::Dx12::hub().adapters.register_identity( + log::info!("Adapter Dx12 {:?}", adapter.raw.info); + let id_out = backend::Dx12::hub(global).adapters.register_identity( id_dx12.unwrap(), adapter, &mut token, @@ -411,8 +426,8 @@ pub fn request_adapter( let adapter = Adapter { raw: adapters_dx11.swap_remove(selected), }; - info!("Adapter Dx11 {:?}", adapter.raw.info); - let id_out = backend::Dx11::hub().adapters.register_identity( + log::info!("Adapter Dx11 {:?}", adapter.raw.info); + let id_out = backend::Dx11::hub(global).adapters.register_identity( id_dx11.unwrap(), adapter, &mut token, @@ -425,18 +440,19 @@ pub fn request_adapter( None } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_request_adapter(desc: Option<&RequestAdapterOptions>) -> AdapterId { - request_adapter(&desc.cloned().unwrap_or_default(), &[]).unwrap() + request_adapter(&*GLOBAL, &desc.cloned().unwrap_or_default(), &[]).unwrap() } pub fn adapter_request_device( + global: &Global, adapter_id: AdapterId, desc: &DeviceDescriptor, id_in: Input, ) -> Output { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); let device = { let (adapter_guard, _) = hub.adapters.read(&mut token); @@ -445,12 +461,11 @@ pub fn adapter_request_device( let family = adapter .queue_families .iter() - .find(|family| { - family.queue_type().supports_graphics() - }) + .find(|family| family.queue_type().supports_graphics()) .unwrap(); let mut gpu = unsafe { - adapter.physical_device + adapter + .physical_device .open(&[(family, &[1.0])], hal::Features::empty()) .unwrap() }; @@ -467,7 +482,7 @@ pub fn adapter_request_device( "Adapter uniform buffer offset alignment not compatible with WGPU" ); if desc.limits.max_bind_groups == 0 { - warn!("max_bind_groups limit is missing"); + log::warn!("max_bind_groups limit is missing"); } else { assert!( u32::from(limits.max_bound_descriptor_sets) >= desc.limits.max_bind_groups, @@ -496,27 +511,25 @@ pub fn adapter_request_device( hub.devices.register_identity(id_in, device, &mut token) } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_adapter_request_device( adapter_id: AdapterId, desc: Option<&DeviceDescriptor>, ) -> DeviceId { let desc = &desc.cloned().unwrap_or_default(); - gfx_select!(adapter_id => adapter_request_device(adapter_id, desc, PhantomData)) + gfx_select!(adapter_id => adapter_request_device(&*GLOBAL, adapter_id, desc, PhantomData)) } -pub fn adapter_get_info(adapter_id: AdapterId) -> AdapterInfo { - let hub = B::hub(); +pub fn adapter_get_info(global: &Global, adapter_id: AdapterId) -> AdapterInfo { + let hub = B::hub(global); let mut token = Token::root(); let (adapter_guard, _) = hub.adapters.read(&mut token); let adapter = &adapter_guard[adapter_id]; adapter.raw.info.clone() } -#[cfg(not(feature = "remote"))] -pub fn wgpu_adapter_get_info( - adapter_id: AdapterId -) -> AdapterInfo { - gfx_select!(adapter_id => adapter_get_info(adapter_id)) +#[cfg(feature = "local")] +pub fn wgpu_adapter_get_info(adapter_id: AdapterId) -> AdapterInfo { + gfx_select!(adapter_id => adapter_get_info(&*GLOBAL, adapter_id)) } diff --git a/wgpu-native/src/lib.rs b/wgpu-native/src/lib.rs index 7bdf0b759..bb6c01094 100644 --- a/wgpu-native/src/lib.rs +++ b/wgpu-native/src/lib.rs @@ -10,7 +10,10 @@ pub mod backend { pub use gfx_backend_empty::Backend as Empty; #[cfg(any(target_os = "ios", target_os = "macos"))] pub use gfx_backend_metal::Backend as Metal; - #[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 = "gfx-backend-vulkan" + ))] pub use gfx_backend_vulkan::Backend as Vulkan; } @@ -29,15 +32,15 @@ mod track; pub use self::binding_model::*; pub use self::command::*; pub use self::device::*; -#[cfg(feature = "remote")] +#[cfg(not(feature = "local"))] pub use self::hub::{Access, IdentityManager, Registry, Token}; pub use self::id::*; pub use self::instance::*; pub use self::pipeline::*; pub use self::resource::*; pub use self::swap_chain::*; -pub use hal::pso::read_spirv; pub use hal::adapter::AdapterInfo; +pub use hal::pso::read_spirv; use std::{ os::raw::c_char, diff --git a/wgpu-native/src/resource.rs b/wgpu-native/src/resource.rs index f9795157e..4ad358cd4 100644 --- a/wgpu-native/src/resource.rs +++ b/wgpu-native/src/resource.rs @@ -288,7 +288,6 @@ pub struct TextureView { pub(crate) extent: hal::image::Extent, pub(crate) samples: hal::image::NumSamples, pub(crate) range: hal::image::SubresourceRange, - #[cfg_attr(feature = "remote", allow(dead_code))] pub(crate) life_guard: LifeGuard, } diff --git a/wgpu-native/src/swap_chain.rs b/wgpu-native/src/swap_chain.rs index 3846869db..666ade328 100644 --- a/wgpu-native/src/swap_chain.rs +++ b/wgpu-native/src/swap_chain.rs @@ -34,8 +34,7 @@ use crate::{ conv, - gfx_select, - hub::{GLOBAL, GfxBackend, Token}, + hub::{GfxBackend, Global, Token}, resource, DeviceId, Extent3d, @@ -46,15 +45,12 @@ use crate::{ SwapChainId, TextureViewId, }; +#[cfg(feature = "local")] +use crate::{gfx_select, hub::GLOBAL}; -use hal::{ - self, - device::Device as _, - queue::CommandQueue as _, - window::PresentationSurface as _, -}; +use hal::{self, device::Device as _, queue::CommandQueue as _, window::PresentationSurface as _}; -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] use std::marker::PhantomData; const FRAME_TIMEOUT_MS: u64 = 1000; @@ -88,7 +84,11 @@ pub struct SwapChainDescriptor { } impl SwapChainDescriptor { - pub(crate) fn to_hal(&self, num_frames: u32, features: &Features) -> hal::window::SwapchainConfig { + pub(crate) fn to_hal( + &self, + num_frames: u32, + features: &Features, + ) -> hal::window::SwapchainConfig { let mut config = hal::window::SwapchainConfig::new( self.width, self.height, @@ -129,13 +129,14 @@ pub struct SwapChainOutput { } pub fn swap_chain_get_next_texture( + global: &Global, swap_chain_id: SwapChainId, view_id_in: Input, ) -> SwapChainOutput { - let hub = B::hub(); + let hub = B::hub(global); let mut token = Token::root(); - let (mut surface_guard, mut token) = GLOBAL.surfaces.write(&mut token); + let (mut surface_guard, mut token) = global.surfaces.write(&mut token); let surface = &mut surface_guard[swap_chain_id.to_surface_id()]; let (device_guard, mut token) = hub.devices.read(&mut token); let (mut swap_chain_guard, mut token) = hub.swap_chains.write(&mut token); @@ -153,12 +154,8 @@ pub fn swap_chain_get_next_texture( log::warn!("acquire_image() failed ({:?}), reconfiguring swapchain", e); let desc = sc.desc.to_hal(sc.num_frames, &device.features); unsafe { - suf - .configure_swapchain(&device.raw, desc) - .unwrap(); - suf - .acquire_image(FRAME_TIMEOUT_MS * 1_000_000) - .unwrap() + suf.configure_swapchain(&device.raw, desc).unwrap(); + suf.acquire_image(FRAME_TIMEOUT_MS * 1_000_000).unwrap() } } } @@ -191,50 +188,50 @@ pub fn swap_chain_get_next_texture( let (view_id, _) = hub.texture_views.new_identity(view_id_in); hub.texture_views.register(view_id, view, &mut token); - assert!(sc.acquired_view_id.is_none(), "Swap chain image is already acquired"); + assert!( + sc.acquired_view_id.is_none(), + "Swap chain image is already acquired" + ); sc.acquired_view_id = Some(Stored { value: view_id, ref_count, }); - SwapChainOutput { - view_id, - } + SwapChainOutput { view_id } } -#[cfg(not(feature = "remote"))] +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_swap_chain_get_next_texture(swap_chain_id: SwapChainId) -> SwapChainOutput { - gfx_select!(swap_chain_id => swap_chain_get_next_texture(swap_chain_id, PhantomData)) + gfx_select!(swap_chain_id => swap_chain_get_next_texture(&*GLOBAL, swap_chain_id, PhantomData)) } -pub fn swap_chain_present(swap_chain_id: SwapChainId) { - let hub = B::hub(); +pub fn swap_chain_present(global: &Global, swap_chain_id: SwapChainId) { + let hub = B::hub(global); let mut token = Token::root(); - let (mut surface_guard, mut token) = GLOBAL.surfaces.write(&mut token); + let (mut surface_guard, mut token) = global.surfaces.write(&mut token); let surface = &mut surface_guard[swap_chain_id.to_surface_id()]; let (mut device_guard, mut token) = hub.devices.write(&mut token); let (mut swap_chain_guard, mut token) = hub.swap_chains.write(&mut token); let sc = &mut swap_chain_guard[swap_chain_id]; let device = &mut device_guard[sc.device_id.value]; - let view_id = sc.acquired_view_id + let view_id = sc + .acquired_view_id .take() .expect("Swap chain image is not acquired"); let (view, _) = hub.texture_views.unregister(view_id.value, &mut token); let (image, framebuffer) = match view.inner { resource::TextureViewInner::Native { .. } => unreachable!(), - resource::TextureViewInner::SwapChain { image, framebuffer, .. } => (image, framebuffer), + resource::TextureViewInner::SwapChain { + image, framebuffer, .. + } => (image, framebuffer), }; let err = unsafe { let queue = &mut device.queue_group.queues[0]; - queue.present_surface( - B::get_surface_mut(surface), - image, - Some(&sc.semaphore), - ) + queue.present_surface(B::get_surface_mut(surface), image, Some(&sc.semaphore)) }; if let Err(e) = err { log::warn!("present failed: {:?}", e); @@ -247,7 +244,8 @@ pub fn swap_chain_present(swap_chain_id: SwapChainId) { } } +#[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_swap_chain_present(swap_chain_id: SwapChainId) { - gfx_select!(swap_chain_id => swap_chain_present(swap_chain_id)) + gfx_select!(swap_chain_id => swap_chain_present(&*GLOBAL, swap_chain_id)) } diff --git a/wgpu-remote/Cargo.toml b/wgpu-remote/Cargo.toml index a7ae1db2b..2dff45aae 100644 --- a/wgpu-remote/Cargo.toml +++ b/wgpu-remote/Cargo.toml @@ -14,7 +14,7 @@ crate-type = ["lib", "cdylib", "staticlib"] default = [] [dependencies] -wgpu-native = { path = "../wgpu-native", version = "0.3", features = ["remote"] } +wgpu-native = { path = "../wgpu-native", version = "0.3", features = ["serde"] } ipc-channel = "0.12" log = "0.4" parking_lot = { version = "0.9" } diff --git a/wgpu-remote/src/lib.rs b/wgpu-remote/src/lib.rs index 67a42b8b9..39823542d 100644 --- a/wgpu-remote/src/lib.rs +++ b/wgpu-remote/src/lib.rs @@ -9,7 +9,6 @@ use wgn::{AdapterId, Backend, DeviceId, IdentityManager, SurfaceId}; use crate::server::Server; use ipc_channel::ipc; -use log::error; use parking_lot::Mutex; use serde::{Deserialize, Serialize}; @@ -124,7 +123,7 @@ pub extern "C" fn wgpu_initialize() -> Infrastructure { } } Err(e) => { - error!("WGPU initialize failed: {:?}", e); + log::error!("WGPU initialize failed: {:?}", e); Infrastructure { client: ptr::null_mut(), server: ptr::null_mut(), diff --git a/wgpu-remote/src/server.rs b/wgpu-remote/src/server.rs index fe743de83..a909cb7ed 100644 --- a/wgpu-remote/src/server.rs +++ b/wgpu-remote/src/server.rs @@ -23,7 +23,8 @@ enum ControlFlow { Terminate, } -fn process(message: GlobalMessage) -> ControlFlow { +fn process(_message: GlobalMessage) -> ControlFlow { + /* match message { GlobalMessage::RequestAdapter(ref desc, ref ids) => { wgn::request_adapter(desc, ids); @@ -33,7 +34,7 @@ fn process(message: GlobalMessage) -> ControlFlow { wgn::gfx_select!(adapter_id => fun(adapter_id, desc, id)); } GlobalMessage::Terminate => return ControlFlow::Terminate, - } + }*/ ControlFlow::Continue }